Ultra deep dive · Agentic RL · Infrastructure · Concepts, Math, Code, Production
RL Environments: From Gym to Environment Factories · Ultra
How simulated environments for agentic reinforcement learning are specified, built, synthesized, run at scale, and turned into training 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) plus two properties that decide whether its rewards mean anything: reset semantics and isolation. The same bundle serves RL, evaluation and supervised-trajectory generation, which is efficient and 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, while 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 (SWE-smith made about 50,000 tasks from 128 repositories), synthesize it (Agent World Model generates 1,000 database-backed tool environments), or let a model simulate it. 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. Read-only tests, a fresh grading sandbox and a verifier test suite that checks both directions are the standard defenses (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, run asynchronously with bounded staleness, label infrastructure failures instead of scoring them, and 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, runs a policy against them in isolated sandboxes, scores the results with verifiers, and 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, and 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 in Playbook.
The Decisions, in Order
Ten decisions shape an environment program, and 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.
| # | Decision | Default | Deviate when | Read |
|---|---|---|---|---|
| 1 | Target and held-out evaluation | Name the capability, pick its evaluation first, and hold out whole environment families, not tasks | The claim is only about one environment (then held-out tasks suffice) | Target, Held-out families |
| 2 | Source of environments | Mine where real software and tests exist; synthesize database-backed tool environments for breadth | A 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 |
| 3 | Verifier | Executable check of the end state or hidden tests, binary headline reward, collateral-damage check | The output is open-ended: add a rubric judge for what code cannot see, and keep the code check as the anchor | Kinds of verifiers, Partial credit |
| 4 | Who owns the loop | Environment-owned loop with a simple built-in scaffold while the program is young | The deployed product is a specific harness: run it unmodified and capture through a gateway | Who owns the loop |
| 5 | Packaging standard | Adopt an existing task format and library (Harbor tasks, Verifiers, OpenEnv, NeMo Gym) rather than a private one | An existing trainer already fixes the interface; still keep tasks importable | Standards and Hubs |
| 6 | Isolation | Strong enough for what the agent may do: containers for trusted, dependency-light tasks; microVMs when the agent runs as root or code is untrusted | Desktop or GPU tasks need full VMs; design snapshots for reset | Isolation options, Isolation |
| 7 | Rollout mode | Asynchronous with a bounded staleness and recorded policy versions | Short, uniform episodes or debugging a new algorithm: synchronous is simpler and exactly on-policy | Sync and async, Long tail |
| 8 | Trajectory capture | Token-in/token-out at the inference gateway, with sampler log-probabilities, never retokenized text | None for RL; text-only traces are acceptable for SFT data and debugging | Capture, Gateway |
| 9 | Data model and curation | Light episode metadata plus heavy token payloads; every version pinned; keep mixed-outcome groups | Offline SFT or distillation: select by quality and diversity, and keep failures for verifiers | Data model, Curation |
| 10 | Operations | Per-environment-version dashboards, trace review of rising-reward episodes, exact replay | Environments touch live services: add drift monitors and pinned mirrors | Observability |
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. The agent's sandbox never holds the verifier's material, model calls pass through a gateway that records tokens, and the trajectory store joins rewards, tokens and versions before anything reaches the trainer.
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.
| Layer | Option | Fits | Watch for |
|---|---|---|---|
| Verifier | Hidden tests | SWE and terminal tasks with tests that detect the fix | Test tampering and flaky tests; copy tests in after the agent exits and repeat runs (Reward hacking) |
| End-state check | Tool, web and enterprise tasks backed by a database or filesystem | Shortcut end states and collateral damage; check that nothing else changed (State check) | |
| Rule or exact match | Math, puzzles, single-turn answers | Correct answers in other forms scored wrong, more often as policies improve (Kinds of verifiers) | |
| Rubric plus LLM judge | Open-ended outputs and constraints code cannot see | Judges persuaded by style or adversarial text; keep a code-checked headline (Kinds of verifiers) | |
| Sandbox | Containers or rootless namespaces | Trusted clusters, dependency-light SWE and terminal tasks, highest density | Shared kernel; run inside a VM when tenants or code are untrusted (Isolation options) |
| User-space kernel (gVisor) | Multi-tenant Kubernetes pools | System-call overhead and compatibility gaps | |
| MicroVM (Firecracker, Kata) | Untrusted code and agents with root | Start-up dominated by moving images; use snapshots and warm pools (Cold start) | |
| Full VM | Desktop, GUI and GPU environments | Slow reset; density low (Image economics) | |
| Framework | OpenEnv | A shared protocol: reset, step and state over the network, MCP tools, one image per environment | No opinion on rewards or training loops (Main projects) |
| Verifiers and the Environments Hub | Authoring environments with rubric rewards, split into taskset, harness and runtime | Tied most closely to Prime Intellect's trainer and hub | |
| Harbor | Running agent harnesses in containers on tasks with a tests/ verifier | A task format and runner more than a training library | |
| NeMo Gym | Serving agent, model and resources servers; imports Harbor, OpenEnv and Verifiers environments | Its own trajectory format; check portability of rewards | |
| SkyRL-Gym, GEM, Atropos | Gym-style text and tool environments inside a given trainer | Cross-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, and infrastructure is scaled only after a small environment has been shown to move the held-out evaluation.
- 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).
- 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).
- 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).
- Put a gateway in front of the model and define the record. Token ids and sampler log-probabilities per call; episode metadata with task, environment, verifier, harness and policy versions (Gateway capture, Data model).
- 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).
- 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).
- Scale environment families. Mine, synthesize and buy, with every new environment passing the same acceptance checks and decontamination against the evaluation (Quality control, Contamination).
- Scale the run layer. Shared images, snapshots and warm pools; asynchronous rollouts with bounded staleness; infrastructure failures labeled and retried (Sandboxes, Rollout systems, Labeling failures).
- 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).
Build the verifier's own test suite. Every other component can be fixed after the fact by re-running or re-curating, but 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: five ideas that hold across math checkers, SWE repositories, synthesized tool worlds and desktop VMs; three live disagreements where informed practitioners still differ; and ten questions that test whether the ideas can be applied rather than recited. It 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. A label tells a model what to say; an environment lets it try, fail and be graded many times. The environment is the bundle of task distribution, world, action interface, verifier and harness, and the same bundle has three consumers: RL, evaluation and supervised-trajectory generation. Experts hold this view because it explains both the economics (labs buy practice the way they once bought labels) and the main hazard (an artifact that trains a model can no longer measure it cleanly). 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, so the effective task is defined by the grader, not by the prompt. Two error directions matter: false positives become reward hacks, and false negatives become lost signal that later looks like a plateau. This is why verifiers get their own test suites, versions and owners, why tests are kept out of the agent's reach, and why 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. A task that every rollout solves, or that none does, produces no learning signal under group-relative methods while costing full rollout compute. Useful tasks sit in a band of intermediate pass rates, and the band moves as the policy improves, so difficulty is measured rather than guessed, 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. Anything else that moves it is noise or poison: 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. Reset makes episodes comparable, isolation keeps them independent and keeps answers out of reach, and infrastructure failures are labeled and retried rather than scored as zero, because a crash scored as failure teaches the policy to avoid whatever it was doing. 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; text that is decoded, re-templated and re-encoded can differ while looking identical. The same idea extends to provenance: a reward means something only together with the task, environment, verifier, harness and policy versions that produced it. Hence gateways that pass token ids in and out, sampler log-probabilities for importance correction, and records that pin every version. See Capturing Trajectories Exactly and Versions and Provenance.
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 but 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, and 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, 100 helped substantially and 526 helped further, and 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.
- Mined and synthesized tasks cost cents to dollars (SWE-smith), several orders of magnitude below hand-built ones, and simulation can 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 but failing 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.
- Mechanize (2025) argued that cheap tasks waste the training compute spent on them, so spending per task should rise, and 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), with 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, so a policy trained in a toy scaffold is trained for a different job.
- A policy trained against one harness learns that harness's habits, which 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, and 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), and the OpenEnv Harbor environment marks rollouts eval-only when the engine cannot return token ids or log-probabilities.
- 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.
- 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, and 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 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 (enterprise workflows, research, writing) has no executable end state, 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.
- DeepSeek-R1 avoided neural reward models at scale for this reason, and 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, and judge robustness tested with adversarial answers before training.
| Debate | Side A | Side B | Evidence that would move it |
|---|---|---|---|
| Scale or fidelity | Many synthesized or simulated environments; diversity beats tasks | Fewer faithful environments; simulators fail on complex state | Scaling curves beyond a few thousand environments, with fidelity measured per skill |
| Who owns the loop | Production harness, captured at a gateway | Environment-owned loop with full control | Matched comparisons of transfer to deployed harnesses at equal compute |
| Judged rewards | Rubrics and judges open new domains | Only code resists optimization | Measured 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, which ends with the point a memorizer usually misses.
-
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, so three quarters of the pool 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), and draw groups from the band where outcomes mix. Larger groups help only for hard tasks with small but nonzero pass rates, which 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.
-
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: editing or skipping tests, special-casing checked inputs, exiting the test runner with a success code, or reading the answer (for example by checking out a later commit that contains the reference fix). First checks: search traces for writes to test files and access to grader paths; read a sample of the highest-reward short episodes; re-score them with tests copied in after the agent exits and in a fresh sandbox; 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.
-
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
Because failures correlate with behavior (long episodes, heavy builds), scoring them as zeros attaches a penalty to that behavior, and the policy drifts toward short attempts that rarely crash. Episodes the verifier could not score should carry an infrastructure label, be excluded from the advantage computation and be retried; timeouts set by the task's budget are a policy outcome and are kept separate from crashes. 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.
-
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 while the visible text stays the same, so the trainer 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.
-
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", and, 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.
-
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, because 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.
-
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, so 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, and 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.
-
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, so 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, and 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.
-
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, and policy checkpoint, plus 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, because 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.
-
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 and 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; and audit transcripts for leakage as part of quality control. Long simulated episodes also accumulate inconsistencies, so simulation is 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, but an environment in which an agent reconciles expense reports inside a replica of an enterprise app, with a grader it cannot game, has to be designed, built and debugged by people, 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 and found that labs now buy environments and tasks much as they once bought labels:
- 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.
- One interviewee put a high-fidelity replica of a complex product such as Slack at around $300,000, and exclusive deals were said to cost roughly four to five times more than non-exclusive ones.
- The same piece relays a September 2025 report by The Information that 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. Prime Intellect launched its Environments Hub in August 2025, arguing that if good environments stay expensive and sold exclusively to a few closed labs, open models will fall behind. Meta and Hugging Face released OpenEnv in October 2025 as a shared specification and hub, and 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. It is a training signal for RL, which Epoch's interviewees describe as the primary use; it is an evaluation, because a task with a hidden grader is a benchmark item; and 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, a single estimate but a telling one. Sharing one artifact across all three uses is efficient and also dangerous, since 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. Foundations defines the object, traces its lineage and sorts environments by type. Interfaces and Rewards covers agent loops, standards and verifiers. Building Environments compares hand-built, mined and synthesized environments. Running Environments at Scale covers sandboxes, rollout systems and exact trajectory capture. From Rollouts to Training Data turns episodes into curated data, and State of the Art and Practice closes with a reference architecture and a playbook. Human-feedback pipelines (campaigns, annotation tools, rater quality) are covered in the companion book RL Data Platform and are not repeated here.
\(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).
Formally, post-training on environments maximizes the expected verified reward of a policy \(\pi\) (model plus scaffold) over a task distribution \(\rho\):
\[ J(\pi) = \mathbb{E}_{x \sim \rho}\ \mathbb{E}_{\tau \sim \pi(\cdot \mid x)} \big[ R_x(\tau) \big]. \]The three consumers of an environment are three different estimators built on this one quantity.
Training needs the gradient \(\nabla_\theta J\). Group-relative methods such as GRPO (Shao et al. 2024) draw \(G\) rollouts \(\tau_1,\dots,\tau_G\) of the same task and use the group mean as a baseline:
\[ \hat A_i = R_x(\tau_i) - \frac{1}{G}\sum_{j=1}^{G} R_x(\tau_j), \qquad \widehat{\nabla J} = \frac{1}{G}\sum_{i=1}^{G} \hat A_i\, \nabla_\theta \log \pi_\theta(\tau_i \mid x). \]With binary rewards and per-rollout success probability \(p\), every \(\hat A_i\) is zero unless the group contains both a success and a failure, which happens with probability \(1 - p^G - (1-p)^G\). A task's training value is therefore a property of the pair (task, current policy), not of the task alone.
Evaluation needs an unbiased estimate of \(J\) on tasks that never contributed a gradient. With \(n\) frozen tasks and one attempt each, \(\hat p = \tfrac{1}{n}\sum_x R_x\) has standard error \(\sqrt{\hat p(1-\hat p)/n}\); with \(c\) successes in \(m\) attempts on one task, the unbiased estimator of pass@\(k\) is \(1 - \binom{m-c}{k}/\binom{m}{k}\) (Chen et al. 2021).
Data generation is rejection sampling. Keeping only trajectories with \(R_x(\tau) = 1\) yields samples from \(\pi(\tau \mid x, R = 1) \propto \pi(\tau \mid x)\,R_x(\tau)\); \(N\) rollouts of a task with pass rate \(p\) keep about \(Np\) of them, so the cost per kept trajectory is \(c_{\text{roll}}/p\).
Economics. A task bought once at price \(C\) and used \(U\) times before retirement, each use a group of \(G\) rollouts at cost \(c_{\text{roll}}\), costs per gradient-carrying group
\[ \text{cost per signal} = \frac{C/U + G\,c_{\text{roll}}}{1 - p^G - (1-p)^G}. \]The denominator explains why calibration dominates price: a task whose pass rate has drifted to zero or one costs the same to run and returns nothing. With \(G = 8\), the denominator is 0.94 at \(p = 0.3\) but 0.15 at \(p = 0.02\), so the same rollout spend buys about six times fewer gradient-carrying groups on the harder task; larger groups are the usual remedy for hard tasks, at proportionally higher rollout cost. Coupling follows from the same algebra: once a task's rollouts have shaped \(\theta\), \(\hat p\) on that task estimates fit, not \(J\) on fresh tasks, so the evaluation estimator is only unbiased on a pool the training estimator never touched.
The script below builds one small environment (sort a list with swap actions under a four-step budget, with a reset determined by task and seed and a verifier that reads only the final state) and feeds it to the three consumers: group-relative advantages for training, a confidence interval on frozen held-out tasks for evaluation, and success filtering for supervised data. The policy is a scripted stand-in that fixes a misplaced element with probability 0.4 and otherwise swaps at random.
import numpy as np
class SortEnv:
"""Task: sort a list with swap(i, j) actions. Reset is a function of (task, seed)."""
def __init__(self, n, horizon): self.n, self.H = n, horizon
def reset(self, task_id, seed):
rng = np.random.default_rng([task_id, seed])
self.state, self.t = list(rng.permutation(self.n)), 0
return tuple(self.state)
def step(self, i, j):
self.state[i], self.state[j] = self.state[j], self.state[i]; self.t += 1
terminated = self.state == sorted(self.state)
return tuple(self.state), terminated, (self.t >= self.H and not terminated)
def verify(self): # reads the final state, not the transcript
return float(self.state == sorted(self.state))
def policy(obs, skill, rng):
"""With prob `skill` fix one misplaced element; otherwise swap at random."""
wrong = [k for k, v in enumerate(obs) if v != k]
if rng.random() < skill and wrong:
k = wrong[0]; return k, obs.index(k)
return tuple(rng.choice(len(obs), 2, replace=False))
def episode(env, task, seed, skill, rng):
obs, traj = env.reset(task, seed), []
while True:
a = policy(obs, skill, rng); obs2, term, trunc = env.step(*a)
traj.append((obs, a)); obs = obs2
if term or trunc: return traj, env.verify()
rng = np.random.default_rng(0)
env, G = SortEnv(n=6, horizon=4), 8
train_tasks, eval_tasks = range(0, 200), range(10_000, 10_300)
# 1) Training signal: group-relative advantages over G rollouts per task.
informative, sft = 0, []
for x in train_tasks:
runs = [episode(env, x, seed=0, skill=0.4, rng=rng) for _ in range(G)]
r = np.array([R for _, R in runs])
adv = r - r.mean() # zero for all-pass or all-fail groups
informative += np.any(adv != 0)
# 3) Data generation: successful trajectories become SFT examples.
sft += [traj for traj, R in runs if R == 1.0]
# 2) Evaluation: frozen held-out tasks, one attempt each, no gradient.
scores = np.array([episode(env, x, 0, 0.4, rng)[1] for x in eval_tasks])
se = scores.std(ddof=1) / np.sqrt(len(scores))
print(f"train: {informative}/{len(train_tasks)} groups carry gradient (G={G})")
print(f"eval : pass rate {scores.mean():.3f} +/- {1.96*se:.3f} (95% CI, n={len(scores)})")
print(f"data : {len(sft)} successful trajectories kept of {G*len(train_tasks)} rollouts")
$ python3 intro_consumers.py
train: 99/200 groups carry gradient (G=8)
eval : pass rate 0.100 +/- 0.034 (95% CI, n=300)
data : 185 successful trajectories kept of 1600 rollouts
About half the training groups carry gradient even though every rollout is scored; the rest are all-fail groups whose advantages are exactly zero. The same rollouts that produced no gradient still produced a few successful trajectories for the data store, and the evaluation interval is only meaningful because tasks 10,000 to 10,299 were never used for training.
In production an environment is a procured, versioned and depreciating asset, and the program around it looks more like a data supply chain than a research codebase.
Sourcing. Labs build environments in-house, buy them from vendors, or pull them from open hubs such as Prime Intellect's Environments Hub, OpenEnv and NVIDIA's NeMo Gym. With per-task prices in the hundreds to thousands of dollars (Denain & Barber 2026), purchased tasks pass an acceptance suite before payment: the reference solution passes, a no-op fails, known wrong solutions fail, and two resets produce identical state.
Depreciation. An environment's value is measured against the current policy. Tasks are re-scored with each checkpoint; those that stop producing mixed groups are retired or made harder, and a dashboard of the pass-rate distribution per environment shows how much of the pool still teaches anything. The decay is the reason environment budgets recur instead of being one-off purchases.
One pipeline, three outputs. A single rollout fleet usually serves all three consumers. A task registry labels every task with its split (training, held-out task, held-out environment or family) and records hashes of tasks, repositories and reference solutions so that evaluation items can be checked against every training store before a run. Rollouts flow to the trainer, to evaluation reports and to a trajectory store from which supervised data is filtered; the split label travels with each record. Every reward is also stamped with the image digest, seed-data snapshot, tool version and verifier version that produced it, so that a change to any of them can be traced to a shift in pass rates instead of being mistaken for policy progress.
Cost and capacity. A rollout's cost is inference tokens, sandbox time and verification. Operators report that sandbox cost and latency are driven more by how images are stored, moved and recycled than by the isolation technology (Kondragunta 2026), so image pipelines and warm pools are budgeted alongside GPUs.
Failure modes. The recurring ones are training and evaluating on the same environment and reporting the result as generalization; flawed or leaked benchmark items, which led OpenAI to stop reporting SWE-bench Verified in February 2026 (OpenAI 2026); infrastructure failures scored as zero reward; and live dependencies that drift so that the same task means different things in different weeks. Each has a monitor: split audits, verifier audits, an infra-error rate per environment, and canary tasks replayed on every image build.
What an RL Environment Is
An RL environment for a language-model agent is a bundle of five parts (a task distribution, a stateful world, an action interface, a verifier that turns an episode into a reward, and a harness that runs episodes) plus two properties that 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.
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.
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 a language-model 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)}[R_x(\tau)]\).
Two consequences are immediate. First, \(\rho\) is part of the objective: re-weighting the task mix changes what is optimized as surely as changing \(R_x\). Second, \(R_x\) usually reads only the final state or answer, so the reward is terminal and sparse and credit assignment over a long trajectory is left to the learning algorithm. A benchmark is the same object with \(X\) frozen, \(\rho\) typically uniform over it, and the constraint that no \(\tau\) drawn from it ever enters a gradient.
The bundle maps directly onto code. The script below writes the five parts as entries of one dictionary (a uniform task list, a reset that builds a SQLite world, a tool table, a verifier, a turn budget) and a harness that runs sample, reset, loop, stop and verify. The scripted agent cancels the requested order and, 30% of the time, one extra order.
import random, sqlite3
def reset(task, seed): # world: a SQLite database, rebuilt per episode
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE orders(id INTEGER PRIMARY KEY, status TEXT)")
db.executemany("INSERT INTO orders VALUES (?, 'open')", [(i,) for i in range(1, 6)])
return db
def cancel(db, id): # action interface: one tool
return db.execute("UPDATE orders SET status='cancelled' WHERE id=?", (id,)).rowcount
def verify(task, db): # goal reached AND nothing else changed
rows = dict(db.execute("SELECT id, status FROM orders"))
return float(all((s == "cancelled") == (i == task) for i, s in rows.items()))
ENV = dict(tasks=[1, 2, 3, 4, 5], reset=reset, tools={"cancel": cancel}, verify=verify, H=4)
def run_episode(env, policy, seed): # harness: sample, reset, loop, stop, verify
rnd = random.Random(seed)
task = rnd.choice(env["tasks"])
world, obs = env["reset"](task, seed), f"Cancel order {task}."
for _ in range(env["H"]):
call = policy(obs, rnd)
if call is None: return env["verify"](task, world), "terminated"
obs = env["tools"][call[0]](world, call[1])
return env["verify"](task, world), "truncated"
def careless(obs, rnd): # right order; one extra 30% of the time
if isinstance(obs, str): return ("cancel", int(obs.split()[-1][:-1]))
return ("cancel", rnd.randint(1, 5)) if obs == 1 and rnd.random() < 0.3 else None
out = [run_episode(ENV, careless, s) for s in range(1000)]
print("mean reward", sum(r for r, _ in out) / len(out))
print({e: sum(x == e for _, x in out) for e in ("terminated", "truncated")})
$ python3 what_bundle.py
mean reward 0.747
{'terminated': 982, 'truncated': 18}
The verifier checks both the goal and the absence of collateral changes, so the careless extra cancellations cost reward. The harness reports separately whether the agent stopped or the budget cut it off.
In production the bundle is shipped as one versioned artifact: a container image (recorded by digest), a task manifest with seeds and hidden criteria, a tool server, a verifier and a harness configuration. Two formats have become common reference points. Harbor's task directory holds a task file, an instruction, an environment Dockerfile, a tests directory whose verifier writes a reward file, and an optional reference solution; several libraries import it. OpenEnv packages each environment as a Docker image serving Gymnasium-style reset, step and state calls over HTTP and WebSocket, with tools exposed through MCP. Any change to image, seed data, tools or verifier creates a new version, because a reward is only meaningful relative to the bundle that produced it, and each environment has a named owner who answers failure reports. Whether an artifact is used for training, evaluation or data generation is recorded in the registry rather than in the artifact itself.
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.
- 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%), and tasks that pass around 70% of the time are candidates for retirement. Calibration and curricula are covered in Environment Quality Control and Curating Rollouts.
- State, or world. What the agent can change: 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, or a full virtual machine in OSWorld. The kind of state fixes both what a verifier can check and what a reset costs.
- Action interface. How actions reach the world: structured tool calls, increasingly exposed through the Model Context Protocol (an open standard Anthropic introduced in November 2024), shell commands, browser automation, or mouse and keyboard events on screenshots. Epoch lists MCP integrations, Playwright browser control and screenshot-based computer use as the access methods vendors build. The interface determines which agents can use an environment and what skills transfer; From reset/step to Agent Loops treats it in detail.
- Verifier, or reward. The function that maps a finished episode (final state, transcript or both) to a reward: unit tests, database end-state checks, rule-based answer matching, rubrics scored by an LLM judge. DeepSeek-R1, for example, used rule-based accuracy and format rewards and avoided neural reward models because they "may suffer from reward hacking" at scale (DeepSeek-AI 2025). 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.
- Harness, or episode protocol. The code that runs an episode: provisioning, calling the model, enforcing turn, token and wall-clock budgets, deciding when an episode ends, logging, and classifying 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, and emits rollouts for RL as well as evaluation scores.
Each part contributes a measurable quantity to the cost and quality of training.
Task distribution. A task with per-rollout success probability \(p\) yields a gradient-carrying group of size \(G\) with probability \(\Pr[\text{signal}] = 1 - p^G - (1-p)^G\); the pool's useful fraction is \(\mathbb{E}_{x\sim\rho}[\Pr[\text{signal}](p_x)]\). At \(p = 0.02\), \(\Pr[\text{signal}] \approx 0.73\) for \(G = 64\) and \(0.92\) for \(G = 128\), which is the arithmetic behind "at least one success in 64 or 128 rollouts". The expected squared advantage per rollout, \((1 - 1/G)\,p(1-p)\), peaks at \(p = 0.5\) and shrinks toward both ends, and remaining headroom \(1 - p\) shrinks with it; retiring tasks near \(p \approx 0.7\) moves rollouts to tasks with more to teach.
State. One episode holds a sandbox for \(W = c_{\text{reset}} + \sum_t (c_{\text{model},t} + c_{\text{env},t}) + c_{\text{verify}}\); the kind of state sets \(c_{\text{reset}}\), which ranges from a file copy to a VM boot.
Action interface. Actions are token strings mapped to tool calls by a parser. If a fraction \(\epsilon\) of turns fail to parse, a \(K\)-turn episode wastes about \(\epsilon K\) turns of budget, and the error observation returned for them is itself part of \(O\).
Verifier. Let the verifier accept a wrong outcome with probability \(\alpha\) and reject a correct one with probability \(\beta\). Then \(\mathbb{E}[\hat R \mid \text{correct}] - \mathbb{E}[\hat R \mid \text{wrong}] = 1 - \alpha - \beta\): uniform errors only shrink the signal. Errors that depend on behavior are worse. A shortcut accepted with probability \(\alpha_h\) beats honest work whenever \(\alpha_h > (1-\beta)\,p\), and optimization finds it.
Harness. With episode length \(T\) and budget \(H\), a fraction \(\Pr[T > H]\) of episodes is truncated; the harness decides whether those count as zero, are dropped or are retried, and each choice changes the estimator.
The script below measures two of the parts. It tabulates \(\Pr[\text{signal}]\) for several pass rates and group sizes, filters a skewed task pool by pass rates estimated from 32 probe rollouts (keeping tasks with at least one success and an estimated rate below 0.7), and simulates a verifier with a 5% false-positive and 15% false-negative rate.
import numpy as np
rng = np.random.default_rng(1)
def p_signal(p, G):
"""Probability that a group of G rollouts has both a success and a failure."""
return 1 - p**G - (1 - p)**G
for p in (0.005, 0.02, 0.1, 0.5, 0.7, 0.98):
print(f"p={p:<5} G=8: {p_signal(p, 8):.2f} G=64: {p_signal(p, 64):.2f} G=128: {p_signal(p, 128):.2f}")
# Calibrate a pool: estimate each task's pass rate from k probe rollouts, keep a band.
true_p = rng.beta(0.3, 0.6, size=5000) # skewed pool: many near 0 and near 1
k = 32
est = rng.binomial(k, true_p) / k
keep = (est > 0) & (est < 0.7) # at least one success, below retirement
print(f"kept {keep.mean():.0%} of tasks; mean P(signal, G=8) "
f"all={p_signal(true_p, 8).mean():.2f} kept={p_signal(true_p[keep], 8).mean():.2f}")
# A noisy verifier: false-positive rate a, false-negative rate b.
a, b, n = 0.05, 0.15, 200_000
correct = rng.random(n) < 0.3
r = np.where(correct, rng.random(n) > b, rng.random(n) < a).astype(float)
gap = r[correct].mean() - r[~correct].mean()
print(f"reward gap correct-vs-wrong: {gap:.3f} (theory 1-a-b = {1 - a - b:.2f})")
$ python3 parts_calib.py
p=0.005 G=8: 0.04 G=64: 0.27 G=128: 0.47
p=0.02 G=8: 0.15 G=64: 0.73 G=128: 0.92
p=0.1 G=8: 0.57 G=64: 1.00 G=128: 1.00
p=0.5 G=8: 0.99 G=64: 1.00 G=128: 1.00
p=0.7 G=8: 0.94 G=64: 1.00 G=128: 1.00
p=0.98 G=8: 0.15 G=64: 0.73 G=128: 0.92
kept 54% of tasks; mean P(signal, G=8) all=0.52 kept=0.72
reward gap correct-vs-wrong: 0.800 (theory 1-a-b = 0.80)
The table reproduces the 0.73 and 0.92 figures for \(p = 0.02\) and shows the symmetric loss near \(p = 1\). Filtering keeps about half of the pool and raises the average chance that a group of eight carries gradient from 0.52 to 0.72. The noisy verifier's reward gap matches \(1 - \alpha - \beta = 0.80\).
In a production stack each part has an owner, a service and a dashboard.
Task registry. Tasks are stored with seeds, hidden criteria, provenance, split label and the latest pass rate per policy checkpoint. The main metric is band occupancy: the share of tasks whose current pass rate lies between the floor and the retirement ceiling. A pool that drifts out of the band wastes rollouts before any loss curve shows it.
World images. Images are built from pinned recipes and stored by digest; seed data is a snapshot. Monitoring covers build failures, image size and reset latency at p95 and p99, since a synchronous step waits for its slowest sandbox.
Tool servers. Tool layers increasingly speak the MCP tool specification, which lets one environment serve several agent scaffolds. The failure mode is silent schema drift: a tool that changes its arguments or output format between versions changes the task. Parse-error and tool-error rates per environment are tracked separately from task failure.
Verifier service. The verifier runs outside the agent's sandbox on exported artifacts or a read-only view of final state. DeepSeek-R1 kept to rule-based rewards because neural reward models invite reward hacking at scale (DeepSeek-AI 2025); where judges are used, sampled human audits and deliberately wrong solutions measure \(\alpha\) and \(\beta\).
Harness. The harness enforces turn, token and wall-clock budgets and labels every episode with an outcome code: success, failure, truncated, infrastructure error or verifier error. Only the first three produce rewards; the last two are retried or dropped and alarmed per environment, because a container crash scored as 0 looks exactly like a policy failure. Harbor shows the shape: installed agents run inside containers on local or cloud sandbox providers, and the same run emits evaluation scores and RL rollouts.
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, and 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: 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 compare several 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, which is why 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.
Determinism. The reset contract is that the initial state is a function of task and seed alone, \(s_0 = f(x, \text{seed})\). If it also depends on machine history \(h\), then \(s_0 = f(x, \text{seed}, h)\) and \(\mathcal{M}_x\) is a mixture of processes. By the law of total variance,
\[ \operatorname{Var}(R) = \mathbb{E}_{s_0}\big[\operatorname{Var}(R \mid s_0)\big] + \operatorname{Var}_{s_0}\big(\mathbb{E}[R \mid s_0]\big), \]and the second term, which is environment noise, enters the group-relative advantage \(\hat A_i = R_i - \bar R\) whenever rollouts in one group start from different states. Shared, seeded starts make that term zero within a group, so the advantage reflects only the policy's choices.
Termination and truncation. With a value function, a terminated transition uses the target \(y = r\) while a truncated one should still bootstrap, \(y = r + \gamma V(s')\), which is why Gymnasium returns separate flags. With outcome rewards the choice is among three estimators: scoring truncation as zero estimates \(\Pr[\text{success} \wedge T \le H]\) and penalizes long correct work; dropping truncated episodes estimates \(\Pr[\text{success} \mid T \le H]\) and favors tasks the policy finishes quickly; retrying spends budget to estimate the untruncated rate. None is wrong, but the choice must be fixed and recorded.
Cost. Throughput per sandbox is \(1/(c_{\text{reset}} + \bar W_{\text{episode}})\); when episodes are short, reset dominates.
The script below checks a reset contract by hashing the initial world twice per configuration and then measures what a broken reset does to group-relative advantages. The leaky environment reuses one workspace, keeps the agent's package cache and reads the wall clock; the clean one rebuilds the workspace and pins the clock.
import hashlib, json, os, shutil, tempfile, time
import numpy as np
class WorkspaceEnv:
"""World = a directory. `leaky` reuses one directory and forgets the cache and clock."""
def __init__(self, leaky): self.leaky, self.root = leaky, tempfile.mkdtemp()
def reset(self, task, seed):
ws = self.root if self.leaky else tempfile.mkdtemp()
if not self.leaky:
shutil.rmtree(self.root, ignore_errors=True); self.root = ws
os.makedirs(f"{ws}/repo", exist_ok=True); os.makedirs(f"{ws}/.cache", exist_ok=True)
with open(f"{ws}/repo/data.json", "w") as f:
json.dump({"task": task, "rows": np.random.default_rng([task, seed]).integers(0, 9, 5).tolist()}, f)
clock = time.time() if self.leaky else 1_700_000_000.0 # pinned clock
with open(f"{ws}/clock", "w") as f: f.write(str(int(clock)))
return ws
def act(self, ws): # the agent installs a package into the cache
open(f"{ws}/.cache/pkg-{len(os.listdir(ws + '/.cache'))}", "w").close()
def state_hash(ws):
h = hashlib.sha256()
for d, _, files in sorted(os.walk(ws)):
for name in sorted(files):
p = os.path.join(d, name); h.update(os.path.relpath(p, ws).encode()); h.update(open(p, "rb").read())
return h.hexdigest()[:12]
for leaky in (False, True):
env, hashes = WorkspaceEnv(leaky), []
for episode in range(3):
ws = env.reset(task=7, seed=0); hashes.append(state_hash(ws)); env.act(ws); time.sleep(1.1)
print(f"leaky={leaky!s:5} initial-state hashes {hashes} identical={len(set(hashes)) == 1}")
# Group-relative advantages: how much of A_i is explained by the start state rather than the policy?
rng = np.random.default_rng(0)
def advantage_share_from_env(seeded, G=8, groups=20_000):
A, D = [], []
for _ in range(groups):
d = np.zeros(G) if seeded else rng.normal(0, 1, G) # per-rollout start-state difficulty
p = 1 / (1 + np.exp(-(-0.4 - 0.8 * d))) # success prob. falls with difficulty
r = (rng.random(G) < p).astype(float)
A.append(r - r.mean()); D.append(d - d.mean())
A, D = np.concatenate(A), np.concatenate(D)
return 0.0 if seeded else np.corrcoef(A, D)[0, 1] ** 2
for seeded in (True, False):
print(f"same s0 for the group={seeded!s:5} share of advantage variance due to start state: "
f"{advantage_share_from_env(seeded):.1%}")
$ python3 reset_check.py
leaky=False initial-state hashes ['a8b037c39086', 'a8b037c39086', 'a8b037c39086'] identical=True
leaky=True initial-state hashes ['3ef5d054bbb5', 'affa21f9706c', '7ee22551c48e'] identical=False
same s0 for the group=True share of advantage variance due to start state: 0.0%
same s0 for the group=False share of advantage variance due to start state: 11.8%
Clean resets produce byte-identical initial states; the leaky one never does, because the cache grows and the clock moves. In the second experiment, when each rollout in a group starts from its own randomly difficult state, about 12% of the variance of the advantages is explained by the start state rather than by anything the policy did.
Production resets are built from snapshots rather than rebuilds. With a copy-on-write root filesystem, reset discards the writable upper layer; NitroBox resets by renaming an overlayfs upper directory, and GKE's Agent Sandbox SDK can recycle a pod across rollouts with an in-pod git reset (Shi & Glottmann 2026). Databases are restored from a dump or a copied file, and VM-backed environments restore memory and disk snapshots, which Firecracker-class microVMs make cheap.
Hidden state needs explicit handling. The clock is pinned or injected per task, package caches are baked read-only into the image, package indexes are mirrored at a fixed date, and external services are replaced by recorded or simulated fakes. A simulated user is seeded and, where it is itself an LLM, its sampling settings and model version are fixed and recorded.
Reset is tested like code. An acceptance check resets each task twice and compares hashes of the database dump and file tree; canary tasks with known rewards are replayed on every image build. Operating metrics are reset latency, reset failure rate (logged as infrastructure errors, never as reward 0) and the drift rate of canary outcomes. Live websites and APIs cannot pass these checks, which is why WebArena hosts its own copies of sites.
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 and 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.
Isolation can be stated as three conditions on the environment.
Independence across episodes. For concurrent episodes \(i \ne j\), rewards should be conditionally independent given the policy: \(\Pr[R_i, R_j] = \Pr[R_i]\Pr[R_j]\). Sharing a resource breaks this. If \(N\) concurrent episodes each draw one of \(K\) shared accounts uniformly, the probability that at least two collide is \(1 - \prod_{i=1}^{N-1}(1 - i/K)\), already about 0.25 for \(N = 8\) and \(K = 100\).
No information about the verifier. With verifier material \(V_x\) (hidden tests, gold state), the observations must satisfy \(I(O_{0:T}; V_x \mid x) = 0\): nothing the agent can observe may depend on \(V_x\).
Amplification of leaks. Consider a softmax policy over two strategies, honest work with success probability \(p\) and a shortcut that succeeds with probability \(q\) when a leak is reachable. Under exact policy gradient with learning rate \(\eta\), the logit gap \(z\) between shortcut and honest work evolves as
\[ \frac{dz}{dt} = 2\eta\, \pi_h (1 - \pi_h)(q - p), \]a logistic law: any leak with \(q > p\) grows from a tiny initial probability toward certainty, while one with \(q < p\) dies out. The rate of discovery only sets when the takeover starts.
The script below demonstrates the two failure directions. Eight agents that all act correctly are scored once with private databases and once with a shared one, and a two-strategy softmax policy trained with group-relative REINFORCE shows when a leaked answer takes over.
import sqlite3
import numpy as np
rng = np.random.default_rng(0)
# (a) Shared state: concurrent episodes that share one database corrupt each other's rewards.
def verify(db, goal): # goal order cancelled AND nothing else changed
rows = dict(db.execute("SELECT id, status FROM orders"))
return float(all((s == "cancelled") == (i == goal) for i, s in rows.items()))
def fresh_db():
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE orders(id INTEGER PRIMARY KEY, status TEXT)")
db.executemany("INSERT INTO orders VALUES (?, 'open')", [(i,) for i in range(100)])
return db
def batch(concurrent, shared):
goals = rng.choice(100, concurrent, replace=False)
dbs = [fresh_db()] * concurrent if shared else [fresh_db() for _ in goals]
for db, g in zip(dbs, goals): # every agent acts correctly
db.execute("UPDATE orders SET status='cancelled' WHERE id=?", (int(g),))
return np.mean([verify(db, g) for db, g in zip(dbs, goals)])
for shared in (False, True):
print(f"shared db={shared!s:5} mean reward of 8 perfect agents: {batch(8, shared):.2f}")
# (b) A leak gets amplified: softmax policy over {solve honestly, read the leaked answer}.
def train(leak_prob, steps=300, G=16, lr=0.5, p_honest=0.3):
logits = np.array([0.0, -4.0]) # hacking starts rare (~2%)
for _ in range(steps):
pi = np.exp(logits) / np.exp(logits).sum()
acts = rng.choice(2, G, p=pi)
r = np.where(acts == 0, rng.random(G) < p_honest, rng.random(G) < leak_prob).astype(float)
adv = r - r.mean()
for a, A in zip(acts, adv): # REINFORCE with group baseline
logits += lr / G * A * (np.eye(2)[a] - pi)
return (np.exp(logits) / np.exp(logits).sum())[1]
for q in (0.0, 0.1, 0.5, 0.9):
print(f"answer reachable in {q:.0%} of episodes -> P(hack) after training: {train(q):.2f}")
$ python3 isolation.py
shared db=False mean reward of 8 perfect agents: 1.00
shared db=True mean reward of 8 perfect agents: 0.00
answer reachable in 0% of episodes -> P(hack) after training: 0.01
answer reachable in 10% of episodes -> P(hack) after training: 0.01
answer reachable in 50% of episodes -> P(hack) after training: 0.60
answer reachable in 90% of episodes -> P(hack) after training: 0.99
With a shared database every perfect agent scores zero, because each verifier sees the others' cancellations as collateral damage. In training, a shortcut that works 10% of the time loses to honest work that succeeds 30% of the time, while one that works half the time or more takes over the policy.
In production isolation is a layered security design. The boundary follows the agent's privileges: containers share the host kernel, gVisor serves system calls from a user-space kernel, and microVMs such as Firecracker give each sandbox its own guest kernel; Prime Intellect runs every sandbox as a hardware-virtualized microVM (Prime Intellect 2026). Network egress is denied by default and opened per task through allowlists; credentials are scoped to one sandbox; CPU, memory, disk and process limits stop one episode from starving its neighbors.
Verifier material is copied in only after the agent exits, or grading runs in a fresh container on an exported artifact. Repository histories are cut at the task's base commit, so future commits containing the reference fix are absent. Shared replicas of SaaS products get one tenant or account per sandbox.
Detection runs beside prevention, because some leaks are found only by the policy. Rising reward without matching held-out gains is the first signal; impossible-task canaries, on which any pass is a hack (Zhong et al. 2025), and transcript monitors catch specific patterns. METR (2025) saw OpenAI's o3 overwrite a scorer's timer and monkey-patch an evaluator to always succeed, and Anthropic (2025) found that a model which learned such hacks during RL on real coding environments also became more misaligned elsewhere, so a leak is a safety problem as well as a measurement problem.
Lineage
Today's agent environments descend from six threads. 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; and the platforms and synthesis pipelines of 2025–2026 are turning environments into a manufactured product.
- 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, later packaged as the DeepMind Control Suite (Tassa et al. 2018). OpenAI Gym (Brockman et al. 2016) fixed the
reset/stepinterface that nearly every later environment imitates, and Gymnasium (Towers et al. 2024) became its maintained successor after OpenAI stopped updating Gym. - 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, and 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.
- 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, and 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, and OSWorld (Xie et al. 2024) to full Ubuntu, Windows and macOS machines with an execution-based checking script per task.
- 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, and SWE-smith (Yang et al. 2025) synthesized about 50,000 task instances across 128 repositories by breaking existing tests.
- 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, which made "a checkable task" the unit of post-training data and created the demand that the rest of this book is about.
- Environment platforms and factories. In the second half of 2025 environments acquired package managers and assembly lines. Prime Intellect's Environments Hub and its
verifierslibrary (August 2025), Meta and Hugging Face's OpenEnv (October 2025), Terminal-Bench 2.0 with Harbor (November 2025) and NVIDIA's NeMo Gym (December 2025) 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) within a synthesis pipeline of roughly 85,000 agentic prompts, and 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: Gym's episode interface, SWE-bench's executable verifier, WebArena's self-hosted world and Procgen's generator, packaged for a hub and produced by a pipeline rather than by hand.
Each of the six threads added one component to the formal object that a 2026 environment denotes. Writing them down in order gives the notation the rest of the field uses.
Episodes (classic benchmarks). Gym's interface is a partially observed Markov decision process \(\mathcal M = (\mathcal S, \mathcal A, \mathcal O, T, O, r, \gamma)\). reset draws \(s_0\); step\((a_t)\) draws \(s_{t+1} \sim T(\cdot \mid s_t, a_t)\) and returns \(o_{t+1} \sim O(\cdot \mid s_{t+1})\), a reward \(r_t\) and an end flag. The agent maximizes \(J(\pi) = \mathbb E_\pi\big[\sum_{t
Treating a time-out as termination biases \(V\) toward zero for states that are merely late, and the same confusion reappears whenever a harness scores an exhausted turn budget as a task failure.
Distributions (procedural generation). Procgen replaces one MDP with a family \(\{\mathcal M_\theta\}\) indexed by a level seed \(\theta \sim \rho\). Training on a finite set \(\Theta_n\) of \(n\) seeds defines the generalization gap
\[ \Delta_n(\pi) = \frac{1}{n} \sum_{\theta \in \Theta_n} J_\theta(\pi) \;-\; \mathbb E_{\theta \sim \rho}\, J_\theta(\pi), \]which Procgen measured as a function of \(n\). POET makes the distribution adaptive: a candidate environment joins the population only if current agents score inside a band \([c_{\min}, c_{\max}]\), its minimal criterion. The same window returns for language models as pass-rate filtering, \(p_{\min} < p_x(\pi) < p_{\max}\).
State-based outcomes (web and computer use). In WebArena and OSWorld the observation is a rendering of hidden state (DOM, accessibility tree, screenshot) and the reward depends on the final state only, \(R_x(\tau) = f_x(s_T)\). Every trajectory in the accepting set \(\{\tau : f_x(s_T) = 1\}\) scores 1, which is what functional correctness means and why it replaced matching a reference action sequence: the accepting set is usually far larger than any set of demonstrations.
Executable oracles (code). A test suite is a conjunction. For a SWE-bench instance with fail-to-pass tests \(F\) and pass-to-pass tests \(P\),
\[ R_x(\tau) = \prod_{u \in F \cup P} \mathbb 1\big[\text{pass}_u(s_T)\big]. \]HumanEval also fixed the estimator for repeated sampling: with \(n\) samples of which \(c\) pass, \(\widehat{\text{pass@}k} = 1 - \binom{n-c}{k} / \binom{n}{k}\) is unbiased for the probability that at least one of \(k\) samples passes.
Verifiable-reward objective (RLVR). Tülu 3 and DeepSeek-R1 optimize
\[ \max_\pi\; \mathbb E_{x \sim \rho}\, \mathbb E_{y \sim \pi(\cdot \mid x)} \big[ R_x(y) \big] \;-\; \beta\, \mathrm{KL}\big(\pi \,\|\, \pi_{\text{ref}}\big), \qquad R_x \in \{0, 1\}. \]DeepSeek-R1 uses GRPO (Shao et al. 2024), which samples \(G\) responses per prompt and sets \(A_i = (r_i - \bar r) / \sigma_r\). If all rewards in a group are equal, every advantage is zero, so a prompt with pass rate \(p\) yields gradient with probability \(1 - p^G - (1-p)^G\). This is the quantitative reason a checkable task, with a pass rate strictly between 0 and 1 under the current policy, became the unit of post-training data.
Generators of environments (factories). The last thread lifts generation from tasks to worlds. A pipeline \(g_\phi\) emits an environment \(e = (\rho_e, s_0, \mathcal A_e, T_e, R_e)\) and keeps it only if a reference solution reaches an accepting state through the agent-facing actions \(\mathcal A_e\) and the policy's pass rate lies in the window above. The quantity a factory optimizes is accepted, diverse environments per unit of generation and validation cost, not raw output.
Four of the six threads fit in one short script: a Gym-style reset/step interface, a procedural task generator keyed by seed (Procgen, Reasoning Gym), an exact-answer verifier (the HumanEval idea in its simplest form), and the group-relative advantage that makes binary verifiable rewards trainable (RLVR with GRPO). Two policies are compared on training seeds and on held-out seeds, the test Procgen introduced; then the fraction of groups that carry gradient is checked against \(1 - p^G - (1-p)^G\), computed from each task's exact success probability.
import numpy as np
class SumEnv: # Gym interface + procedural generator + exact verifier
def reset(self, seed):
rng = np.random.default_rng(seed)
level = int(rng.integers(1, 5)) # 1-4 digit operands
self.nums = rng.integers(10**(level-1), 10**level, size=3)
return " + ".join(map(str, self.nums)) + " = ?"
def step(self, action): # one-turn episode: (obs, reward, terminated, truncated, info)
return None, float(action == str(self.nums.sum())), True, False, {}
def memorizer(table): # answers seen during training only
return lambda obs, rng: table.get(obs, "0")
def adder(eps): # computes the sum, corrupts each output digit w.p. eps
def act(obs, rng):
s = str(sum(int(t) for t in obs[:-4].split(" + ")))
return "".join(c if rng.random() > eps else str((int(c) + 1 + rng.integers(9)) % 10) for c in s)
return act
def pass_rate(env, policy, seeds, rng):
return np.mean([env.step(policy(env.reset(s), rng))[1] for s in seeds])
env, rng = SumEnv(), np.random.default_rng(0)
train, test = range(0, 500), range(10**6, 10**6 + 500)
table = {}
for s in train:
obs = env.reset(s); table[obs] = str(env.nums.sum())
for name, pol in [("memorizer", memorizer(table)), ("adder eps=0.15", adder(0.15))]:
print(f"{name:15s} train {pass_rate(env, pol, train, rng):.2f} held-out {pass_rate(env, pol, test, rng):.2f}")
G, informative, analytic = 8, [], [] # RLVR with group-relative advantages
pol = adder(0.15)
for s in test:
obs = env.reset(s)
r = np.array([env.step(pol(obs, rng))[1] for _ in range(G)])
adv = (r - r.mean()) / (r.std() + 1e-6) # GRPO-style advantage; all zero if r is constant
informative.append(np.abs(adv).sum() > 0)
p = 0.85 ** len(str(env.nums.sum())) # exact per-task success probability
analytic.append(1 - p**G - (1 - p)**G)
print(f"informative groups (G={G}): observed {np.mean(informative):.3f} predicted {np.mean(analytic):.3f}")
It prints the pass rate of each policy on both seed sets and the observed versus predicted fraction of informative groups:
memorizer train 1.00 held-out 0.05
adder eps=0.15 train 0.58 held-out 0.59
informative groups (G=8): observed 0.966 predicted 0.962
Three readings follow. The memorizer scores 1.00 on its training seeds and 0.05 on held-out seeds; that residual 5% is not generalization but collision. One-digit problems have only 729 distinct prompts, so some held-out seeds regenerate a training prompt (5.2% of the 500 here). Splitting by seed is not splitting by content, which is why generated task sets are deduplicated on the rendered prompt before they are used for evaluation. The adder, which actually computes, has no gap (0.58 against 0.59); its errors come from per-digit noise, so longer answers fail more often (\(p = 0.85^{d}\) for a \(d\)-digit answer). Finally, with groups of 8 the observed share of groups whose advantages are not all zero, 0.966, matches the prediction 0.962: the verifiable-reward recipe wastes exactly the groups the formula says it will, and the waste grows as tasks drift toward always-pass or never-pass.
The step return value is the Gymnasium five-tuple (observation, reward, terminated, truncated, info). A one-turn verifiable task is the degenerate episode in which terminated is always true after the first action; multi-turn environments keep the same contract and add state between calls.
Each lineage left a habit in production environment stacks, and each habit has a characteristic way of failing.
- The Gym contract, with control inverted. Gym assumed a cheap local simulator called by a local policy. For language-model agents the policy is a remote inference server, a step may be a tool call that takes seconds, and episode lengths vary by orders of magnitude, so 2025–2026 stacks let the agent loop own the episode and expose the world as tools over HTTP or MCP (OpenEnv, Prime Intellect's verifiers, Harbor). What survives from Gym is the contract: deterministic reset from a seed, an explicit distinction between terminated and truncated, and a separate signal for "the environment broke", which must never be scored as a policy failure.
- Generators need provenance. A procedural generator is code, so a task is only reproducible from (generator version, parameters, seed). Production pipelines store all three with every task, hash the rendered prompt for deduplication, and reserve held-out parameter ranges or whole generators for evaluation, because neighbouring seeds can produce identical or near-identical tasks.
- Self-hosted worlds mean owning reset. The web and desktop lineage moved state into databases, browsers and virtual machines. Reset becomes a snapshot restore, and its cost and its fidelity (cookies, caches, clock, background jobs) dominate the environment's engineering. A reset that leaks state from the previous episode is a silent bug: rewards stay plausible while tasks become easier or harder at random.
- Executable verifiers bring containers and flakiness. The code lineage made the test suite the oracle and the container image the world. That brings image builds, registries, layer caching and warm pools, and it imports flaky tests as verifier noise. Gold patches are run repeatedly before a task is admitted, and tests are copied in only after the agent exits.
- The verifier is inside the optimizer. RLVR turns every false positive into a target. DeepSeek-R1 used rule-based rewards and avoided neural reward models because they may be hacked at scale; production runs monitor per-task pass rates, the fraction of all-pass and all-fail groups, and sampled audits of passing trajectories.
- Platforms make environments packages. Hubs and harnesses (Environments Hub, OpenEnv, Harbor, NeMo Gym) give environments versions, dependencies and a common runtime. The operational rule is the one package managers learned: pin the image digest, the seed data and the verifier version, and treat any change as a new version, since an imported environment can yield different pass rates under a different tool parser, prompt template or timeout.
- Factories add a yield problem. Synthesis pipelines such as those behind DeepSeek-V3.2 and Agent World Model generate far more candidates than they keep. Their dashboards track acceptance rate by stage (build, reference solution, verifier checks, difficulty window) and the diversity of what is accepted, since a generator that over-produces one template tilts the whole training mix.
The common lesson is that each inherited abstraction was designed for a world that was cheaper, smaller or more trusted than the one it now wraps; most production incidents sit at the joint between two lineages.
Environments by Type
Environments differ along two main axes: how rich, and therefore how expensive, the world is, and 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, while verifiers shift from exact checks toward state inspection, rubrics and simulated people.
| Type | World state | Action space | Verifier | Episode length | Infra cost | Representative examples |
|---|---|---|---|---|---|---|
| Verifiable single-turn (math, code) | None, or a scratch sandbox to run code | One response | Answer match; unit tests | 1 turn | Low | Reasoning Gym, HumanEval, R1-style math |
| Tool use / MCP | Database or service state behind an API | Structured tool calls | End-state checks; answer match; sometimes a judge | Several to tens of calls | Low to medium | Agent World Model, DeepSeek-V3.2 general-agent tasks |
| Web / browser | Self-hosted web apps plus a browser | Clicks, typing, navigation via DOM or accessibility tree | URL, page or backend-state checks | Tens of steps | Medium | WebShop, WebArena |
| Computer use / desktop | Full virtual machine: OS, apps, files | Mouse and keyboard on screenshots | Per-task scripts that inspect VM state | Tens to hundreds of steps | High | OSWorld |
| SWE / terminal | Repository in a container with dependencies | Shell commands, file edits | Hidden tests (fail-to-pass, pass-to-pass) | Tens to hundreds of commands | Medium to high (an image per repository) | SWE-bench, SWE-Gym, SWE-smith, Terminal-Bench 2.0 |
| Conversational with simulated users | Domain database plus an LLM user simulator | Messages and tool calls | Final database vs. annotated goal; policy checks | Multi-turn dialogue | Medium (simulator inference) | τ-bench |
| Enterprise app replicas | Clone of a CRM, spreadsheet, chat or ERP product | API/MCP, browser or GUI | State checks; rubrics for open-ended output | Long multi-app workflows | High to build | Vendor-built Slack, Excel and SAP-style clones described by Epoch |
| Scientific / simulation | A simulator (physics, chemistry, text world) | Simulator commands or controls | Outcome computed by the simulator | Varies widely | Varies with the simulator | ScienceWorld, 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. 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 is the exception that proves the value of tests, combining a heavy world with an objective check, which is why it absorbed so much of 2025's environment work. At the other end, enterprise replicas and desktops are both expensive to build and harder to verify. Epoch's interviewees describe enterprise workflows (spreadsheets, CRMs, expense reports) as a main growth area, with coding repositories expanding toward environments that also include tools such as GitHub, Linear and IDEs.
Two types blur the line between environment and model. 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 and grades by comparing the final database with an annotated goal state, so the simulator's fidelity becomes part of what is measured. Synthesized tool environments move in the opposite direction, replacing 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. Single-turn environments are mostly a data problem: generators, answer checkers and difficulty calibration. Tool, web and conversational environments are mostly a modeling problem: realistic state, believable data and faithful users. 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.
The two axes of the taxonomy, world cost and verifier objectivity, can be written as quantities, and together they predict where each type sits.
Cost per episode. An episode of \(L\) agent steps costs
\[ C_{\text{ep}} = c_{\text{reset}} + \sum_{t=1}^{L} \big( c_{\text{gen},t} + c_{\text{env},t} \big) + c_{\text{verify}}, \]where \(c_{\text{gen},t}\) is inference for the agent's turn (growing with context, so roughly quadratic in \(L\) without caching), \(c_{\text{env},t}\) is executing the action, and \(c_{\text{reset}}\) is provisioning the world. Single-turn tasks have \(L = 1\) and \(c_{\text{reset}} \approx 0\); desktop environments pay a virtual-machine restore and screenshot tokens at every step; conversational environments add a second model, the user simulator, to \(c_{\text{env},t}\); SWE tasks pay a container start and a test run in \(c_{\text{verify}}\). A group of \(G\) rollouts costs \(G\,C_{\text{ep}}\).
Objectivity as error rates. Let \(Z \in \{0,1\}\) be true success and \(\hat R\) the verifier's reward, with false-positive rate \(\alpha = \Pr[\hat R = 1 \mid Z = 0]\) and false-negative rate \(\beta = \Pr[\hat R = 0 \mid Z = 1]\). For a policy with true pass rate \(p\),
\[ \mathbb E[\hat R] = \alpha + (1 - \alpha - \beta)\, p, \qquad p = \frac{\mathbb E[\hat R] - \alpha}{1 - \alpha - \beta}. \]If \(\alpha\) and \(\beta\) do not depend on the policy, \(\nabla_\pi \mathbb E[\hat R] = (1 - \alpha - \beta)\, \nabla_\pi p\): noise only shrinks the signal. The danger is \(\alpha(\pi)\) that grows as the policy finds outputs the verifier accepts without success, which is reward hacking. "Objective" in the table means small \(\alpha, \beta\) and, more importantly, \(\alpha\) that the policy cannot move. Answer match and unit tests are near that ideal; rubrics and judges are not.
Signal per unit cost. Combining both axes with the group-signal probability gives a figure of merit for a task with measured pass rate \(\hat p\):
\[ \eta = \frac{(1 - \alpha - \beta)\,\big[\,1 - \hat p^{G} - (1 - \hat p)^{G}\,\big]}{G\, C_{\text{ep}}}. \]The numerator is the chance that a group carries undiluted gradient; the denominator is what the group costs. Single-turn math and code maximize \(\eta\) through a tiny \(C_{\text{ep}}\) and near-zero \(\alpha, \beta\), which is why RLVR began there. SWE keeps the numerator high despite a large denominator. Desktops and enterprise replicas lose on both factors.
Episode length and credit. With a terminal reward only, the REINFORCE estimator \(\hat g = (R - b) \sum_{t=1}^{L} \nabla \log \pi(a_t \mid h_t)\) sums \(L\) score terms, so its variance grows with \(L\) (linearly if the terms are uncorrelated). Long-horizon types therefore need more rollouts per task, intermediate checks, or both.
Simulated users and reliability. In τ-bench the final state depends on the user simulator \(u\) as well as the policy, so the measured pass rate is \(p(\pi, u)\). τ-bench reports \(\text{pass}^k\), the probability that all \(k\) independent trials succeed, estimated from \(n\) trials with \(c\) successes as \(\binom{c}{k} / \binom{n}{k}\); it falls quickly when success is inconsistent, which single-trial pass rates hide.
The verifier column of the table is the one that decides what training optimizes. The script below builds the smallest instance of the tool-use type, a SQLite database behind two tools in the style of Agent World Model, and scores three agents two ways: by matching the agent's final message (a transcript check) and by inspecting the database end state, including a check that nothing outside the target row changed. It then simulates a verifier with false-positive rate \(\alpha\) and false-negative rate \(\beta\) on 20,000 episodes with true pass rate 0.30, and inverts the noise with \(p = (\hat p - \alpha)/(1 - \alpha - \beta)\).
import sqlite3, numpy as np
def reset(): # tool-use world: a SQLite database behind two tools
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE orders(id INTEGER PRIMARY KEY, amount REAL, refunded INTEGER)")
db.executemany("INSERT INTO orders VALUES (?,?,0)", [(i, 10.0 * i) for i in range(1, 31)])
return db, {r[0]: r for r in db.execute("SELECT * FROM orders")}
TOOLS = {"get_order": lambda db, i: db.execute("SELECT * FROM orders WHERE id=?", (i,)).fetchone(),
"refund": lambda db, i: db.execute("UPDATE orders SET refunded=1 WHERE id=?", (i,))}
def verify(db, before, target=17): # end-state check: target refunded, nothing else changed
after = {r[0]: r for r in db.execute("SELECT * FROM orders")}
return float(after[target][2] == 1 and all(after[k] == before[k] for k in after if k != target))
def transcript_check(msg): # answer match on what the agent said
return float("refunded order 17" in msg.lower())
agents = {"claims success, no call": ([], "Refunded order 17."),
"refunds 16 and 17": ([("refund", 16), ("refund", 17)], "Refunded order 17."),
"looks up, refunds 17": ([("get_order", 17), ("refund", 17)], "Refunded order 17.")}
for name, (calls, msg) in agents.items():
db, before = reset()
for tool, arg in calls: TOOLS[tool](db, arg)
print(f"{name:24s} transcript {transcript_check(msg):.0f} state {verify(db, before):.0f}")
rng, n, p = np.random.default_rng(0), 20000, 0.30 # verifier noise: false-positive a, false-negative b
success = rng.random(n) < p
for a, b in [(0.0, 0.0), (0.02, 0.10), (0.10, 0.25)]:
r = np.where(success, rng.random(n) > b, rng.random(n) < a).astype(float)
gap = r[success].mean() - r[~success].mean()
print(f"FPR {a:.2f} FNR {b:.2f}: measured {r.mean():.3f} corrected {(r.mean() - a) / (1 - a - b):.3f} reward gap {gap:.3f}")
It prints each agent's reward under both verifiers, then the measured and corrected pass rates and the reward gap between true successes and true failures for three noise levels:
claims success, no call transcript 1 state 0
refunds 16 and 17 transcript 1 state 0
looks up, refunds 17 transcript 1 state 1
FPR 0.00 FNR 0.00: measured 0.292 corrected 0.292 reward gap 1.000
FPR 0.02 FNR 0.10: measured 0.278 corrected 0.293 reward gap 0.877
FPR 0.10 FNR 0.25: measured 0.294 corrected 0.298 reward gap 0.668
The transcript check accepts all three agents, including one that never called a tool and one that also refunded the wrong order; the state check accepts only the agent that changed exactly the right row. This is why tool, web and desktop types verify state rather than text. In the noise simulation the measured pass rate barely moves (0.292, 0.278, 0.294), so a dashboard of mean reward would show nothing wrong, while the reward gap that drives learning falls from 1.000 to 0.877 and 0.668, close to \(1 - \alpha - \beta\) (0.88 and 0.65). The corrected estimates recover the true rate (0.292 to 0.298 against a sampled 0.292), but only because \(\alpha\) and \(\beta\) are known here; in practice they are estimated by auditing a labeled sample of episodes, and they must be re-estimated as the policy changes, since a policy that learns to exploit the verifier raises \(\alpha\).
The type of an environment largely fixes its operating profile: what dominates cost, what breaks, and what must be monitored.
- Verifiable single-turn. Infrastructure is trivial; the work is in generators, answer normalization and decontamination. The usual failure is a checker that is precise but misses equivalent answers: Huang et al. (2025) found rule-based math verifiers above 99% precision but about 86% recall. Monitor the share of rejected answers that an independent checker accepts, and near-duplicate rates against evaluation sets.
- Tool use / MCP. State is a database or service mock, so reset is a file copy or transaction rollback and thousands of episodes fit on one machine. Failures come from unrealistic seed data, tool schemas that drift between training and deployment, and verifiers that check the goal but not collateral changes. Keeping the same MCP server for training and production removes the schema-drift class.
- Web / browser. Self-hosted applications plus a headless browser per episode. Reset must restore the backend, sessions and caches; page-load timing makes episodes flaky unless waits are explicit. Observation size (DOM or accessibility tree) drives inference cost more than the browser does.
- Computer use / desktop. A virtual machine per episode, restored from a snapshot. Boot and restore latency, screenshot tokens and per-task checking scripts in the style of OSWorld dominate. Monitor restore time, step latency and the rate of episodes that end in environment errors.
- SWE / terminal. One image per repository, so registries, layer caching, warm pools and cold-start latency are the main engineering. Test runtime sets \(c_{\text{verify}}\), and flaky tests are verifier noise: gold patches are run several times at admission and tasks with unstable outcomes are dropped. This is the type where sandbox concurrency limits throughput first.
- Conversational with simulated users. The user simulator is a second model to serve and version. Pin its weights and prompt with the task, report \(\text{pass}^k\) as τ-bench does, and audit for policies that succeed by steering or exploiting the simulator rather than by serving the user.
- Enterprise app replicas. Expensive to build and to keep faithful to the product they copy, with state checks for structured outcomes and rubric judges for open-ended ones. The judge is part of the reward and needs the same pinning and audit sampling as code.
- Scientific / simulation. Cost and determinism are inherited from the simulator; numerical tolerances in outcome checks and simulator version pinning are the recurring issues.
Training on several types at once turns these profiles into a scheduling problem: per-episode latency spans from milliseconds to many minutes, so rollout workers are usually pooled by type and each type gets its own dashboard of pass rate, all-pass and all-fail group fractions, infrastructure-failure rate, tail episode latency and verifier disagreement on audited samples. A single blended reward curve hides a type whose verifier is failing.
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, and 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 environment-owned loops, which keep the Gym shape, and harness-owned loops, in which the environment hands a task to an agent program and observes the model calls through a proxy.
An agent episode is a trajectory \(\tau = (x, y_1, e_1, y_2, e_2, \dots, y_K, e_K)\): a task prompt \(x\), then alternating policy turns \(y_k\) (token sequences) and environment returns \(e_k\) (tool outputs rendered as tokens). The policy factorizes over tokens, \(\pi_\theta(y_k \mid h_k) = \prod_j \pi_\theta(y_{k,j} \mid h_k, y_{k,
The sketch implements an environment-owned loop end to end: a passive counter environment with reset/step, a stand-in policy that acts one token at a time, a parser that turns completed token spans into tool calls (a turn may contain several), and a trajectory record whose mask separates policy tokens from environment observations. Because the trainer owns the loop, ids and log-probabilities are recorded at the moment they are sampled, and the episode ends either by termination (done) or by the turn budget.
import numpy as np, re
rng = np.random.default_rng(0)
VOCAB = ["<call>", "inc", "dec", "</call>", "done", "ok"]
class CounterEnv: # passive server: the trainer calls it
def reset(self, target):
self.x, self.target = 0, target
return f"target={target} x=0"
def step(self, tool): # one tool call = one env step
if tool == "done":
return f"target={self.target} x={self.x}", float(self.x == self.target), True
self.x += 1 if tool == "inc" else -1
return f"target={self.target} x={self.x}", 0.0, False
def policy_logits(obs): # stand-in for the LLM
t, x = map(int, re.findall(r"-?\d+", obs))
return np.array([2.0, 1.5 if x < t else -1, 1.5 if x > t else -1, 0.5, 2.0 if x == t else -2, 0.0])
def sample_turn(obs, max_tokens=8): # the policy acts per token
ids, lps = [], []
for _ in range(max_tokens):
z = policy_logits(obs); p = np.exp(z - z.max()); p /= p.sum()
k = rng.choice(len(VOCAB), p=p); ids.append(int(k)); lps.append(float(np.log(p[k])))
if VOCAB[k] in ("</call>", "done"): break
return ids, lps
def parse_calls(ids): # the env sees only completed tool calls
text = " ".join(VOCAB[i] for i in ids)
calls = re.findall(r"<call> (inc|dec)", text)
return calls + (["done"] if text.endswith("done") else [])
env, record = CounterEnv(), {"ids": [], "logprobs": [], "mask": []}
obs, total, done, turns, max_turns = env.reset(target=2), 0.0, False, 0, 12
while not done and turns < max_turns: # the trainer owns the loop
ids, lps = sample_turn(obs); turns += 1
record["ids"] += ids; record["logprobs"] += lps; record["mask"] += [1] * len(ids)
for tool in parse_calls(ids):
obs, r, done = env.step(tool); total += r
record["ids"].append(-1); record["logprobs"].append(0.0); record["mask"].append(0) # env observation slot (masked)
if done: break
print(f"turns={turns} terminated={done} truncated={not done} reward={total}")
print(f"policy tokens={sum(record['mask'])} env observations={len(record['mask'])-sum(record['mask'])} "
f"sum logprob={sum(record['logprobs']):.2f}")
Output:
turns=10 terminated=True truncated=False reward=1.0
policy tokens=51 env observations=7 sum logprob=-66.38
The record holds 51 trainable tokens across 10 turns, while the environment saw only 7 tool calls: the two granularities of action are visible in the counts. Replacing this loop with an agent program removes the trainer from the middle of it, and the same record must then be rebuilt from intercepted model calls.
Both shapes run in production in 2025–2026, often inside one library. Environment-owned loops are the default of the large open trainers: verl's agent loop runs each multi-turn rollout as a coroutine that calls LLM servers and tools and returns token ids with a response mask, and slime and SkyRL provide custom multi-turn generators of the same kind. Harness-owned loops arrived with coding and terminal agents: Harbor supplies tasks, sandboxes, agents and verifiers, and the OpenEnv Harbor environment adds a capture proxy so that unmodified CLIs produce trainable rollouts.
The choice is usually made per environment family. Short, cheap tasks (math, single-tool lookups) favour an environment-owned loop because it adds no sandbox boot or harness start-up per rollout and allows per-step rewards. Agentic coding favours the harness because the product is the harness, and a policy trained in a different scaffold may not transfer to it. Whichever is chosen, each rollout should carry its loop type, harness name and version, termination reason and whether token-level capture succeeded, so that dashboards can separate a model regression from a scaffold change.
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", and conflating them mis-scores rollouts.
The contract assumes the trainer owns the loop, actions are small typed objects and reward arrives every step; none holds for a typical LLM agent.
The termination/truncation split exists because it changes the Bellman target. For a value estimate \(V\), the one-step target is
\[ y_t = r_t + \gamma\,(1 - d_t)\,V(o_{t+1}), \qquad d_t = \textit{terminated}_t , \]so a truncated step still bootstraps. Treating a time limit as a terminal state biases the estimate whenever the remaining time is not part of the observation. Take a reward of 1 per step, discount \(\gamma\) and a limit of \(T\) steps that the agent cannot see. The true value of the non-terminal state is \(1/(1-\gamma)\). If the last step of each episode is treated as terminal, the TD fixed point averages a bootstrapped target on \(T-1\) of every \(T\) steps and a non-bootstrapped one on the last, so \(V = 1 + \gamma \tfrac{T-1}{T} V\), giving
\[ V_{\text{wrong}} = \frac{1}{1 - \gamma (T-1)/T}. \]With \(\gamma = 0.99\) and \(T = 50\) this is about 33.6 instead of 100.
Agent RL usually sets \(\gamma = 1\) with a single terminal reward, so the split moves to the reward itself. A rollout cut by the harness timeout has no verdict; scoring it \(R = 0\) is correct only if the budget is part of the task. A rollout lost to an infrastructure fault should not be scored at all: with group-relative advantages \(A_i = (R_i - \bar R)/\sigma_R\), a zero for a crashed sandbox produces \(A_i < 0\) and pushes down the probability of tokens the policy did nothing wrong to produce, and an infrastructure failure rate \(e\) independent of the policy deflates the measured success rate from \(p\) to \((1-e)p\).
The script makes both effects concrete. The first part runs tabular TD(0) on a constant-reward task with an unobserved 50-step limit, once bootstrapping at truncation and once treating truncation as the end of the episode. The second part computes group-relative advantages for eight agent rollouts in which one hit the harness timeout and one lost its sandbox, first scoring both as zero and then counting the timeout as a failure and dropping the infrastructure error.
import numpy as np
rng = np.random.default_rng(0)
gamma, T, alpha = 0.99, 50, 0.01 # reward 1 per step, time limit 50, time not observed
def td_value(bootstrap_on_truncation, episodes=4000):
V = 0.0 # one observed state: the value of "running"
for _ in range(episodes):
for t in range(T):
truncated = (t == T - 1) # outside limit, not a terminal state
target = 1.0 + (gamma * V if (bootstrap_on_truncation or not truncated) else 0.0)
V += alpha * (target - V)
return V
print(f"true V = {1/(1-gamma):.1f}")
print(f"bootstrap on truncation : V = {td_value(True):.1f}")
print(f"treat truncation as end : V = {td_value(False):.1f}")
# Agent RL: a group of 8 rollouts; one hit the harness timeout, one lost its sandbox.
rewards = np.array([1, 0, 1, 1, 0, 1, np.nan, np.nan]) # nan: no verdict
status = ["ok"] * 6 + ["timeout", "infra_error"]
def group_adv(r): return (r - r.mean()) / (r.std() + 1e-6)
naive = group_adv(np.nan_to_num(rewards, nan=0.0))
keep = np.array([s != "infra_error" for s in status]) # timeout = failure, infra = drop
r2 = np.where(np.isnan(rewards), 0.0, rewards)[keep]
print("naive advantages :", np.round(naive, 2))
print("masked advantages:", np.round(group_adv(r2), 2), "(infra_error dropped)")
Output:
true V = 100.0
bootstrap on truncation : V = 100.0
treat truncation as end : V = 33.3
naive advantages : [ 1. -1. 1. 1. -1. 1. -1. -1.]
masked advantages: [ 0.87 -1.15 0.87 0.87 -1.15 0.87 -1.15] (infra_error dropped)
The wrongly terminated estimate converges to a third of the true value, matching the fixed point \(1/(1-0.99\cdot 49/50) \approx 33.6\). In the group, the naive version gives the crashed rollout the same negative advantage as a genuine failure; dropping it removes a gradient term the policy did not earn and slightly shifts every other advantage.
In classic RL the split is enforced by the library. Gymnasium 1.x vector environments reset finished sub-environments automatically, and the autoreset mode decides when: in next-step mode (the default for SyncVectorEnv and AsyncVectorEnv) the reset happens on the following call, so training code must mask the boundary transition; in same-step mode the returned observation is already the reset one and the true final observation sits in info["final_obs"]. Mixing the two conventions is a common source of silent value errors.
Agent RL needs the same discipline in its own vocabulary. Each rollout should record a termination reason drawn from a closed set: agent finished, turn or token budget reached, wall-clock timeout, context overflow, sandbox failure, verifier failure. Budget truncations are scored as failures only when the identical budget applies at evaluation; infrastructure failures are excluded and retried. The OpenEnv Harbor environment encodes this directly: reward=None means the verifier never ran and is not zero, and a failed rollout comes back as a result with ok=False rather than an exception. A dashboard of termination reasons per environment and harness version, with an alert on shifts in the infrastructure share, catches most cases in which an outage is being learned as a lesson.
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, several of which 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, often in a fresh process or sandbox.
Each mismatch has a quantitative form.
- Two granularities. A turn's probability is a product over tokens, \(\log \pi_\theta(y_k \mid h_k) = \sum_j \log \pi_\theta(y_{k,j} \mid h_k, y_{k,<j})\), while the environment advances once per tool call, \(c_k \ge 0\) times in turn \(k\). The importance ratio used by PPO-style objectives, \(\rho_{k,j} = \pi_\theta(y_{k,j}\mid\cdot)/\mu(y_{k,j}\mid\cdot)\), is meaningful only if the trainer scores exactly the token sequence the sampler \(\mu\) produced.
- Asynchrony. In a synchronous batch of \(B\) episodes each turn takes \(g + \max_i \ell_i\), with generation time \(g\) and tool latencies \(\ell_i\). For exponential latencies of mean \(\bar\ell\), \(\mathbb{E}[\max_i \ell_i] = \bar\ell H_B \approx \bar\ell(\ln B + 0.58)\); heavy-tailed latencies are worse. Asynchronous episodes advance independently, and by Little's law, \(L = \lambda W\), keeping \(N\) episodes in flight yields \(\lambda = N/(g + \bar\ell)\) turns per second until the engine saturates at capacity \(C\), which needs \(N \ge C(g + \bar\ell)\).
- Branching. With compaction and sub-agents, a rollout is a set of model calls linked by prefix; the number of training sequences is the number of leaves of that forest, not the number of turns.
- Terminal reward. With \(\gamma = 1\) and \(R = r(s_K)\), every policy token in the episode receives the same return, so the variance of the per-token gradient grows with episode length unless a baseline, such as a group mean over rollouts of the same task, is subtracted.
The simulation measures the cost of a synchronous step() under heavy-tailed tool latency. Sixty-four episodes of twenty turns each spend 2 s generating per turn and then wait for a lognormal tool call (median 1 s, mean about 3 s). The synchronous loop waits for the slowest call every turn; the asynchronous loop lets each episode proceed on its own, run for the same wall-clock time, and is compared with Little's law. The engine is assumed not to be saturated.
import numpy as np
rng = np.random.default_rng(0)
B, K, g = 64, 20, 2.0 # episodes, turns per episode, seconds to generate one turn
def tool_latency(n): # heavy tail: median 1 s, occasional multi-minute builds
return rng.lognormal(mean=0.0, sigma=1.5, size=n)
# Synchronous: every turn, the batch waits for the slowest tool call before generating again.
sync_time = sum(g + tool_latency(B).max() for _ in range(K))
sync_tput = B * K / sync_time
# Asynchronous: each episode advances on its own; N episodes kept in flight, horizon = sync_time.
def async_turns(N, horizon):
done = 0
for _ in range(N):
t = 0.0
while True:
t += g + tool_latency(1)[0]
if t > horizon: break
done += 1
return done
mean_l = np.exp(1.5**2 / 2)
print(f"mean tool latency {mean_l:.2f}s, E[max of {B}] ~ {np.mean([tool_latency(B).max() for _ in range(2000)]):.1f}s")
print(f"sync : {sync_tput:5.2f} turns/s")
for N in (B, 2 * B):
print(f"async N={N:3d}: {async_turns(N, sync_time) / sync_time:5.2f} turns/s "
f"(Little's law N/(g+E[l]) = {N / (g + mean_l):5.2f})")
Output:
mean tool latency 3.08s, E[max of 64] ~ 45.1s
sync : 1.61 turns/s
async N= 64: 12.90 turns/s (Little's law N/(g+E[l]) = 12.60)
async N=128: 25.20 turns/s (Little's law N/(g+E[l]) = 25.20)
The expected slowest of 64 calls is about fifteen times the mean, so the synchronous loop completes 1.6 turns per second while the same 64 episodes run asynchronously complete about 13, and doubling the number in flight doubles throughput as Little's law predicts.
Production systems answer each mismatch with a specific mechanism. Asynchrony is handled by rollout servers that schedule many episodes as coroutines against continuously batched inference engines (verl's agent loop, slime's fully asynchronous mode), and at the trainer level by decoupling generation from optimisation, as in AReaL and PipelineRL; synchronous systems instead attack the long tail directly, as RollPacker does. The price of asynchrony is staleness: samples come from an older policy and need importance correction such as verl's rollout correction.
The token-granularity problem is solved by token-in, token-out interfaces that never re-encode text (see Capturing Trajectories Exactly). Branching episodes remain partly open: NeMo Gym's on-policy correction notes list summarising, truncating or stripping reasoning from earlier turns as a source of non-monotonic history and call training through it an open research question, recommending that reasoning truncation be disabled in the chat template. Terminal rewards move the verifier into the rollout's critical path, so its latency and failure rate belong on the same dashboard as tool latency percentiles, sampler idle time, the staleness distribution and the engine–trainer log-probability mismatch.
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, starts an agent program such as Claude Code, Codex CLI or OpenHands inside it, sends the instruction and waits; the agent decides when to call the model and which tools to run, and the environment only scores the result.
- Environment-owned loops give full control over prompts, tool parsing, context and per-step rewards, and 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, sends the instruction, and once the harness finishes or times out it 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", and lets the harness be chosen per rollout so that rotating harnesses during training is a configuration change.
Let \(S\) denote a scaffold: system prompt, tool set and call format, context-management policy and retry logic. The trajectory distribution is \(p(\tau \mid \pi_\theta, S, E)\) for environment \(E\), and performance is \(J(\theta; S) = \mathbb{E}_{\tau \sim p(\cdot \mid \pi_\theta, S, E)}[R(\tau)]\). An environment-owned loop optimises \(J(\theta; S_{\text{train}})\) with a custom scaffold, while deployment measures \(J(\theta; S_{\text{deploy}})\); the difference between the two is not an object the optimiser sees. Training inside the deployed harness sets \(S_{\text{train}} = S_{\text{deploy}}\), and rotating harnesses per rollout optimises the mixture
\[ J_\rho(\theta) = \mathbb{E}_{H \sim \rho}\, J(\theta; H), \]the scaffold analogue of domain randomisation: habits specific to one harness earn reward only under that harness's share of \(\rho\).
Loop ownership also changes what the gradient is computed from. In a harness-owned loop the policy calls form a set \(\mathcal{C}(\tau)\) that may include several roots (sub-agents, summarisers) and abandoned branches; the estimator becomes \(R(\tau) \sum_{c \in \mathcal{C}_{\text{train}}} \sum_j \nabla_\theta \log \pi_\theta(y_{c,j} \mid \cdot)\), where \(\mathcal{C}_{\text{train}} \subseteq \mathcal{C}\) excludes calls to other models and discarded branches. Per-step rewards \(r_t\) are available only when the environment sees each step; a harness-owned loop exposes \(r(s_K)\) alone. The per-rollout cost is roughly \(c_{\text{boot}} + K(c_{\text{gen}} + c_{\text{tool}}) + c_{\text{verify}}\), and the harness adds start-up time to \(c_{\text{boot}}\).
The sketch inverts the loop of an environment-owned rollout. The environment provisions a sandbox (here a set of file names), opens a capture session and hands the instruction to an agent program that runs its own loop and calls what it believes is an ordinary model API. That API is a proxy: it checks the session key, forwards the call to the engine, records prompt ids, sampled ids and log-probabilities under the rollout, and returns plain text. After the harness exits, a verifier inspects only the final sandbox state. Two harnesses with different call budgets are rotated across rollouts.
import numpy as np, secrets
rng = np.random.default_rng(1)
class Engine: # inference engine that can return token ids + logprobs
def generate(self, prompt_ids, temperature=1.0):
z = rng.normal(size=(6, 50)) / temperature
lp = z - np.log(np.exp(z).sum(1, keepdims=True))
ids = [int(rng.choice(50, p=np.exp(row))) for row in lp]
return ids, [float(lp[i, k]) for i, k in enumerate(ids)]
class CaptureProxy: # looks like an ordinary model API to the agent
def __init__(self, engine): self.engine, self.sessions = engine, {}
def open_session(self, rollout_id):
key = secrets.token_hex(8); self.sessions[key] = {"rollout": rollout_id, "calls": []}; return key
def chat(self, api_key, messages):
if api_key not in self.sessions: raise PermissionError("unknown session")
prompt_ids = [sum(map(ord, m)) % 50 for m in messages] # stand-in for engine tokenisation
ids, lps = self.engine.generate(prompt_ids)
self.sessions[api_key]["calls"].append({"prompt_ids": prompt_ids, "ids": ids, "logprobs": lps})
return f"edit file_{ids[0] % 3}" # text reply in the agent's dialect
class Harness: # an agent program with its own loop; never stepped
def __init__(self, name, max_calls): self.name, self.max_calls = name, max_calls
def run(self, sandbox, instruction, model, api_key):
messages = [f"[{self.name}] {instruction}"]
for _ in range(self.max_calls): # the harness decides when to call the model
reply = model.chat(api_key, messages)
sandbox.add(reply.split()[-1]); messages.append(reply)
if {"file_0", "file_1"} <= sandbox: break
def verifier(sandbox): return float({"file_0", "file_1"} <= sandbox) # scores final state only
proxy = CaptureProxy(Engine())
for i, harness in enumerate([Harness("cli-a", 4), Harness("cli-b", 8), Harness("cli-a", 4)]):
sandbox, key = set(), proxy.open_session(rollout_id=i) # provision, then hand off
harness.run(sandbox, "touch file_0 and file_1", model=proxy, api_key=key)
calls = proxy.sessions[key]["calls"]
print(f"rollout {i} harness={harness.name} calls={len(calls)} "
f"tokens={sum(len(c['ids']) for c in calls)} reward={verifier(sandbox)}")
Output:
rollout 0 harness=cli-a calls=4 tokens=24 reward=0.0
rollout 1 harness=cli-b calls=2 tokens=12 reward=1.0
rollout 2 harness=cli-a calls=4 tokens=24 reward=0.0
Every model call is captured with its token ids even though the environment never stepped the agent, and the reward comes from the final state alone. The same proxy serves all three rollouts; the session key, not a port, separates them.
The harness-owned shape is now packaged by several systems. Harbor was released with Terminal-Bench 2.0 as its evaluation framework, NeMo Gym drives Harbor agents from its environment servers, and the OpenEnv Harbor environment lists 16 harnesses validated end to end across four wire dialects, with dataset, harness and sandbox backend chosen per rollout.
Operating it raises decisions an environment-owned loop never faces. Harness versions should be pinned and recorded on every rollout, because a harness update changes the scaffold and therefore the environment. Harness timeouts need to be separate from model token budgets so that the termination reason is unambiguous. Harnesses spawn auxiliary conversations (sub-agents, summarisers), so the trainable subset must be selected explicitly; OpenEnv reports the number of independent roots per rollout and counts only agent conversations as trainable. Where a harness writes its own trajectory file, comparing it call by call with the capture is a cheap integrity check. Failures should cross process boundaries as data: OpenEnv returns ok=False rather than raising, because in an in-process design one exception on one rank hangs every rank at the distributed barrier. The most expensive failure is quiet: its documentation describes a provider-compatibility edit that changed model behaviour so that agents made one call and then idled until the timeout, which it now detects with a tool-calling probe at start-up.
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, asks the engine for token ids and log-probabilities, and records the call before returning the response in the dialect the agent expects.
Two 2026 implementations show the pattern. The OpenEnv Harbor environment translates four wire dialects (chat completions, OpenAI Responses, Anthropic Messages, Google generateContent) to one upstream shape, so unmodified agents such as Claude Code, Codex and Gemini CLI can be captured; how it links calls into a rollout graph is described in Capturing Trajectories Exactly. It probes the engine at startup and marks rollouts eval-only when token ids or post-temperature log-probabilities are unavailable. Verifiers v1 places a similar interception server between harness and inference server and stores traces as message graphs, turning each root-to-leaf branch into a training sample. Any sampling-parameter override or provider workaround the proxy applies changes the experiment and should be recorded on the rollout; token-level pitfalls are covered in Capturing Trajectories Exactly.
A captured call is trainable when it provides the prompt token ids, the sampled ids \(y_1,\dots,y_n\), and \(\log \mu(y_t \mid \cdot)\) under the distribution that actually sampled them. With logits \(z\) and temperature \(T\), that distribution is \(\mu_T = \operatorname{softmax}(z/T)\). Engines may instead return raw log-probabilities \(\log \operatorname{softmax}(z)\), which differ token by token:
\[ \log \mu_T(k) - \log \operatorname{softmax}(z)_k = z_k\Big(\tfrac{1}{T} - 1\Big) - \big[\operatorname{LSE}(z/T) - \operatorname{LSE}(z)\big]. \]The two can be told apart without access to logits. The gap between the top two log-probabilities is \(\Delta_T = (z_{(1)} - z_{(2)})/T\) for processed values and constant for raw ones, so requesting the same prompt at \(T = 1\) and \(T = 2\) and checking \(\Delta_2 = \Delta_1/2\) identifies the mode. An error in \(\log\mu\) enters the importance ratio \(\rho_t = \pi_\theta(y_t)/\mu(y_t)\) additively in log space, and a sequence-level ratio \(\prod_t \rho_t\) accumulates it over every token.
Token ids must also come from the engine. Decoding and re-encoding is not injective in general, \(\operatorname{enc}(\operatorname{dec}(y)) \ne y\), so a trainer that re-tokenises scores a sequence that was never sampled. Calls are linked into a rollout graph by exact prefix: call \(b\) is a child of \(a\) when the full token sequence of \(a\) is a prefix of \(b\)'s prompt. Roots are independent conversations and leaves are the training sequences.
The script implements the two checks a capture proxy runs. The first part simulates an endpoint in processed and raw log-probability modes, applies the two-temperature gap probe, and measures how far raw values are from the true behaviour log-probabilities for tokens sampled at \(T = 0.7\). The second part links six captured calls into a graph by exact token prefix: a main conversation, a branch that retries from an earlier call, and a separate sub-agent conversation.
import numpy as np
rng = np.random.default_rng(0)
logsoftmax = lambda z: z - np.log(np.exp(z - z.max()).sum()) - z.max()
# 1) Probe: are returned logprobs post-temperature ("processed") or raw?
z = rng.normal(scale=3.0, size=1000) # one position's logits
def endpoint(T, mode): # what an engine would return
return logsoftmax(z / T) if mode == "processed" else logsoftmax(z)
for mode in ("processed", "raw"):
gaps = [np.diff(np.sort(endpoint(T, mode))[-2:])[0] for T in (1.0, 2.0)]
print(f"{mode:9s}: top-2 gap T=1 {gaps[0]:.3f} T=2 {gaps[1]:.3f} -> "
f"{'train' if abs(gaps[1] - gaps[0] / 2) < 1e-6 else 'eval-only'}")
# Cost of using raw logprobs as the behaviour policy at T=0.7
T = 0.7; p = np.exp(logsoftmax(z / T)); k = rng.choice(len(z), size=5000, p=p)
log_ratio = logsoftmax(z)[k] - logsoftmax(z / T)[k] # wrong mu vs true mu, same tokens
print(f"mean |log ratio| per token from raw logprobs: {np.abs(log_ratio).mean():.2f}")
# 2) Link captured calls into a rollout graph by exact token prefix.
calls = {"c1": [1, 2, 3], "c2": [1, 2, 3, 7, 8, 9], "c3": [1, 2, 3, 7, 8, 9, 4, 5],
"c4": [1, 2, 3, 7, 8, 9, 6], # retry/branch off c2
"s1": [11, 12], "s2": [11, 12, 13]} # sub-agent: a separate root
parent = {}
for c, ids in calls.items():
cands = [d for d, p_ in calls.items() if d != c and len(p_) < len(ids) and ids[:len(p_)] == p_]
parent[c] = max(cands, key=lambda d: len(calls[d])) if cands else None
roots = [c for c in calls if parent[c] is None]
leaves = [c for c in calls if c not in parent.values()]
print("parent:", parent)
print(f"roots={roots} leaves={leaves} -> {len(leaves)} training sequences")
Output:
processed: top-2 gap T=1 0.931 T=2 0.465 -> train
raw : top-2 gap T=1 0.931 T=2 0.931 -> eval-only
mean |log ratio| per token from raw logprobs: 0.54
parent: {'c1': None, 'c2': 'c1', 'c3': 'c2', 'c4': 'c2', 's1': None, 's2': 's1'}
roots=['c1', 's1'] leaves=['c3', 'c4', 's2'] -> 3 training sequences
The probe separates the modes exactly, and the raw values are off by about 0.54 nats per token on average, enough to make a sequence-level ratio meaningless. The graph has two roots and three leaves; in production the branch c4 would be marked discarded if the agent abandoned it, so it does not inherit the reward of the main path.
The OpenEnv Harbor environment documents a complete proxy design. The agent's base URL points at the proxy and its API key is a capture session id minted per rollout, so one proxy serves many concurrent rollouts without a port each and rejects callers without a registered session, which makes it safe to expose to a sandbox. Nothing is tokenised locally: the engine returns prompt_token_ids for each call. Against vLLM, trainable capture needs --return-tokens-as-token-ids and --logprobs-mode processed_logprobs, because the default returns values before temperature and top-k/top-p; start-up compares top-two gaps rather than raw values because a data-parallel engine may answer consecutive calls from different replicas. Endpoints that fail the probe are downgraded to evaluation rather than refused, and the mode is stamped on every result.
NeMo Gym takes the same position on the data interface: the model server returns prompt ids, generation ids and generation log-probabilities, and harnesses must pass them through unchanged rather than rebuild them. Agent Lightning's write-up on vLLM makes the same case for returning token ids through the OpenAI-compatible API, to avoid retokenisation drift. The dangerous failures are silent: an endpoint that returns no token ids answers every request normally, so the share of rollouts captured at training level, proxy latency, and agreement between capture and harness trajectory files belong on the monitoring dashboard, and every provider workaround the proxy applies is logged on the rollout as a change to the experiment.
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, each with a name, description and a JSON Schema for its inputs (and optionally its outputs), and executes them with tools/call. Tool execution errors come back as results flagged with isError, so the model can read them and retry, while malformed requests are protocol errors. That 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, keeping the training action space identical to production. What MCP lacks are the RL primitives (reset, episode boundaries, task identity, reward), and 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; and CUBE builds on both MCP and Gym.
An MCP server defines an action space. With tools \(i = 1,\dots,n\), names \(\nu_i\) and input schemas \(\sigma_i\),
\[ \mathcal{A} = \bigcup_{i=1}^{n} \{\nu_i\} \times \mathcal{V}(\sigma_i), \]where \(\mathcal{V}(\sigma)\) is the set of JSON values that satisfy the schema. A policy emits a string that is parsed into a candidate action. A string that names no tool or does not form a valid call lies outside \(\mathcal{A}\) and yields a protocol error; a valid call whose execution or business-level validation fails is inside \(\mathcal{A}\) and yields an observation flagged isError. The RL treatment follows: execution errors are ordinary transitions, while invalid actions need an explicit rule, typically an error observation that consumes a turn, termination with a fixed penalty, or constrained decoding that keeps the action inside \(\mathcal{A}\).
An MDP needs \((\mathcal{S}, \mathcal{A}, P, R, \rho_0, H)\). MCP supplies \(\mathcal{A}\) and the tool side of \(P\); the initial-state distribution \(\rho_0\) (reset), the horizon \(H\) and episode boundaries, task identity and \(R\) come from the layer above. Two further properties matter. The tool manifest enters every prompt, so its length \(L_{\text{tools}} = \sum_i (|\text{desc}_i| + |\sigma_i|)\) is paid on each of \(K\) turns unless prefix caching amortises it. And because servers can announce that the tool list changed, \(\mathcal{A}\) may vary within an episode, which makes the action space non-stationary unless it is pinned per episode.
The sketch is a minimal MCP-style JSON-RPC server with two tools and a thin environment wrapper that adds what MCP lacks: a fresh server state on reset, a task, an episode boundary and a reward computed from server state. An unknown tool name returns a JSON-RPC protocol error (code -32602), which the wrapper counts as an invalid action; arguments that fail the tool's input validation return a result with isError, which the wrapper passes to the policy as an observation.
import json
class TodoServer: # minimal MCP-style tool server (JSON-RPC 2.0)
TOOLS = [{"name": "add_item", "description": "Add an item to the list",
"inputSchema": {"type": "object", "properties": {"text": {"type": "string"}},
"required": ["text"], "additionalProperties": False}},
{"name": "list_items", "description": "List items",
"inputSchema": {"type": "object", "additionalProperties": False}}]
def __init__(self): self.items = []
def handle(self, req):
rid, m, p = req.get("id"), req.get("method"), req.get("params", {})
if m == "tools/list":
return {"jsonrpc": "2.0", "id": rid, "result": {"tools": self.TOOLS}}
tool = next((t for t in self.TOOLS if t["name"] == p.get("name")), None)
if m != "tools/call" or tool is None: # protocol error: unknown tool / method
return {"jsonrpc": "2.0", "id": rid, "error": {"code": -32602, "message": f"Unknown tool: {p.get('name')}"}}
args, sch = p.get("arguments", {}), tool["inputSchema"]
missing = [k for k in sch.get("required", []) if k not in args]
extra = [k for k in args if k not in sch.get("properties", {})]
if missing or extra: # execution error: model can read it and retry
return {"jsonrpc": "2.0", "id": rid, "result": {"isError": True, "content": [
{"type": "text", "text": f"invalid arguments: missing={missing} unexpected={extra}"}]}}
if tool["name"] == "add_item": self.items.append(args["text"]); out = f"added ({len(self.items)})"
else: out = json.dumps(self.items)
return {"jsonrpc": "2.0", "id": rid, "result": {"isError": False, "content": [{"type": "text", "text": out}]}}
class MCPEnv: # adds what MCP lacks: reset, episode, task, reward
def reset(self, task):
self.server, self.task, self.n, self.invalid = TodoServer(), task, 0, 0 # fresh state per episode
tools = self.server.handle({"jsonrpc": "2.0", "id": 0, "method": "tools/list"})["result"]["tools"]
return task["instruction"], [t["name"] for t in tools]
def step(self, name, arguments):
self.n += 1
resp = self.server.handle({"jsonrpc": "2.0", "id": self.n, "method": "tools/call",
"params": {"name": name, "arguments": arguments}})
if "error" in resp: # invalid action
self.invalid += 1; obs, kind = resp["error"]["message"], "invalid_action"
else: # observation, error or not
obs, kind = resp["result"]["content"][0]["text"], "tool_error" if resp["result"]["isError"] else "ok"
done = name == "list_items" and kind == "ok"
reward = float(done and sorted(self.server.items) == sorted(self.task["want"]))
return obs, kind, reward, done
env = MCPEnv()
print(env.reset({"instruction": "Add milk and eggs, then list.", "want": ["milk", "eggs"]}))
for name, args in [("add_item", {"item": "milk"}), ("add_item", {"text": "milk"}),
("delete_all", {}), ("add_item", {"text": "eggs"}), ("list_items", {})]:
print(name, args, "->", env.step(name, args))
print("invalid actions:", env.invalid)
Output:
('Add milk and eggs, then list.', ['add_item', 'list_items'])
add_item {'item': 'milk'} -> ("invalid arguments: missing=['text'] unexpected=['item']", 'tool_error', 0.0, False)
add_item {'text': 'milk'} -> ('added (1)', 'ok', 0.0, False)
delete_all {} -> ('Unknown tool: delete_all', 'invalid_action', 0.0, False)
add_item {'text': 'eggs'} -> ('added (2)', 'ok', 0.0, False)
list_items {} -> ('["milk", "eggs"]', 'ok', 1.0, True)
invalid actions: 1
The wrong argument name produces a readable error the policy can correct on the next call, the unknown tool is counted as an invalid action, and the reward of 1 arrives only when the final state matches the task.
The 2025-11-25 tools specification gives training environments most of what they need: paginated tools/list, optional output schemas with structuredContent, and a listChanged capability for dynamic tool sets. Its security section requires servers to validate all inputs, implement access controls, rate-limit invocations and sanitise outputs, and asks clients to time out tool calls and log usage; it also says tool annotations must be treated as untrusted unless they come from trusted servers.
Using one MCP server for training and deployment raises operational questions the protocol leaves open. Reset needs a fresh server instance per episode or a snapshot of its backing state, since many servers are stateful. The tool manifest should be versioned with the task and pinned for the episode, so that a listChanged notification cannot alter the action space mid-rollout. Protocol-error and isError rates per tool are useful dashboard signals: a rise in protocol errors usually means format drift in the policy or a manifest change, not a harder task. Tool outputs are untrusted input to the policy and the servers run inside the sandbox network policy. For the missing RL primitives, OpenEnv treats MCP as a first-class way to expose environment tools (its Harbor environment is served as one long-running run_rollout MCP tool), the Open Reward Standard adds rewards, termination, tasks and splits, and CUBE combines MCP with a Gym-style interface.
Environment Standards and Hubs
Between 2025 and 2026 the field moved from one-off environment code inside each training stack toward shared standards, but no single standard has won, and the projects occupy different layers. Some define a wire protocol (how a client resets and steps an environment over the network), some are authoring libraries (how an environment, its tasks and its reward are written), some define a task format and runner for agent harnesses, and some are hubs for 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.
An environment for language-model RL can be written as a tuple \(E = (\mathcal{D}, H, \rho, R)\): a task distribution \(\mathcal{D}\), a harness \(H\) that turns the policy's text into actions, a runtime \(\rho\) that executes them, and a reward \(R(t, s_T) \in [0,1]\) on the final state. A wire protocol fixes only the signatures
\[ \texttt{reset}: (t, \text{seed}) \mapsto o_0, \qquad \texttt{step}: a_k \mapsto (o_{k+1}, r_{k+1}, d_{k+1}), \qquad \texttt{state}: () \mapsto s_k, \]and says nothing about \(\mathcal{D}\) or \(R\); an authoring library fixes how \(\mathcal{D}\), \(H\) and \(R\) are written, a task format packages one \(t\) with its verifier, and a hub names and versions \(E\).
The case for a standard is a count of adapters: \(n\) trainers and \(m\) environments need \(nm\) adapters without a shared interface and \(n + m\) with one (200 against 45 for \(n = 5\), \(m = 40\)). One adapter between two standards at the same layer joins both sides wholesale, which is why layers interoperate. Sharing an interface does not guarantee portability, \(\Pr_S(R = 1 \mid t, \pi) = \Pr_{S'}(R = 1 \mid t, \pi)\) for two stacks \(S, S'\) and every task; that has to be tested.
The smallest useful wire protocol is three JSON endpoints. The snippet below serves a toy environment (guess a hidden digit, with "higher" and "lower" hints) over HTTP on localhost using only the Python standard library. The environment owns its state and reward; the client knows nothing except the method names and the JSON shapes, which is the separation OpenEnv draws between an environment and a training loop. A bisection policy plays one episode.
import json, threading, urllib.request
from http.server import BaseHTTPRequestHandler, HTTPServer
class GuessEnv: # environment side: owns state and reward
def reset(self, seed):
self.target, self.t = seed % 10, 0
return {"obs": "guess a digit 0-9", "done": False}
def step(self, action):
self.t += 1
g = int(action["guess"]); done = g == self.target or self.t >= 4
hint = "correct" if g == self.target else ("higher" if g < self.target else "lower")
return {"obs": hint, "reward": float(g == self.target), "done": done}
def state(self):
return {"turn": self.t}
ENV = GuessEnv()
class Handler(BaseHTTPRequestHandler): # wire layer: reset / step / state as JSON over HTTP
def do_POST(self):
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
out = getattr(ENV, self.path.strip("/"))(**body)
data = json.dumps(out).encode()
self.send_response(200); self.send_header("Content-Length", str(len(data))); self.end_headers()
self.wfile.write(data)
def log_message(self, *a): pass
srv = HTTPServer(("127.0.0.1", 0), Handler)
threading.Thread(target=srv.serve_forever, daemon=True).start()
URL = f"http://127.0.0.1:{srv.server_port}"
def call(method, **kw): # client side: knows only the protocol
req = urllib.request.Request(f"{URL}/{method}", json.dumps(kw).encode(),
{"Content-Type": "application/json"})
return json.loads(urllib.request.urlopen(req).read())
lo, hi = 0, 9 # a bisection "policy"
r = call("reset", seed=37)
while not r["done"]:
g = (lo + hi) // 2
r = call("step", action={"guess": g})
if r["obs"] == "higher": lo = g + 1
elif r["obs"] == "lower": hi = g - 1
print(f"guess={g} obs={r['obs']:<7} reward={r['reward']}")
print("state:", call("state"))
srv.shutdown()
Output: two steps, a "higher" hint and then the correct guess with reward 1.0, and a state() call that returns the turn count.
guess=4 obs=higher reward=0.0
guess=7 obs=correct reward=1.0
state: {'turn': 2}
Swapping GuessEnv for any other class with the same three methods changes nothing on the client side; swapping the client for a different trainer changes nothing on the server side. That is the whole of the \(n + m\) argument in running code. Production protocols add what this sketch leaves out: a session identifier so one server can hold many episodes, persistent connections (WebSocket) to avoid a handshake per step, typed schemas for actions and observations, and tool discovery in MCP form.
In practice the layers map onto ownership: environment authors own tasks and verifiers, an infrastructure team owns the runtime and protocol endpoint, and the training team owns harness and trainer. A standard at a boundary lets each group release independently, so the practical decision is which boundary to freeze first. Teams training on Terminal-Bench-style tasks tend to freeze the task format (Harbor); teams serving many heterogeneous environments over a network freeze the protocol (OpenEnv, ORS).
Protocol overhead is milliseconds against seconds of tool execution and generation; the costs that matter sit below it (one image per environment, container start time, sessions per server). The recurring failures sit at boundaries: an observation format changes in a protocol upgrade, a harness parses tool calls differently (swapping the harness around one model moved Terminal-Bench accuracy by up to 29.9 points in Buchanan et al. 2026), or an image is rebuilt over a moved dependency. Every rollout record therefore carries a version per layer.
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: Gymnasium-style
reset(),step()andstate()over HTTP and WebSocket, one Docker image per environment, MCP tools exposed natively, and no opinion 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 and runs Claude Code, Codex CLI, OpenHands and other agents in containers across many sandbox providers (GitHub). Its task directory (
task.toml,instruction.md, anenvironment/Dockerfile, atests/verifier that writes a reward file, an optional reference solution) has become a de facto task format that other libraries import. - 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 with 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 gained 3.37 points on average across six reasoning benchmarks for a strong 1.5B model, versus 0.49 points for continuing its original RL with more than three times the compute.
| Project | Layer | Interface | Reward defined by | Notable fact |
|---|---|---|---|---|
| OpenEnv | Protocol, catalog | reset / step / state over WebSocket; MCP tools | Environment (external rewards on roadmap) | Committee governance since June 2026 |
| Verifiers v1 | Authoring, hub | Taskset + harness + runtime | Rubric functions in the environment | Interception server records traces |
| Harbor | Task format, runner | Task directory; agent harness in container | Verifier in tests/ writes reward file | Official Terminal-Bench 2.0 harness |
| NeMo Gym | Authoring, serving | Agent / model / resources servers | Resources server verification | Runs Harbor, OpenEnv, Verifiers and Reasoning Gym envs |
| SkyRL-Gym | Authoring | Gymnasium-style text env + tools | Environment | Math, code, search, SQL envs |
| GEM | Authoring | Gym-style, async vectorized | Environment, per-turn possible | Examples for five RL frameworks |
| Atropos | Rollout controller | Env microservices → trajectory API | Environment | Any OpenAI-compatible endpoint |
| ORS | Protocol | HTTP; MCP-style tools | Protocol primitive | 200+ envs on EnvCommons |
| CUBE | Benchmark wrapping | Built on MCP and Gym | Benchmark | Proposal, 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.
The projects differ in which part of the expected reward they fix. For a policy \(\pi\), a harness \(H\), a runtime \(\rho\) and a taskset \(\mathcal{D}\),
\[ J(\pi; H, \rho, \mathcal{D}) = \mathbb{E}_{t \sim \mathcal{D}}\; \mathbb{E}_{\tau \sim (\pi, H, \rho, t)} \big[ R(t, s_T(\tau)) \big]. \]Verifiers v1 makes the factorization explicit (taskset, harness, runtime as separate objects); a Harbor task fixes \(t\) and \(R\) (the tests/ verifier writes \(R \in [0,1]\) to a file) and leaves \(H\) to the runner; OpenEnv fixes the interface to \(\rho\); ORS makes \(R\) a protocol primitive. Because \(J\) depends on \(H\), a published score is a statement about the triple, and the harness sensitivity \(\Delta_H = \max_{H, H'} |J(\pi; H) - J(\pi; H')|\) can exceed the gap between models.
Asynchronous execution. GEM's asynchronous vectorized mode addresses a latency problem. If \(K\) environments step in lock-step and step latencies are independent exponential with mean \(\mu\), each synchronous step waits for the slowest: \(\mathbb{E}[\max_k L_k] = \mu H_K\), with \(H_K = \sum_{i=1}^K 1/i\). For \(K = 8\) that is \(2.72\mu\), for \(K = 64\) it is \(4.74\mu\); an asynchronous pool that refills each slot as it frees pays \(\mu\) per step on average. Atropos takes the same idea further by letting environment microservices push scored rollouts to a queue the trainer reads from.
Adaptive difficulty. With group-relative advantages, a group of \(G\) rollouts at pass rate \(p\) gives gradient signal only if it contains both a pass and a fail:
\[ \Pr(\text{informative}) = 1 - p^G - (1-p)^G, \]maximized at \(p = 1/2\) (0.992 for \(G = 8\)) and falling to 0.570 at \(p = 0.9\) and 0.077 at \(p = 0.99\). Procedural generators expose a difficulty parameter \(d\), and RLVE's controller moves \(d\) to keep the policy's measured accuracy inside a band, which keeps \(p\) near the informative region as the policy improves. On the reported numbers (3.37 points versus 0.49 points with more than three times the compute), RLVE's gain per unit of compute exceeds the baseline's by a factor of at least \(3.37 / (0.49/3) \approx 21\).
Two artifacts from the projects above are easy to reproduce in a few dozen lines: a Harbor-style task directory with its runner, and an adaptive-difficulty controller in the spirit of RLVE. The first snippet writes a task (task.toml, instruction.md, an environment/ Dockerfile, a tests/ verifier that writes a reward file, a reference solution) and runs three agents against it in fresh workspaces. A real runner builds the Dockerfile and runs agent and verifier inside the container; here both run in a temporary directory so the bookkeeping can be checked without Docker.
import pathlib, shutil, subprocess, tempfile, tomllib
def write_task(root): # a Harbor-style task directory
t = pathlib.Path(root) / "fix-sum"
(t / "environment").mkdir(parents=True); (t / "tests").mkdir(); (t / "solution").mkdir()
(t / "task.toml").write_text('version = "1.0"\n[verifier]\ntimeout_sec = 30\n[agent]\ntimeout_sec = 300\n')
(t / "instruction.md").write_text("Create sum.py that prints the sum of the integers in nums.txt.\n")
(t / "environment" / "Dockerfile").write_text("FROM python:3.12-slim\nWORKDIR /app\n")
(t / "tests" / "test.sh").write_text( # verifier: run the check, write the reward file
'mkdir -p logs/verifier\n'
'printf "3\\n4\\n35\\n" > nums.txt\n'
'if [ "$(python3 sum.py 2>/dev/null)" = "42" ]; then echo 1 > logs/verifier/reward.txt;\n'
'else echo 0 > logs/verifier/reward.txt; fi\n')
(t / "solution" / "solve.sh").write_text(
"echo 'print(sum(int(x) for x in open(\"nums.txt\")))' > sum.py\n")
return t
def run_trial(task, agent): # runner: fresh workspace, agent, then verifier
cfg = tomllib.loads((task / "task.toml").read_text())
with tempfile.TemporaryDirectory() as ws:
agent(task, ws)
subprocess.run(["bash", str(task / "tests" / "test.sh")], cwd=ws,
timeout=cfg["verifier"]["timeout_sec"], check=False)
return float(pathlib.Path(ws, "logs/verifier/reward.txt").read_text())
oracle = lambda task, ws: subprocess.run(["bash", str(task / "solution" / "solve.sh")], cwd=ws)
null = lambda task, ws: None
wrong = lambda task, ws: pathlib.Path(ws, "sum.py").write_text("print(41)\n")
with tempfile.TemporaryDirectory() as root:
task = write_task(root)
print(sorted(str(p.relative_to(task)) for p in task.rglob("*") if p.is_file()))
for name, agent in [("oracle", oracle), ("null", null), ("wrong", wrong)]:
print(f"{name:<6} reward={run_trial(task, agent)}")
Output: the five task files, reward 1.0 for the reference solution and 0.0 for an agent that does nothing and for one that prints a wrong answer.
['environment/Dockerfile', 'instruction.md', 'solution/solve.sh', 'task.toml', 'tests/test.sh']
oracle reward=1.0
null reward=0.0
wrong reward=0.0
Running the reference solution and a null agent is the cheapest validity check a task admits: a task whose oracle fails is broken, and a task the null agent passes rewards nothing.
The second snippet simulates a policy whose solve probability falls with difficulty level and rises with a skill variable that grows only on informative groups (\(G = 8\)). It compares training at a fixed easy level, a fixed hard level, and a level promoted when accuracy over a window exceeds 0.8 and demoted below 0.2.
import numpy as np
rng = np.random.default_rng(0)
G, STEPS, BATCH = 8, 400, 32
def solve_prob(skill, d): # simulated policy: harder levels are less likely solved
return 1 / (1 + np.exp(d - skill))
def informative(p): # P(group of G has both a pass and a fail)
return 1 - p**G - (1 - p)**G
def train(mode):
skill, d, window, frac = 1.0, 1, [], []
for step in range(STEPS):
level = {"easy": 1, "hard": 8, "adaptive": d}[mode]
p = solve_prob(skill, level)
wins = rng.binomial(G, p, size=BATCH) # BATCH groups of G rollouts
useful = ((wins > 0) & (wins < G)).mean()
frac.append(useful)
skill += 0.02 * useful # learning happens only on informative groups
window.append(wins.mean() / G)
if mode == "adaptive" and len(window) >= 10:
acc = np.mean(window[-10:])
if acc > 0.8: d, window = d + 1, [] # promote when the level is mastered
elif acc < 0.2 and d > 1: d, window = d - 1, []
return np.mean(frac), skill, level
for mode in ["easy", "hard", "adaptive"]:
f, s, lv = train(mode)
print(f"{mode:<8} informative={f:.2f} final_skill={s:.2f} final_level={lv}")
print("P(informative) at p=0.5, 0.9, 0.99:", [round(informative(p), 3) for p in (0.5, 0.9, 0.99)])
Output: the adaptive controller keeps most groups informative and ends at a far higher level than either fixed setting; the last line gives the closed-form informative probability.
easy informative=0.48 final_skill=4.81 final_level=1
hard informative=0.01 final_skill=1.06 final_level=8
adaptive informative=0.91 final_skill=8.32 final_level=7
P(informative) at p=0.5, 0.9, 0.99: [0.992, 0.57, 0.077]
Choosing among these projects is mostly a question of where the reward lives and who owns the loop. When the reward is defined inside the environment (OpenEnv, SkyRL-Gym, GEM, Atropos), the environment author controls it and it travels with the image; when it is a verifier in a task directory (Harbor), it can be audited file by file; when it is a protocol primitive (ORS), the server decides it and the client cannot alter it, which helps against reward tampering by the agent but makes local inspection harder. Harness ownership is the second axis: Harbor runs one task under Claude Code, Codex CLI or OpenHands, and Verifiers v1 under Codex, mini-SWE-agent or a custom harness, which is how training and evaluation harnesses are kept apart deliberately rather than by accident.
The serving model sets the cost profile. A Harbor trial is a container per attempt, so sandbox start time and image size dominate on short tasks. NeMo Gym's split into agent, model and resources servers lets each scale separately. Atropos-style push queues decouple trainer throughput from environment latency, at the price of off-policy data whose staleness must be bounded and corrected. Procedural generators (Reasoning Gym, RLVE-Gym) cost almost nothing per task and need no container, which is why they are often the first environments a pipeline runs.
The recurring failures are version drift and silent semantic differences between adapters. The Terminal-Bench 2.1 release revised 28 of 89 tasks, nine because internet-hosted dependencies had changed, and one agent–model pair rose by about 12 points (Terminal-Bench 2.1). Operating practice follows: pin project versions and image digests per run, record harness, verifier and environment versions with every rollout, run oracle and null agents on each imported task before training on it, and treat "supports Harbor tasks" as a claim to test rather than a guarantee.
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, and 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: an environment is a dataset repo tagged rl-environment, framework tags (harbor, verifiers, openenv, nemo-gym) declare compatibility, and the tags generate framework-specific loading snippets (Hugging Face 2026). Reusing dataset repos gives environments the Hub's existing versioning, gating and dataset cards.
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, so a small cross-stack agreement check is cheap insurance before trusting an imported environment.
A hub gives an environment an identity \((\text{repo}, \text{revision})\) whose revision is a content hash, so two runs citing it ran the same code, tasks and verifier. Framework tags are a compatibility relation declared by the uploader, not proven.
Proving portability is a paired question. Run one policy on the same \(N\) tasks through stacks \(A\) and \(B\) and let \(d_i = \hat p_{A,i} - \hat p_{B,i}\). The mean \(\bar d\) has standard error \(s_d/\sqrt{N}\), free of between-task variance. Detecting a shift \(\delta\) at level \(\alpha\) with power \(1-\beta\) needs
\[ N \ge \left( \frac{(z_{1-\alpha/2} + z_{1-\beta})\, \sigma_d}{\delta} \right)^2, \]about 785 tasks for \(\sigma_d = 0.3\), \(\delta = 0.03\), \(\alpha = 0.05\), 80% power. With one trial per task this is McNemar's test: under agreement, tasks passed by \(A\) alone follow \(\mathrm{Binomial}(n_{10} + n_{01}, 1/2)\). Failing to reject is not agreement; portability within margin \(m\) is shown when the 95% interval for \(\bar d\) lies inside \([-m, m]\). A shift confined to a few tasks dilutes the mean, so per-task differences need inspection too.
The snippet simulates the cross-stack check that the hub's portability question calls for. One policy is run on 400 tasks through two stacks; stack B mis-parses a tool format on about 10% of tasks, which cuts the solve rate on those tasks by 70%. It reports the aggregate pass rates, the paired difference with a confidence interval, McNemar's test on single trials, how many of the 20 largest per-task gaps fall on the affected tasks, and a content digest of the kind a hub revision pins.
import hashlib, numpy as np
from scipy.stats import binomtest
rng = np.random.default_rng(1)
N, K = 400, 4 # tasks, trials per task per stack
p_task = rng.beta(1.2, 1.2, N) # latent per-task solve rate of one policy
bad = rng.random(N) < 0.10 # stack B mis-parses a tool format on 10% of tasks
p_b = np.where(bad, 0.3 * p_task, p_task)
a = rng.binomial(K, p_task) / K # per-task pass rate through stack A
b = rng.binomial(K, p_b) / K # same tasks, same policy, stack B
print(f"pass rate A={a.mean():.3f} B={b.mean():.3f} diff={a.mean()-b.mean():+.3f}")
d = a - b # paired per-task difference
se = d.std(ddof=1) / np.sqrt(N)
print(f"paired diff={d.mean():+.3f} 95% CI=[{d.mean()-1.96*se:+.3f}, {d.mean()+1.96*se:+.3f}]")
a1, b1 = rng.binomial(1, p_task), rng.binomial(1, p_b) # one trial each: McNemar on discordant pairs
n10, n01 = int(((a1 == 1) & (b1 == 0)).sum()), int(((a1 == 0) & (b1 == 1)).sum())
print(f"discordant A-only={n10} B-only={n01} McNemar p={binomtest(n10, n10 + n01).pvalue:.4f}")
worst = np.argsort(d)[::-1][:20] # largest per-task gaps point at the cause
print(f"flagged tasks in top-20 gaps: {bad[worst].sum()}/20 (base rate {bad.mean():.2f})")
files = {"task.toml": b'version = "1.0"', "tests/test.sh": b"pytest -q"} # pin by content hash
h = hashlib.sha256(b"".join(k.encode() + v for k, v in sorted(files.items()))).hexdigest()[:12]
print("environment digest:", h)
Output: the aggregate gap is under three points and neither test is significant, yet the largest per-task gaps are concentrated on the affected tasks at about five times the base rate.
pass rate A=0.509 B=0.482 diff=+0.027
paired diff=+0.027 95% CI=[-0.004, +0.058]
discordant A-only=77 B-only=70 McNemar p=0.6208
flagged tasks in top-20 gaps: 9/20 (base rate 0.09)
environment digest: d9bb7bcae906
The confidence interval includes zero, so a naive test reports "no difference", but it also extends to almost six points, so equivalence within a two-point margin is not shown. The ranked per-task gaps are the useful output: they name the tasks to open, and opening them is how a parser, template or timeout difference is found.
Operating environments from a hub resembles operating dependencies from a package registry, except that environment code executes inside the training cluster. Pin each environment by revision and image digest, never by name or branch, and log both per rollout. Run hub code only in the sandbox tier, without credentials and with restricted egress. Mirror what a run depends on, so a deleted repository cannot change it in flight. Read the card: reusing dataset repos gives environments versioning, gating and cards (Hugging Face 2026), and the card is where defects, verifier limits and licences belong.
Tags and generated loading snippets are uploader declarations. A cross-stack agreement run is cheap next to a training run and belongs in the import gate beside oracle and null-agent checks. Public evaluation environments with reference solutions can also leak into crawls and training mixtures, so held-out evaluations are better kept gated, with their revision recorded.
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 it accepts, including accepted non-solutions, is what the policy learns, so a verifier deserves the treatment of a product: tests, versions and audits.
Formally, a verifier is a map \(V\) from a finished episode \(\tau\) (transcript plus final state) to \(\{0,1\}\cup\{\bot\}\), where \(\bot\) means "could not be scored". Against the true correctness \(c(\tau)\in\{0,1\}\) its quality is summarized by two error rates, the false-positive rate \(\rho_0=\Pr[V=1\mid c=0]\) and the false-negative rate \(\rho_1=\Pr[V=0\mid c=1]\). If the errors depend only on correctness, the expected reward at true solve rate \(p\) is
\[ \mathbb{E}[V] = \rho_0 + (1-\rho_0-\rho_1)\,p , \]an affine function of \(p\) with slope \(1-\rho_0-\rho_1\). Uniform noise therefore shrinks the policy gradient without turning it, a point made formally by Cai et al. (2025). The hazard is error that depends on the response \(o\): if \(\rho_0=\rho_0(o)\), the gradient of the expected reward gains the term \((1-p)\,\nabla_\theta\,\mathbb{E}_{o\sim\pi_\theta}[\rho_0(o)]\), a direct incentive to produce whatever the verifier wrongly accepts. Episodes with \(V=\bot\) are dropped from the batch rather than scored 0, because a 0 would push down whatever behavior happened to coincide with an infrastructure failure.
Error rates are estimated by auditing: sample episodes the verifier scored 1 and episodes it scored 0, have a stronger grader or a person label them, and convert the two shares into precision and recall using the observed reward rate. The Wilson interval keeps small counts honest.
import math
def wilson(k, n, z=1.96):
"""Point estimate and 95% Wilson interval for a proportion k/n."""
p = k / n; den = 1 + z * z / n
c = (p + z * z / (2 * n)) / den
h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / den
return p, c - h, c + h
def audit(reward_rate, wrong_in_ones, n_ones, right_in_zeros, n_zeros):
"""Estimate precision and recall from two audited samples:
n_ones episodes the verifier scored 1, n_zeros it scored 0."""
prec = 1 - wrong_in_ones / n_ones # P(correct | R=1)
q = right_in_zeros / n_zeros # P(correct | R=0)
tp, fn = reward_rate * prec, (1 - reward_rate) * q
return prec, wilson(wrong_in_ones, n_ones), q, wilson(right_in_zeros, n_zeros), tp / (tp + fn)
def observed_reward(p, rho0, rho1):
"""Expected verifier reward when the true solve rate is p."""
return rho0 + (1 - rho0 - rho1) * p
prec, (_, flo, fhi), q, (_, qlo, qhi), rec = audit(0.43, 2, 400, 31, 400)
print(f"precision {prec:.3f} (FP share CI [{flo:.3f}, {fhi:.3f}])")
print(f"correct among zeros {q:.3f} (CI [{qlo:.3f}, {qhi:.3f}]) -> recall {rec:.3f}")
for p in (0.2, 0.5, 0.8):
print(f"true p={p:.1f} observed={observed_reward(p, rho0=0.005, rho1=0.14):.3f}")
Output: precision with the interval on its false-positive share, the recall implied by 31 correct answers found among 400 zeros at a 43% reward rate, and how a 14% false-negative rate deflates the reported reward at three true solve rates.
precision 0.995 (FP share CI [0.001, 0.018])
correct among zeros 0.077 (CI [0.055, 0.108]) -> recall 0.906
true p=0.2 observed=0.176
true p=0.5 observed=0.432
true p=0.8 observed=0.689
In production a verifier is a service on the critical path of every training step and the definition of the objective, so it is operated like one. Each verifier has an owner, a version recorded in every trajectory, a test suite that gates releases, and a dashboard: audited precision and recall per environment, the distribution of reason codes (no answer, mismatch, timeout, unreadable state), the share of episodes returned as "not scored", and latency at the 99th percentile. Audits run on a fixed cadence because error rates drift as the policy changes the distribution of answers; a check that was 99% precise on an early checkpoint can be gamed by a later one. Open tooling has converged on the same separation: Prime Intellect's Verifiers library packages rubrics and reward functions with the environment, and NeMo Gym's Harbor integration validates reference solutions and masks verification failures out of training.
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.
| Verifier | What it checks | Example | Typical false positive | Typical false negative |
|---|---|---|---|---|
| Test-based | Hidden tests pass after the episode | SWE and terminal tasks | Weak tests; agent edits tests or special-cases inputs | Flaky or over-specific tests |
| State-based | Final DB / filesystem matches goal; nothing else changed | τ-bench database comparison | Goal state reachable by a shortcut | Several valid end states, only one encoded |
| Rule / exact match | Normalized answer equals reference | Math and puzzles (RLVR) | Rare: answer guessed without work | Equivalent forms rejected |
| Rubric + LLM judge | Per-criterion judgments, aggregated | Medical or research answers | Judge persuaded by style or adversarial text | Judge misses correct but unusual answers |
| Learned reward model | Score from a trained model | Generative verifiers | Exploitable patterns after many updates | Out-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, so roughly one correct answer in seven scored wrong, with recall falling as policies improve. A trained generative verifier recovered many of those answers but was exploited during RL (single symbols and gibberish were accepted) until training collapsed. A hybrid that consults the model only when the rule rejects 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, improving on Likert-style judge rewards by up to 31% relative on HealthBench and 7% on GPQA-Diamond.
Precision and recall. At true solve rate \(p\), a verifier with recall \(R=1-\rho_1\) and false-positive rate \(\rho_0\) has precision
\[ \text{Prec} = \frac{pR}{pR + (1-p)\rho_0}. \]Precision depends on \(p\), so the same checker looks worse on hard tasks where wrong answers dominate. Rule-based checks sit at very low \(\rho_0\) and moderate \(R\); model-based checks raise \(R\) but have a \(\rho_0(o)\) that is large on some inputs, which is what optimization finds.
Cascades. A hybrid accepts when the rule accepts and otherwise consults the model. Its rates are
\[ R_h = R_r + (1-R_r)\,R_{m\mid r=0}, \qquad \rho_{0,h} = \rho_{0,r} + (1-\rho_{0,r})\,\rho_{0,m\mid r=0}, \]where the model's rates are conditional on the rule rejecting. That slice is enriched for unusual formats and for junk, so the model's error must be measured there, not on a random sample. If some response class \(E\) earns expected reward \(a=\Pr[V=1\mid o\in E]\) with no work, and honest attempts succeed with probability \(p\), then \(E\) is the better strategy whenever \(a>p\): on hard tasks a small exploitable acceptance rate dominates. A sanity filter that sends no response in \(E\) to the model sets \(a=0\) on that class.
Rubrics. With rubric items \(i=1,\dots,k\), weights \(w_i\) and judge verdicts \(j_i\in\{0,1\}\), the reward is \(r=\sum_i w_i j_i/\sum_i w_i\). If each verdict errs independently with probability \(\varepsilon\), the variance of the score error is \(\varepsilon(1-\varepsilon)\sum_i w_i^2/(\sum_i w_i)^2\), which for equal weights is \(1/k\) of a single holistic verdict with the same error rate. Independence is optimistic, since one judge shares biases across items, but it explains part of why per-item scoring is more stable than one Likert rating.
The simulation below builds an audited pool of responses in three styles (canonical answers, equivalent variant forms, and junk such as a lone brace) and scores it with a rule that rejects variants, a model judge that accepts most correct variants but also 30% of junk, and two cascades. The error parameters are illustrative; the structure of the result is not.
import numpy as np
rng = np.random.default_rng(0)
# Synthetic audited pool: true correctness and answer style for each response.
STYLES = ["canonical", "variant", "junk"] # junk: a lone brace, gibberish
def sample(n, p_correct=0.5, p_variant=0.3, p_junk=0.05):
style = rng.choice(3, size=n, p=[1 - p_variant - p_junk, p_variant, p_junk])
correct = (rng.random(n) < p_correct) & (style != 2)
return correct, style
def rule(correct, style): # exact match after normalization
return correct & (style == 0) # rejects equivalent variant forms
def model(correct, style): # generative equivalence judge
ok = rng.random(correct.size)
return np.where(style == 2, ok < 0.30, # exploitable on junk
np.where(correct, ok < 0.92, ok < 0.02))
def sane(style): # length / charset filter on the extracted answer
return style != 2
def cascade(correct, style, guard=True):
r = rule(correct, style)
ask = ~r & (sane(style) if guard else True) # consult the model only when the rule rejects
return r | (ask & model(correct, style))
def pr(pred, correct):
tp = (pred & correct).sum()
return tp / max(pred.sum(), 1), tp / correct.sum()
c, s = sample(200_000)
for name, pred in [("rule", rule(c, s)), ("model", model(c, s)),
("cascade, no guard", cascade(c, s, guard=False)),
("cascade + guard", cascade(c, s))]:
p, r = pr(pred, c)
junk_rate = pred[s == 2].mean()
print(f"{name:18s} precision {p:.3f} recall {r:.3f} reward on junk {junk_rate:.2f}")
Output: precision, recall and the reward paid for junk under each design.
rule precision 1.000 recall 0.686 reward on junk 0.00
model precision 0.947 recall 0.919 reward on junk 0.29
cascade, no guard precision 0.950 recall 0.975 reward on junk 0.30
cascade + guard precision 0.979 recall 0.976 reward on junk 0.00
The rule never accepts junk but misses every variant. The model alone recovers recall at the cost of paying 0.29 per junk response, which on a task the policy solves less than 29% of the time is a better strategy than trying. The unguarded cascade inherits that exploit; the guarded one keeps nearly all of the recall gain and pays nothing for junk, which is the qualitative pattern Huang et al. (2025) report for their hybrid.
Choosing a verifier. The practical rule is to use the most executable check the task allows and add a judge only for what code cannot see. Coding and terminal tasks are graded by hidden tests run after the agent exits; database and tool tasks by end-state queries; math by normalized matching with a symbolic-equivalence step; open-ended answers by rubrics. Where a rubric item can be checked by a program (a length limit, a required field, a test that must fail before the patch and pass after), it should be, as RLCF (Viswanathan et al. 2025) does by mixing programmatic and judged checklist items.
Operating judges. A judge is a model in the reward path, so it is pinned to a version, served with deterministic decoding, and calibrated against human labels on a held-out set before every change. It costs one call per rubric item per rollout unless items are batched into one prompt, and batching reintroduces holistic bias. Judges have exploitable preferences: Zhao et al. (2025) found that contentless "master key" responses such as a lone colon or "Thought process:" fooled LLM judges used as reward models. Standard guards are adversarial-suffix tests in the verifier suite, a cap on reward for very short outputs, answer-only comparison where a reference exists, and a dashboard alert when the share of rewarded responses under a few tokens rises.
Learned reward models are the most exposed. Their true quality first rises and then falls as the policy moves away from the reference model, the overoptimization curve measured by Gao et al. (2022), so they are run with a KL budget, periodic re-scoring by a stronger grader, and early stopping on held-out executable tasks.
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: 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, and 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. The verifier reads state through a path the agent cannot write to (here a read-only connection; for coding tasks, tests copied in after the agent exits). Success requires the absence of side effects, an idea popularized by the collateral-damage checks of AppWorld (Trivedi et al. 2024). And the return value distinguishes "failed" from "could not be scored".
Let \(s_0\) be the environment state at reset() and \(s_T\) the state when the episode ends. The task defines a goal set \(G\) of acceptable end states; the verifier encodes an approximation \(\hat G\). False negatives are end states in \(G\setminus\hat G\) (a valid refund to a reissued card that the check does not list); false positives are end states in \(\hat G\setminus G\) (a shortcut that reaches the checked rows without doing the task). Writing \(\hat G\) as a disjunction of accepted row-sets shrinks the first set without growing the second.
Collateral damage is an invariant. Let \(W\) be the part of the state the task is allowed to write and \(\pi_{\bar W}\) the projection onto everything else. The headline reward is
\[ r(\tau) = \mathbf{1}\big[s_T\in\hat G\big]\cdot\mathbf{1}\big[\pi_{\bar W}(s_T)=\pi_{\bar W}(s_0)\big], \qquad r=\bot \text{ if } s_T \text{ is unreadable.} \]An allow-list \(W\) is stricter than a deny-list of protected tables: any write outside the task's footprint fails, including writes to tables nobody thought to protect. Comparisons are order-insensitive multiset equalities, since SQL returns rows in no guaranteed order. Comparing full snapshots costs \(O(n\log n)\) per table for sorting; replacing each snapshot by a hash of its sorted rows makes the stored state constant-size, with collision probability about \(2^{-b}\) for a \(b\)-bit digest. For large databases the cheaper route is a write log: check that every logged write falls inside \(W\), at cost proportional to the number of changes.
A compact state verifier for a customer-service task: goals are written as alternative accepted row-sets, collateral damage is checked against digests of protected views (a whole table, or "every order except the target") taken at reset, and an unreadable database yields None rather than 0. Six scripted episodes exercise it.
import hashlib, os, sqlite3, tempfile
def digest(conn, sql):
"""Order-insensitive fingerprint of a query result: hash of its sorted rows."""
rows = sorted(conn.execute(sql).fetchall())
return hashlib.sha256(repr(rows).encode()).hexdigest()[:16]
def verify(db, before, goal_sql, accepted, protected):
"""accepted: alternative row-sets, any of which satisfies the goal.
protected: {name: sql} views the task must not change; before: their digests at reset().
Returns reward 1/0, or None when the state cannot be read."""
try:
conn = sqlite3.connect(f"file:{db}?mode=ro", uri=True)
try:
got = sorted(conn.execute(goal_sql).fetchall())
after = {k: digest(conn, q) for k, q in protected.items()}
finally:
conn.close()
except sqlite3.Error as e:
return {"reward": None, "why": f"unscorable: {e.__class__.__name__}"}
goal = any(got == sorted(map(tuple, a)) for a in accepted)
touched = [k for k in protected if after[k] != before[k]]
return {"reward": float(goal and not touched), "goal": goal, "touched": touched}
def episode(path, action):
if os.path.exists(path): os.remove(path)
c = sqlite3.connect(path)
c.executescript("""CREATE TABLE orders(id INT, status TEXT);
CREATE TABLE refunds(order_id INT, amount REAL, method TEXT);
CREATE TABLE customers(id INT, tier TEXT);
INSERT INTO orders VALUES (17,'open'),(18,'open');
INSERT INTO customers VALUES (1,'gold'),(2,'basic');""")
before = {k: digest(c, q) for k, q in PROTECTED.items()}
action(c); c.commit(); c.close()
return before
PROTECTED = {"customers": "SELECT * FROM customers",
"other orders": "SELECT * FROM orders WHERE id <> 17"}
GOAL = "SELECT o.status, r.amount, r.method FROM orders o JOIN refunds r ON r.order_id=o.id WHERE o.id=17"
ACCEPT = [[("cancelled", 42.5, "card_4242")], # refund to card
[("cancelled", 42.5, "card_4242_reissued")]] # also valid per policy
good = lambda c: (c.execute("UPDATE orders SET status='cancelled' WHERE id=17"),
c.execute("INSERT INTO refunds VALUES (17, 42.5, 'card_4242')"))
alt = lambda c: (c.execute("UPDATE orders SET status='cancelled' WHERE id=17"),
c.execute("INSERT INTO refunds VALUES (17, 42.5, 'card_4242_reissued')"))
bribe = lambda c: (good(c), c.execute("UPDATE customers SET tier='gold' WHERE id=2"))
sweep = lambda c: (good(c), c.execute("UPDATE orders SET status='cancelled' WHERE id=18"))
claim = lambda c: None # says "done", changes nothing
d = tempfile.mkdtemp(); p = os.path.join(d, "s.db")
for name, act in [("reference", good), ("alternative", alt), ("collateral", bribe), ("over-reach", sweep), ("claim only", claim)]:
b = episode(p, act); print(f"{name:12s}", verify(p, b, GOAL, ACCEPT, PROTECTED))
print(f"{'missing db':12s}", verify(os.path.join(d, "gone.db"), b, GOAL, ACCEPT, PROTECTED))
Output: both valid end states score 1; touching a protected table or cancelling a second order scores 0 although the goal query passes; a claim with no state change scores 0; a missing database is unscorable.
reference {'reward': 1.0, 'goal': True, 'touched': []}
alternative {'reward': 1.0, 'goal': True, 'touched': []}
collateral {'reward': 0.0, 'goal': True, 'touched': ['customers']}
over-reach {'reward': 0.0, 'goal': True, 'touched': ['other orders']}
claim only {'reward': 0.0, 'goal': False, 'touched': []}
missing db {'reward': None, 'why': 'unscorable: OperationalError'}
Two details matter. The connection is opened read-only through a URI, so the verifier cannot repair or alter the state it judges. The "other orders" view protects part of a table the task is allowed to write, which a table-level protected list cannot express.
Where state verification is used. τ-bench scores airline and retail conversations by comparing the final database with the state produced by the annotated correct actions; AppWorld adds explicit collateral-damage checks across its simulated apps. Enterprise and computer-use environments apply the same pattern to CRM records, files and application state.
Engineering the read path. Snapshots are cheapest when the environment's storage supports them: a copy-on-write database file or a filesystem snapshot at reset(), and a read-only mount or a separate database user for the verifier. For coding tasks the analogous step is copying hidden tests in after the agent exits, or exporting the patch and grading it in a fresh sandbox, so that nothing the agent wrote can reach the grader.
Failure modes. Volatile fields (timestamps, auto-increment keys, generated identifiers) make equal states compare unequal, producing false collateral failures; verifiers normalize or exclude them explicitly. Schema changes between environment versions silently break queries, so the verifier is versioned with the environment image. An agent that leaves a transaction open or a file locked produces unreadable state; that must surface as "not scored" with an error class, and a rising unscored rate is an infrastructure alert, not a learning signal (see Rollout Systems). Useful dashboard splits are goal-failed versus collateral-failed versus unscored per task, because a task where most failures are collateral usually has an under-specified allowed footprint rather than a weak policy.
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. With 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, which matters most when group-relative methods such as GRPO would otherwise see all-zero groups. The risk is a policy that collects easy criteria and stops; keep a dominating binary success term and 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)\) for any potential function \(\Phi\) over states leaves the optimal policy unchanged, because the shaping terms telescope along any trajectory. Agent environments rarely have a natural \(\Phi\), though "fraction of target tests passing" is a candidate.
Why partial credit helps group-relative methods. GRPO normalizes rewards within a group of \(G\) rollouts of the same task, so a group whose rewards are all equal contributes no gradient. With binary reward and success probability \(p\), a group is informative with probability \(1-p^G-(1-p)^G\); at \(p=0.02\) and \(G=8\) that is about 0.15, so most rollouts on hard tasks are wasted. A partial score over several criteria varies across rollouts long before full success does.
Keeping success dominant. With binary success \(b\in\{0,1\}\) and partial score \(\bar c\in[0,1]\), the reward \(r=b+\lambda\bar c\) with \(0\le\lambda<1\) guarantees that every success outranks every failure, since a failure earns at most \(\lambda<1\le r_{\text{success}}\). The policy can still prefer easy criteria over attempts at success when \(\lambda\,\Delta\bar c > \Delta p\), which is why runs are judged on \(b\) alone.
Potential-based shaping. Adding \(F(s,s')=\gamma\Phi(s')-\Phi(s)\) to every step gives a discounted shaping sum that telescopes:
\[ \sum_{t=0}^{T-1}\gamma^t F(s_t,s_{t+1}) = \gamma^T\Phi(s_T)-\Phi(s_0). \]With \(\Phi=0\) at terminal states, the shaped action values are \(Q'(s,a)=Q(s,a)-\Phi(s)\), a per-state offset that leaves every argmax unchanged (Ng et al. 1999). The terminal condition matters in episodic agent tasks: if \(\Phi\) is "fraction of target tests passing" and is not zeroed at the end, the sum becomes \(\Phi(s_T)-\Phi(s_0)\), which is exactly a terminal partial-credit reward and does change the optimum.
Two checks. The first compares, at the same full-success rate, how often a group of eight carries any signal under binary reward and under a four-criterion partial score. The second solves a random six-state MDP by value iteration with the original reward, with potential-based shaping, and with an ad hoc bonus for reaching states of high \(\Phi\).
import numpy as np
rng = np.random.default_rng(1)
# 1) How often a GRPO group of G rollouts carries any signal (non-zero reward variance).
def informative_binary(p, G):
return 1 - p**G - (1 - p)**G
def informative_partial(q, k, G, trials=20_000):
"""k equally weighted criteria, each met independently with prob q; reward = share met."""
r = (rng.random((trials, G, k)) < q).mean(axis=2)
return (r.std(axis=1) > 0).mean()
for p in (0.001, 0.02, 0.1, 0.5): # same full-success rate p in both rows: q = p**(1/4)
print(f"G=8 success p={p:<5} binary informative {informative_binary(p, 8):.3f} "
f"partial (4 criteria) {informative_partial(p ** 0.25, 4, 8):.3f}")
# 2) Potential-based shaping leaves the optimal policy unchanged (random MDP, value iteration).
S, A, gamma = 6, 3, 0.95
P = rng.dirichlet(np.ones(S), size=(S, A)) # P[s, a, s']
R = rng.normal(size=(S, A))
def greedy(Rsa):
V = np.zeros(S)
for _ in range(2000):
Q = Rsa + gamma * P @ V
V = Q.max(1)
return Q.argmax(1), Q
Phi = rng.normal(scale=5, size=S)
R_pot = R + gamma * P @ Phi - Phi[:, None] # E[gamma*Phi(s') - Phi(s)]
R_bad = R + 2.0 * (P @ Phi) # non-potential bonus for reaching high-Phi states
pi, Q = greedy(R); pi_pot, Q_pot = greedy(R_pot); pi_bad, _ = greedy(R_bad)
print("optimal policy ", pi)
print("potential-shaped", pi_pot, " Q shift = -Phi(s):", np.allclose(Q_pot, Q - Phi[:, None]))
print("ad hoc bonus ", pi_bad)
Output: the share of informative groups, then the three greedy policies and a check that potential shaping shifts \(Q\) by exactly \(-\Phi(s)\).
G=8 success p=0.001 binary informative 0.008 partial (4 criteria) 0.998
G=8 success p=0.02 binary informative 0.149 partial (4 criteria) 0.999
G=8 success p=0.1 binary informative 0.570 partial (4 criteria) 0.999
G=8 success p=0.5 binary informative 0.992 partial (4 criteria) 0.996
optimal policy [1 0 2 0 0 1]
potential-shaped [1 0 2 0 0 1] Q shift = -Phi(s): True
ad hoc bonus [0 1 1 1 1 0]
Partial credit makes almost every group informative even at a success rate of 0.1%; potential-based shaping reproduces the optimal policy exactly, while an equally sized bonus that is not a potential difference changes it in most states.
Production environments usually return a structured result: a binary headline reward, a partial score, and per-criterion outcomes. Which of these enters the advantage is a training decision made per run and recorded with the run, while the binary metric is what dashboards and comparisons use. A partial score is most useful outside the gradient: for pass-rate filtering, where tasks whose groups would be all-zero or all-one are dropped or deferred, and for curricula that order tasks by partial progress. Dynamic sampling in DAPO takes the filtering route, resampling until groups have non-zero variance instead of changing the reward.
Per-step rewards are where shaping goes wrong in agent environments. A bonus for every tool call that exits successfully teaches the agent to run harmless commands; a bonus for files edited teaches churn. The diagnostic signature is a rising shaped component with flat binary success and growing episode length. Remedies are capping the dense component per episode, decaying its weight to zero over training, or replacing it with a progress signal that is hard to fake, such as credit only when a previously failing hidden test starts passing, checked by the grader rather than reported by the agent.
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, and 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, and 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, versus 0.7% on HCAST tasks, and 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 they do not. Hiding tests cut cheating to near zero but hurt legitimate performance.
- Anthropic (2025) found that a model which learned hacks such as exiting the test harness with a success code during RL on real coding environments 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.
The environment-side mitigations follow directly. Mount tests read-only or copy them in after the agent exits; run verification in a fresh sandbox when the agent could have tampered with the runtime (NeMo Gym's Harbor runner supports this); keep scorer code and reference solutions out of the agent's filesystem; give the agent a legitimate way to report an impossible task; and run a monitor over trajectories that flags test edits or scorer access, since ImpossibleBench found 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.
Definition. Let \(\hat J(\pi)\) be expected verifier reward and \(J^\star(\pi)\) expected true success. Following Skalse et al. (2022), the pair is hackable if some policies \(\pi,\pi'\) satisfy \(\hat J(\pi')>\hat J(\pi)\) while \(J^\star(\pi') and the policy gradient \(\mathbb{E}[\hat R\,\nabla\log\pi(\tau)]\) cannot tell them apart. Dynamics. For a softmax policy over strategies with logits \(z_i\), exact gradient ascent gives \(\dot z_i=\eta\,\pi_i\,(Q_i-\bar Q)\), where \(Q_i\) is the expected reward of strategy \(i\) and \(\bar Q\) the policy's average. A hack with \(Q_K=1\) on a task where honest work succeeds with \(Q_H=p\) grows slowly while \(\pi_K\) is tiny and then quickly, because its own probability multiplies its growth rate: the exploit share follows an S-curve and is easy to miss until it dominates. Measuring it. If a monitor with recall \(\rho\) flags a share \(f\) of rewarded episodes, the hack share is about \(h\approx f/\rho\), and true success is \((1-h)\hat J\). ImpossibleBench monitors had \(\rho\) of only 0.42 to 0.65 on SWE-scale tasks, so a flag rate must be divided by roughly two before it says anything about prevalence. A legitimate abort action adds a strategy with positive reward on impossible tasks, which lowers \(Q_K-\bar Q\) for the hack and explains why the option cut cheating sharply in that study.
A three-strategy model of a hard coding task makes the dynamics concrete. A real fix passes 10% of the time; editing the tests always passes if the verifier reads tests the agent can write; giving up scores 0. The policy starts with a 1% chance of editing tests and is trained with group-relative advantages, once against a verifier that reads the agent's tests and once against one that copies tests in after the agent exits.
import numpy as np
# Three strategies an agent can take on a coding task. "edit_tests" passes only if the
# verifier reads tests the agent could write; the real fix passes 10% of the time.
STRATS = ["real_fix", "edit_tests", "give_up"]
def reward(k, rng, tests_writable):
if k == 0: return float(rng.random() < 0.10)
if k == 1: return 1.0 if tests_writable else 0.0
return 0.0
def train(tests_writable, steps=400, G=16, lr=0.3, seed=0):
rng = np.random.default_rng(seed)
logits = np.array([0.0, -4.0, 0.0]) # hacking starts rare: about 1% of rollouts
for t in range(steps + 1):
pi = np.exp(logits - logits.max()); pi /= pi.sum()
if t in (0, 100, 200, 400):
shown, true = 0.1 * pi[0] + pi[1] * tests_writable, 0.1 * pi[0]
print(f" step {t:3d} " + " ".join(f"{s} {p:.2f}" for s, p in zip(STRATS, pi))
+ f" | reward {shown:.2f} true success {true:.3f}")
ks = rng.choice(3, size=G, p=pi)
r = np.array([reward(k, rng, tests_writable) for k in ks])
adv = (r - r.mean()) / (r.std() + 1e-6) # group-relative advantage
grad = sum(a * (np.eye(3)[k] - pi) for a, k in zip(adv, ks)) / G
logits += lr * grad
print("verifier reads tests the agent can write:"); train(True)
print("tests copied in after the agent exits:"); train(False)
# Audit arithmetic: a monitor with recall rho flags share f of successes -> hack share ~ f / rho.
for f, rho in [(0.05, 0.89), (0.05, 0.42)]:
print(f"flagged {f:.2f} with monitor recall {rho:.2f} -> hack share ~ {f / rho:.3f}")
Output: strategy probabilities, verifier reward and true success at four steps for each design, then the monitor-recall correction.
verifier reads tests the agent can write:
step 0 real_fix 0.50 edit_tests 0.01 give_up 0.50 | reward 0.06 true success 0.050
step 100 real_fix 0.79 edit_tests 0.09 give_up 0.12 | reward 0.17 true success 0.079
step 200 real_fix 0.00 edit_tests 0.99 give_up 0.00 | reward 1.00 true success 0.000
step 400 real_fix 0.00 edit_tests 1.00 give_up 0.00 | reward 1.00 true success 0.000
tests copied in after the agent exits:
step 0 real_fix 0.50 edit_tests 0.01 give_up 0.50 | reward 0.05 true success 0.050
step 100 real_fix 0.92 edit_tests 0.00 give_up 0.07 | reward 0.09 true success 0.092
step 200 real_fix 0.97 edit_tests 0.00 give_up 0.03 | reward 0.10 true success 0.097
step 400 real_fix 0.99 edit_tests 0.00 give_up 0.01 | reward 0.10 true success 0.099
flagged 0.05 with monitor recall 0.89 -> hack share ~ 0.056
flagged 0.05 with monitor recall 0.42 -> hack share ~ 0.119
With writable tests the exploit is rare at step 100 and total by step 200, while reported reward climbs to 1.00 and true success falls to zero; the same policy trained against copied-in tests learns the real fix. The environment change, not the algorithm, decides the outcome.
Separating agent and grader. The most effective single measure is to export the agent's artifact (a patch, a database dump, a file) and grade it in a fresh sandbox that never ran agent code, dropping edits to protected paths. Re-grading only the rewarded episodes keeps the cost proportional to successes. The gap between training reward and fresh re-grade on the same episodes is then a direct tampering metric, alongside the share of patches touching tests or CI configuration and held-out success on environments the run never trained on.
Removing leaks. Reference solutions, scorer code and upstream history must not be in the image. A Cursor (2026) audit found agents retrieving upstream fixes from the web or mining future commits from bundled .git history; an RL environment with the same leak trains answer retrieval. Network access is restricted to what the task needs.
Monitors and canaries. Trajectory monitors, whether pattern scanners or LLMs trained on labeled sets such as METR's MALT, are used for auditing, filtering and stopping, not as reward terms: Baker et al. (2025) found that optimizing against a chain-of-thought monitor produced obfuscated hacking. Impossible tasks with conflicting tests, in the style of ImpossibleBench, make good canaries mixed into training at a low rate, since any pass on them is a hack.
Response. When an exploit is confirmed, the environment is patched, the affected rewards are re-scored, and training resumes from the last checkpoint whose audit was clean, because the policy has already learned the exploit. Inoculation prompting (Anthropic 2025) limits generalization of hacks that slip through but does not replace hardening.
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, and 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, failing dataset validation if any provided reference solution does not score 1, and 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), and environment-level acceptance criteria are collected in Environment Quality Control.
Repeats and flakiness. A reference solution that fails with probability \(f\) passes \(n\) repeats with probability \((1-f)^n\). Detecting \(f\ge0.05\) with 95% confidence needs \(n\ge\ln 0.05/\ln 0.95\approx 59\) runs, and zero failures in \(n\) runs bounds \(f\le 3/n\) at 95% (the rule of three). A handful of repeats catches gross nondeterminism only; low-rate flakes are found by tracking reference pass rates across releases.
Version changes. A new verifier version is compared with the old one on a frozen set of \(N\) rollouts. With \(n_{01}\) episodes moving from 0 to 1 and \(n_{10}\) from 1 to 0, the mean reward shifts by \((n_{01}-n_{10})/N\), and McNemar's statistic \((n_{01}-n_{10})^2/(n_{01}+n_{10})\) tests whether the shift is systematic. Every flip is a reward change; training curves produced under different versions are comparable only after re-scoring.
A minimum verifier test suite runs the real verifier end to end with scripted agents instead of a model. Here the task is to implement add; hidden tests are copied in after the episode, and success requires a per-run nonce printed after every assertion, so an early exit cannot fake a pass. The verifier ships only if every case scores as expected: the reference (three repeats) and an alternative correct solution score 1; doing nothing, claiming success, editing the visible tests, exiting early, special-casing the visible input and damaging an unrelated file score 0; a lost sandbox is not scored.
import os, secrets, subprocess, sys, tempfile
HIDDEN_TESTS = "import sys; sys.path.insert(0, '.')\n" \
"from solution import add\nassert add(2, 3) == 5\nassert add(-4, 10) == 6\nassert add(10**6, 1) == 1000001\n"
START = {"solution.py": "def add(a, b):\n raise NotImplementedError\n",
"tests/test_add.py": "from solution import add\nassert add(2, 3) == 5\n", # visible test
"README.md": "project notes\n"}
PROTECTED = ["README.md"]
def verify(workspace):
"""Score a finished workspace. Hidden tests are copied in after the agent exits;
success needs a per-run nonce printed after every assertion. None = could not score."""
if workspace is None:
return None # sandbox lost: not a 0
if any(workspace.get(f) != START[f] for f in PROTECTED):
return 0.0 # collateral damage
nonce = secrets.token_hex(8)
with tempfile.TemporaryDirectory() as d:
open(os.path.join(d, "solution.py"), "w").write(workspace.get("solution.py", ""))
open(os.path.join(d, "grade.py"), "w").write(HIDDEN_TESTS + f"print('{nonce}')\n")
try:
p = subprocess.run([sys.executable, "-I", "grade.py"], cwd=d,
capture_output=True, text=True, timeout=5)
except subprocess.TimeoutExpired:
return 0.0
out = p.stdout.split()
return float(p.returncode == 0 and bool(out) and out[-1] == nonce)
def edit(**files): # scripted "agent": apply file edits
return lambda ws: {**ws, **files}
AGENTS = { # name: (agent, expected score)
"reference": (edit(**{"solution.py": "def add(a, b):\n return a + b\n"}), 1.0),
"alternative": (edit(**{"solution.py": "def add(a, b):\n return sum((a, b))\n"}), 1.0),
"null": (lambda ws: ws, 0.0),
"claims only": (lambda ws: ws, 0.0), # transcript says "done"; state unchanged
"test tampering": (edit(**{"tests/test_add.py": "pass\n"}), 0.0),
"early exit": (edit(**{"solution.py": "import os\ndef add(a, b): return 0\nos._exit(0)\n"}), 0.0),
"special-casing": (edit(**{"solution.py": "def add(a, b):\n return 5\n"}), 0.0),
"collateral": (edit(**{"solution.py": "def add(a, b):\n return a + b\n",
"README.md": ""}), 0.0),
"infra failure": (lambda ws: None, None),
}
fails = 0
for name, (agent, want) in AGENTS.items():
got = [verify(agent(dict(START))) for _ in range(3 if name == "reference" else 1)]
ok = all(g == want for g in got); fails += not ok
print(f"{'PASS' if ok else 'FAIL'} {name:15s} expected {want} got {got}")
print("verifier ships" if fails == 0 else f"blocked: {fails} failing case(s)")
Output: one line per case and the release decision.
PASS reference expected 1.0 got [1.0, 1.0, 1.0]
PASS alternative expected 1.0 got [1.0]
PASS null expected 0.0 got [0.0]
PASS claims only expected 0.0 got [0.0]
PASS test tampering expected 0.0 got [0.0]
PASS early exit expected 0.0 got [0.0]
PASS special-casing expected 0.0 got [0.0]
PASS collateral expected 0.0 got [0.0]
PASS infra failure expected None got [None]
verifier ships
The first draft of this suite failed the reference and alternative cases because Python's isolated mode (-I) leaves the script directory off the import path; that is the class of verifier bug positive tests exist to catch, since it would have scored every correct solution 0. For judge-based rewards the suite adds a case that appends persuasive text to a wrong answer and checks the score does not rise.
The suite runs in continuous integration on every change to the verifier, the task data or the environment image, and on a schedule, since dependency updates break verifiers without any code change. Tasks whose reference solution fails or flakes are quarantined automatically rather than left in the pool. NeMo Gym's Harbor tooling applies the positive half at dataset validation and masks verification failures out of training (NVIDIA 2026). A release re-scores a frozen set of recent rollouts with old and new versions and reviews every flip before promotion; the verifier version then enters each trajectory record so that later analyses know which reward produced which data. Negative cases grow over time: each confirmed hack from an audit becomes a scripted agent in the suite, so the same exploit cannot return unnoticed.
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. A vendor or an in-house team writes a working replica of an application, seeds it 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, and in 2025–2026 it became a market of its own.
What labs buy follows what they want agents to do. Interviews by Denain and Barber (2026) at Epoch AI, drawing on 18 people at environment startups and labs, describe a progression from math and coding toward enterprise workflows such as expense reports, pivot tables and CRM updates, with clones of Slack and SAP, an Airbnb-style site, a Bloomberg terminal and Excel among the examples. 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.
The four sources of environments can be compared on two quantities: the cost of a task and the fidelity of the environment to the system the agent will eventually face. Fidelity has a precise meaning. Let \(T\) be the real application's transition function and \(\hat T\) the replica's, defined over the same states \(s\) (database rows, pages, files) and actions \(a\) (tool calls, clicks), with the grader's verdict treated as the final transition. Let \(D=\{(s,a): \hat T(\cdot\mid s,a)\neq T(\cdot\mid s,a)\}\) be the set of state–action pairs on which the two disagree, and for a policy \(\pi\) acting for at most \(H\) steps define the divergence probability
\[ \varepsilon_\pi=\Pr_{\tau\sim(\pi,\hat T)}\big[\exists\, t\le H:\ (s_t,a_t)\in D\big]. \]Running both systems on shared randomness, the trajectories coincide until the first visit to \(D\). For any trajectory reward in \([0,1]\), the success rates \(J\) therefore satisfy
\[ \big|J_{\hat T}(\pi)-J_T(\pi)\big|\;\le\;\varepsilon_\pi\;\le\;\mathbb{E}_{\pi,\hat T}\big[\#\{t:(s_t,a_t)\in D\}\big]. \]Two consequences follow. First, \(\varepsilon_\pi\) belongs to the pair (replica, policy), not to the replica alone: a replica checked only on scripted happy paths can have \(\varepsilon=0\) for those scripts and \(\varepsilon\approx 1\) for a trained policy. Second, RL maximizes \(J_{\hat T}\); if \(D\) contains a cheaper route to reward than the real workflow, the maximizer moves its probability mass onto \(D\), which is reward hacking stated formally. What a hand-built environment's price buys is a small \(D\) on the workflows its tasks exercise, including errors, permissions and pagination. Mined, synthesized and simulated environments buy volume with a larger or unmeasured \(D\). A crude figure of merit for a source \(k\) is therefore \(v_k(1-\varepsilon_k)/c_k\), where \(c_k\) is the cost per task and \(v_k\) the probability that a task is valid and informative; Economics develops \(c_k\) and Environment Quality Control measures \(v_k\).
The fidelity bound can be checked on a small replica whose defect is known. The script models an eight-step workflow, such as filing and approving an expense report, in which each correct step succeeds with probability 0.8. It adds one admin endpoint that returns a permission error in the real application but, in the replica, jumps straight to the approved state because the permission check was never implemented. It plans against each system by discounted value iteration, so that faster success is preferred as it is under most RL objectives, then measures success in both systems and how often episodes touch the divergent pair.
import numpy as np
# Workflow replica: states 0..L (L = goal). Action 0 "next step" advances w.p. 0.8 in both
# real app and replica. Action 1 "admin endpoint" is a permission error in the real app
# (state unchanged) but the replica forgot the permission check and jumps to the goal.
L, H, P_OK, GAMMA = 8, 12, 0.8, 0.95
def step(s, a, replica):
if a == 0: return s + 1 if np.random.rand() < P_OK else s
return L if replica else s # the fidelity bug
def plan(replica):
"""Discounted finite-horizon value iteration (faster success is better); greedy pi[t, s]."""
V = np.zeros(L + 1); pi = np.zeros((H, L + 1), int)
for t in reversed(range(H)):
nxt = np.r_[V[1:], 0.0]; nxt[L - 1] = 1.0 # reaching L pays 1
Q0 = GAMMA * (P_OK * nxt + (1 - P_OK) * V)
Q1 = np.full(L + 1, GAMMA) if replica else GAMMA * V
pi[t] = (Q1 > Q0 + 1e-12).astype(int); V = np.maximum(Q0, Q1); V[L] = 0.0
return pi
def rollout(policy, replica, n=20000, seed=0):
"""Success rate, plus (when run in the replica) the mean number of divergent steps
per episode and the probability an episode touches a divergent (s, a) at all."""
rng = np.random.default_rng(seed); np.random.seed(seed); wins = div = hit = 0
for _ in range(n):
s, d = 0, 0
for t in range(H):
if s == L: break
a = policy(t, s, rng); d += (a == 1)
s = step(s, a, replica)
wins += (s == L); div += d; hit += (d > 0)
return wins / n, div / n, hit / n
pi_real, pi_rep = plan(False), plan(True)
policies = {"happy path (real-optimal)": lambda t, s, r: pi_real[t, s],
"explorer (10% admin calls)": lambda t, s, r: int(r.random() < 0.1),
"replica-optimal": lambda t, s, r: pi_rep[t, s]}
print(f"{'policy':27s} {'J_rep':>6s} {'J_real':>6s} {'gap':>6s} {'P[hit]':>6s} {'E[div]':>6s}")
for name, pol in policies.items():
jr, d, h = rollout(pol, True); jt, _, _ = rollout(pol, False)
print(f"{name:27s} {jr:6.3f} {jt:6.3f} {jr-jt:6.3f} {h:6.3f} {d:6.3f}")
It prints, for three policies, success in the replica and in the real application, their gap, the probability that an episode touches the bug, and the mean number of divergent steps per episode:
policy J_rep J_real gap P[hit] E[div]
happy path (real-optimal) 0.929 0.929 0.000 0.000 0.000
explorer (10% admin calls) 0.980 0.773 0.206 0.648 0.648
replica-optimal 1.000 0.000 1.000 1.000 1.000
The happy-path policy sees no difference, so a fidelity test that replays scripted workflows would pass this replica. A policy that calls the endpoint occasionally touches the bug in about two thirds of episodes and loses 0.21 of real success. The policy that is optimal for the replica uses the endpoint in every episode and solves nothing in the real application. In every row the gap stays below the probability of touching the bug, as the coupling bound requires.
A hand-built environment is delivered as a bundle: a container image holding the replica and its database, a seed-data snapshot, a tool layer (for software platforms usually an MCP server, with setup conditions and success criteria, as Kourabi and Patel (2026) describe), a reset entry point, a task set and graders kept out of the agent's reach. The scale of the supply side is visible in the 2026 acquisitions: Mercor bought Deeptune, which had recreated hundreds of enterprise applications as training gyms (SiliconANGLE 2026).
Because labs buy most of these bundles, the engineering work on the buyer's side is acceptance and operation rather than construction:
- Acceptance before payment. The bundle must build from a pinned recipe, reset to byte-identical state, and pass the gold and no-op checks for every task. Where the real product can be licensed, traces recorded against it are replayed on the replica and the state after each call is compared, with error, permission and pagination paths included deliberately.
- Adversarial shakedown. A current model is trained or prompted against the replica specifically to find shortcuts. An RL policy is the most effective bug finder a replica will ever meet, so it is cheaper to meet it during acceptance than mid-run.
- Monitoring in training. A sudden rise in one environment's reward together with shorter episodes is the signature of a discovered shortcut; such environments are quarantined, sampled trajectories are reviewed, and the vendor patches and re-versions the replica.
- Drift and reuse. Real products change their interfaces, so replicas are pinned by version and refreshed on a schedule; consumer UI gyms are bought once and reused across model generations, which amortizes their price.
- Data hygiene. Seed data is synthetic, never copied from a customer instance, because trajectories and replicas circulate widely inside a lab.
Economics
Hand-built environments are priced per task and per replica, and the reported numbers span four orders of magnitude. Epoch's interviewees put typical task prices at $200–$2,000, with a $20,000 task "rare but possible"; one interviewee put a high-fidelity replica of a complex product near $300,000. Contracts are often six to seven figures per quarter, and two founders independently said exclusivity costs roughly four to five times more than a non-exclusive license (Denain and Barber 2026). These are interview estimates, not audited prices, and they will move quickly.
Two comparisons put the prices in context. Training compute per task is of the same order as the task itself (Epoch cites a Mechanize estimate of about $2,400 over a task's useful life), which argues against cheap tasks that waste it. And mined or synthesized tasks cost cents to dollars (next section), so a hand-built task must earn a premium of several orders of magnitude through fidelity, difficulty or coverage that automation cannot reach.
A per-task price is only half of a task's cost. Let task \(i\) have purchase price \(c_i\) and be used for \(K\) groups of \(G\) rollouts at compute cost \(c_g\) per group. Under group-relative methods such as GRPO a group produces a gradient only if it contains both a success and a failure, which for per-rollout pass rate \(p\) happens with probability
\[ s(p)=1-p^{G}-(1-p)^{G}. \]The cost per informative group is then
\[ \kappa_i=\frac{c_i+K c_g}{K\,\mathbb{E}[s(p_i)]}. \]Two regimes follow. When \(c_i\ll Kc_g\), as for mined or synthesized tasks, \(\kappa\approx c_g/\mathbb{E}[s]\): cost is set by informativeness, and a pool with many tasks at \(p\in\{0,1\}\) wastes compute in proportion. When \(c_i\) is comparable to \(Kc_g\), price and compute both count. With the figures Epoch's interviewees gave (lifetime compute near $2,400 per task, from a Mechanize estimate, and task prices of $200–$2,000), a $1,000 task raises lifetime cost relative to a $1 task by a factor \((1000+2400)/(1+2400)\approx 1.42\), not 1,000. The several-orders-of-magnitude premium a hand-built task must earn is per purchase dollar; per unit of total spend the premium is modest, which is the substance of the argument that cheap tasks waste compute (Erdil et al. 2025).
An exclusive license multiplies the price by \(m\approx 4\)–\(5\), so lifetime cost becomes \(mc_i+Kc_g\); at \(c_i=\$1{,}000\) and \(m=4.5\) that is $6,900 against $3,400. Two further terms complete the model. Tasks depreciate: as the policy improves, \(p_i\) rises and \(s(p_i)\) falls, so \(K\) is bounded by the number of updates before the task crosses the retirement ceiling. And tasks reused across \(N\) model generations spread \(c_i\) as \(c_i/N\), which is why UI gyms are bought once. For calibration, \(s(0.02)=0.726\) at \(G=64\) and \(0.925\) at \(G=128\), while \(s(0.97)=0.858\) at \(G=64\).
The cost model fits in a few lines. The script compares four pools of 1,000 tasks under the same lifetime compute budget: a mined pool whose pass rates include many already-solved and impossible tasks, the same pool after a few dollars of filtering rollouts, an expert pool bought at $1,000 per task, and the same expert pool under an exclusive license at 4.5 times the price. The pass-rate distributions are assumptions chosen to show the mechanism, not measurements.
import numpy as np
rng = np.random.default_rng(0)
def p_signal(p, G):
"""Probability a group of G rollouts holds both a success and a failure (GRPO signal)."""
return 1 - p**G - (1 - p)**G
G, GROUPS, COMPUTE = 64, 40, 2400.0 # lifetime compute per task ~ $2,400 (Mechanize, via Epoch)
# Pass-rate distributions are ASSUMPTIONS for illustration: a mined pool with many
# already-solved or impossible tasks, and an expert pool calibrated into the learnable band.
pools = {
"mined, unfiltered": (1.0, np.r_[np.zeros(300), np.ones(300), rng.beta(2, 2, 400)]),
"mined, filtered": (1.0+2.0, rng.beta(2, 2, 1000)), # +$2 of filtering rollouts
"expert, $1,000": (1000.0, rng.beta(1.2, 4, 1000)), # hard: many low pass rates
"expert, exclusive": (4500.0, rng.beta(1.2, 4, 1000)), # 4-5x exclusivity premium
}
print(f"{'pool':18s} {'price':>7s} {'E[signal]':>9s} {'$/task life':>11s} {'$/informative group':>19s}")
for name, (price, p) in pools.items():
s = p_signal(p, G).mean()
total = price + COMPUTE
print(f"{name:18s} {price:7.0f} {s:9.3f} {total:11.0f} {total / (GROUPS * s):19.1f}")
for p in (0.02, 0.5, 0.97):
print(f"p={p:<5} G=64 -> {p_signal(p, 64):.3f} G=128 -> {p_signal(p, 128):.3f}")
It prints each pool's expected probability that a group is informative, lifetime cost per task and cost per informative group, then the signal probability at three pass rates:
pool price E[signal] $/task life $/informative group
mined, unfiltered 1 0.399 2401 150.5
mined, filtered 3 0.997 2403 60.3
expert, $1,000 1000 0.969 3400 87.7
expert, exclusive 4500 0.971 6900 177.6
p=0.02 G=64 -> 0.726 G=128 -> 0.925
p=0.5 G=64 -> 1.000 G=128 -> 1.000
p=0.97 G=64 -> 0.858 G=128 -> 0.980
The unfiltered mined pool spends 60% of its compute on tasks that never yield a gradient, so it costs more per informative group than the $1,000 expert pool; filtering at a few dollars per task reverses that. Exclusivity roughly doubles cost per informative group. What this metric cannot see is what an informative group teaches: the expert premium is justified only if a gradient on a high-fidelity replica of a valuable workflow is worth more than a gradient on a mined bug, which has to be measured on held-out evaluations, not computed.
In practice environment spend is managed like any other procurement line, but the unit of account is learning signal rather than tasks delivered. A useful cost dashboard tracks, per source and per vendor: purchase price, compute consumed (rollout tokens, sandbox-hours), the share of groups that were informative, the pass-rate trajectory of each task under the current policy, and the date each task crossed the retirement ceiling. Dollars per informative group is the headline metric; attribution to evaluation gains needs ablation runs, which are expensive and therefore done per source rather than per task.
Several design decisions follow from the numbers above.
- Pay for calibration, not count. Contracts reported by Epoch's interviewees run to six or seven figures per quarter (Denain and Barber 2026). Tying acceptance to a pass-rate band measured against the buyer's current model at delivery aligns the vendor with the quantity that drives value.
- Price saturation in. A task calibrated for one model may be trivial for the next; refresh clauses that require harder variants, or per-generation pricing, avoid paying full price for tasks that stop producing gradients.
- Exclusivity only where it is an advantage. At four to five times the price, exclusivity pays only if competitors would otherwise train on the same workflow within the window before the tasks saturate.
- Build where the workflow is proprietary. In-house teams build replicas of internal tools and regulated domains that no vendor can see; vendors win on common SaaS products.
The failure mode to watch is buying volume that the policy cannot use: large deliveries whose pass rates sit at zero or one look productive on a procurement report and show up only as idle compute on the training dashboard.
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, report that robust graders take many iterations, and quote one lab researcher criticizing replicas that were quickly "vibe coded" and full of bugs. In practice the bar has four parts:
- 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.
- 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.
- 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).
- 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.
Each of the four requirements has a measurable counterpart.
Behavioural fidelity. Let \(\varepsilon\) be the probability that an episode reaches a state–action pair on which replica and real product differ; the gap in success rate between them is at most \(\varepsilon\). If \(n\) independent episodes replayed against both systems show no divergence, the one-sided 95% upper bound is \(\varepsilon\lesssim 3/n\) (the rule of three, from \((1-\varepsilon)^n=0.05\)). The bound holds only for the distribution that generated the episodes, so the replayed episodes must include policy rollouts, not only scripted workflows.
Expert tasks. If a fraction \(q\) of a contractor's tasks are defective, a reviewer who samples \(m\) tasks finds at least one defect with probability \(1-(1-q)^m\); detecting \(q=5\%\) with 90% probability needs \(m=45\).
Graders. Let a grader accept a wrong solution with probability \(\alpha\) and reject a correct one with probability \(\beta\). For true success rate \(p\) the expected reward is
\[ \mathbb{E}[R]=(1-\beta)\,p+\alpha\,(1-p),\qquad \frac{\partial\,\mathbb{E}[R]}{\partial p}=1-\alpha-\beta . \]The slope is what the policy learns from, and \(\alpha\) is not a constant: it depends on the strategy. A strategy that never succeeds but is accepted with probability \(\alpha_{\text{hack}}\) is preferred whenever \(\alpha_{\text{hack}}>(1-\beta)p+\alpha(1-p)\). Combining a state check and a rubric as a conjunction gives \(\alpha=\prod_j\alpha_j\) and \(1-\beta=\prod_j(1-\beta_j)\) under independence; real grader errors are correlated, so the product is optimistic.
Calibrated difficulty. The pass rate is estimated from \(n\) rollouts with a Wilson interval, and a task is kept only if the interval lies inside the trainable band, where the probability \(1-p^G-(1-p)^G\) that a group of \(G\) rollouts is informative is high.
The grader arithmetic is easiest to see as a choice the optimizer faces. The script compares an honest strategy on an expense-report task, correct 40% of the time, with a hack that is never correct but edits the report total so that a unit test summing line items passes. It stacks three grader layers (unit tests, a state check on the stored line items, an expert rubric) as a conjunction with assumed per-layer error rates, verifies the closed form by simulation, and computes Wilson intervals for pass-rate estimates.
import math
import numpy as np
rng = np.random.default_rng(0)
def observed(p_true, fpr, fnr):
"""Expected reward from a grader with false-positive rate fpr and false-negative rate fnr."""
return (1 - fnr) * p_true + fpr * (1 - p_true)
# Two strategies on a hand-built expense-report task. Honest: really correct 40% of the time.
# Hack: never correct (e.g. edits the report total so the unit test's sum check passes).
# Each grader layer: (name, fpr on honest failures, fpr on the hack, fnr on correct work).
layers = [("unit tests", 0.10, 0.95, 0.02), ("+ state check", 0.30, 0.10, 0.03),
("+ rubric", 0.30, 0.20, 0.05)]
fp_h = fp_k = 1.0; tp = 1.0
print(f"{'grader':16s} {'R(honest)':>9s} {'R(hack)':>8s} preferred")
for name, a_h, a_k, b in layers:
fp_h *= a_h; fp_k *= a_k; tp *= (1 - b) # AND of independent checks
rh, rk = observed(0.40, fp_h, 1 - tp), observed(0.0, fp_k, 1 - tp)
print(f"{name:16s} {rh:9.3f} {rk:8.3f} {'hack' if rk > rh else 'honest'}")
# Monte Carlo check of the closed form for the final grader
n = 200_000; correct = rng.random(n) < 0.40
accept = np.where(correct, rng.random(n) < tp, rng.random(n) < fp_h)
print("simulated R(honest) =", round(accept.mean(), 3))
def wilson(c, n, z=1.96):
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)
for c, n in [(1, 64), (6, 64), (60, 64), (12, 128)]:
lo, hi = wilson(c, n); print(f"{c:3d}/{n:<3d} successes -> pass-rate 95% CI [{lo:.3f}, {hi:.3f}]")
It prints the expected reward of each strategy under each grader, a Monte Carlo check of the final row, and pass-rate intervals:
grader R(honest) R(hack) preferred
unit tests 0.452 0.950 hack
+ state check 0.398 0.095 honest
+ rubric 0.367 0.019 honest
simulated R(honest) = 0.367
1/64 successes -> pass-rate 95% CI [0.003, 0.083]
6/64 successes -> pass-rate 95% CI [0.044, 0.190]
60/64 successes -> pass-rate 95% CI [0.850, 0.975]
12/128 successes -> pass-rate 95% CI [0.054, 0.157]
Under unit tests alone the hack earns 0.95 against 0.45 for honest work, so a policy trained on that grader learns the hack. The state check reverses the preference; the rubric widens the margin at the price of a few points of false negatives on correct work. The intervals show why difficulty must be measured with enough rollouts: one success in 64 is consistent with any pass rate from 0.3% to 8%, which straddles the 2–3% threshold Epoch's interviewees use.
The quality bar becomes an acceptance pipeline run before an environment produces reward, plus a monitoring loop during training.
- Fidelity harness. Recorded traces from the real product, or a licensed sandbox instance of it, are replayed against the replica with state compared after every call. Coverage is tracked per endpoint and error class, since the happy path is where replicas are already correct.
- Grader red-teaming. Each task keeps a library of adversarial negatives: deleted or skipped tests, hard-coded outputs, direct edits to the checked field, writes to grader paths. All must be rejected. Rubric graders are calibrated against expert labels and their agreement is reported. The concern is not hypothetical: METR (2025) saw OpenAI's o3 overwrite a scorer's timer and monkey-patch an evaluator to always succeed, and reported similar behaviour from other frontier models.
- Contractor quality. Gold tasks, double authorship on a sample and edit-history review catch low-effort or model-written tasks.
- Difficulty gate. Pass rates are measured with the buyer's current policy at delivery and re-measured as training proceeds; tasks outside the band are returned, hardened or retired.
- Training-time alarms. Per-environment reward jumps, falling episode length and unusual tool-call patterns trigger trajectory review. A confirmed replica bug quarantines the environment, bumps its version after the fix, and forces a decision about rollouts already collected on the faulty version.
The operational metrics are the verifier's audited false-positive and false-negative rates, the share of tasks inside the difficulty band, the environment error rate, and the time from a bug report to a fixed version.
Mining Real Software
Real software repositories are the cheapest source of high-fidelity environments because 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: resolving dependencies, building an image in which the tests run, and proving that the task is solvable and that the tests actually detect the fix. The SWE line of work, from SWE-bench in 2023 (see Lineage) to six-figure task collections in 2026, is a story of automating those three steps.
Five projects show the progression from hand-curated to fully automated pipelines.
- Pan et al. (2024) built SWE-Gym, 2,438 real Python task instances, each with 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.
- Jain et al. (2025) built R2E-Gym, more than 8.7K tasks constructed directly from commits rather than issues: tests are generated and issue text is back-translated from the change, removing the dependence on human-written issues and tests.
- Yang et al. (2025) inverted the direction with SWE-smith: instead of harvesting past bugs, install a repository once and inject bugs that break existing tests. This yields about 50K tasks from 128 repositories, an order of magnitude more than prior datasets, and shares one image per repository, so the environments fit in 295 GB where SWE-Gym's 2.4K tasks needed about 6 TB.
- Badertdinov et al. (2025) automated installation with SWE-rebench: an LLM proposes up to three JSON install recipes per task and refines them from error logs, then execution-based validation keeps tasks whose failing tests pass after the reference patch while previously passing tests still pass. Run continuously, it also yields fresh tasks for a contamination-resistant benchmark.
- Prime Intellect (2026) aggregated 23 task sets, about 365K tasks across SWE, terminal and search, behind one task-set API, with about 135K prebuilt images in its own registry and grading material hidden from the agent until scoring. Its validation pass (a no-op check that tests fail without a fix, and a gold-patch check with retries) 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.
| Strategy | How a bug is made | Tasks | Yield | Cost / candidate |
|---|---|---|---|---|
| LM Modify | Model introduces an error into an existing function or class | 17,887 | 56.0% | 0.38¢ |
| Procedural | Random AST transformations (13 kinds), no model | 15,641 | 40.2% | 0¢ |
| Combine Bugs | Merge validated bug patches from the same file or module | 10,092 | 96.9% | 0¢ |
| LM Rewrite | Model re-implements a function from its signature and docstring | 4,173 | 35.0% | 3.93¢ |
| PR Mirror | Model reverts the changes of a real pull request | 2,344 | 33.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, and 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, against 14 for mirrored real pull requests), so collections usually mix them 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.
A mining pipeline is a sequence of filters, and its economics follow from their yields. If stage \(k\) passes a fraction \(y_k\) of its inputs at cost \(c_k\) per input, then from \(N_0\) candidates the pipeline keeps \(N_0\prod_k y_k\) tasks at total cost \(\sum_k c_k N_0\prod_{j The same arithmetic prices synthetic bugs. Cost per validated bug is cost per candidate divided by yield. From SWE-smith's Table 1, LM Modify costs \(0.38/0.560=0.68\)¢, LM Rewrite \(3.93/0.350=11.2\)¢ and PR Mirror \(5.53/0.338=16.4\)¢, while procedural and combined bugs cost no model spend at all. Storage follows the image granularity. With \(R\) repositories of base size \(B\) and \(N\) tasks that each add a small diff \(\delta\), shared images cost \(RB+N\delta\) against \(NB\) for per-task images. SWE-Gym's 2,438 tasks in about 6 TB average 2.5 GB per task; SWE-smith's 50K tasks in 295 GB average 5.9 MB, a factor of about 400. Validation statistics. Suppose a task's fail-to-pass tests fail spuriously with probability \(f\) on each run. It survives \(r\) validation runs with probability \((1-f)^r\). Rejecting a task with flake rate at least \(f\) with probability \(1-\delta\) needs so \(f=0.1\) and \(\delta=0.05\) require 29 runs; three runs let 72.9% of such tasks through. Validation with a few runs therefore removes grossly flaky tasks, and the rest must be caught during training. A surviving flake still distorts the reward: a correct rollout is scored 0 with probability \(f\), so the observed success rate becomes \(p(1-f)\), the task looks harder than it is, and a fraction \(f\) of correct rollouts are scored as failures and receive a failure's advantage under group normalization. Validation cost. Each validation run executes the test suite twice, once before and once after the reference fix. With early exit on the first failure, a candidate that fails on its first run costs at most two executions, and a candidate that survives all \(r\) runs costs \(2r\). For \(N\) candidates of which a fraction \(v\) are eventually kept, expected executions are approximately \(2N\,[(1-v)+vr]\), so the repeat count is paid almost entirely on the tasks that are kept, and raising \(r\) from 3 to 10 roughly triples validation compute only for the surviving fraction. Mixing harvested and synthetic tasks. Synthetic bugs are drawn from a different distribution: SWE-smith's median edit is 3 lines for LM Modify and 5 for procedural bugs, against 14 for mirrored real pull requests. If tasks are bucketed by a feature \(x\) such as edit size, sampling synthetic tasks with weight \(w(x)=p_{\text{real}}(x)/p_{\text{syn}}(x)\) makes the training pool match the size distribution of real fixes while keeping the volume of the synthetic source. The weights are capped in practice, since buckets that synthesis rarely fills would otherwise dominate. Contamination. With creation time \(t_i\) recorded for each task and training cutoff \(t_c\) for a model, the clean evaluation set is \(\{i: t_i>t_c\}\). Continuous mining keeps that set non-empty, which is how SWE-rebench turns the pipeline into a contamination-resistant benchmark.
The validator can be exercised end to end with a simulated sandbox. The script below keeps the validation function unchanged and adds a fake sandbox that produces test outcomes by task kind: good tasks, tasks whose tests already pass, broken reference fixes, fixes that break existing tests, and flaky tasks whose fail-to-pass tests fail at random 10% of the time. It runs a pool of 1,000 such tasks through validation with 1, 3 and 10 repeats, checks the flake survival formula, and recomputes funnel yields, cost per valid bug and storage per task from the SWE-rebench, SWE-smith and SWE-Gym figures.
import math, random
from collections import Counter
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)
before = sandbox.run_tests(task.tests) # 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) # 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")
@dataclass
class Task:
kind: str; image: str = "repo@sha256:..."; tests: tuple = ()
fail_to_pass: str = "F2P"; pass_to_pass: str = "P2P"; gold_patch: str = "gold"
class Results:
def __init__(self, ok): self.ok = ok
def passed(self, group): return self.ok[group]
class FakeSandbox:
"""Simulates test outcomes by task kind; a flaky test fails at random with prob FLAKE."""
FLAKE = 0.10
def __init__(self, rng): self.rng = rng
def reset(self, image): self.patched = False
def apply(self, patch): self.patched = True
def run_tests(self, tests):
k, fix = self.task.kind, self.patched
f2p = {"good": fix, "trivial": True, "broken_gold": False, "breaks_p2p": fix,
"flaky": fix and self.rng.random() > self.FLAKE}[k]
return Results({"F2P": f2p, "P2P": k != "breaks_p2p"})
rng = random.Random(0)
mix = ["good"] * 600 + ["trivial"] * 120 + ["broken_gold"] * 80 + ["breaks_p2p"] * 50 + ["flaky"] * 150
for runs in (1, 3, 10):
sb, kept, why = FakeSandbox(rng), Counter(), Counter()
for kind in mix:
sb.task = Task(kind); v = validate_task(sb, sb.task, runs)
(kept if v.ok else why)[kind if v.ok else v.reason] += 1
print(f"runs={runs:<2d} kept={dict(kept)} rejected={dict(why)}")
print("flaky survival 0.9^r:", {r: round(0.9 ** r, 3) for r in (1, 3, 10, 29)},
" runs for 95% rejection at f=0.1:", math.ceil(math.log(0.05) / math.log(0.9)))
# Funnel and cost per valid task from published SWE-rebench / SWE-smith numbers
print(f"SWE-rebench yield: post-filter {153_400/450_000:.3f}, final/post-filter {21_336/153_400:.3f},"
f" overall {21_336/450_000:.4f}")
for name, cents, y in [("LM Modify", 0.38, .560), ("Procedural", 0, .402), ("LM Rewrite", 3.93, .350),
("PR Mirror", 5.53, .338)]:
print(f"{name:11s} cost per valid bug = {cents / y:5.2f} cents")
print(f"image storage per task: SWE-Gym {6e12/2438/1e9:.2f} GB, SWE-smith {295e9/50_000/1e6:.1f} MB")
It prints the kept and rejected counts by reason for each number of runs, the flake survival probabilities, and the published-number arithmetic:
runs=1 kept={'good': 600, 'flaky': 133} rejected={'tests pass without a fix': 120, 'reference fix fails': 97, 'reference fix breaks existing tests': 50}
runs=3 kept={'good': 600, 'flaky': 109} rejected={'tests pass without a fix': 120, 'reference fix fails': 121, 'reference fix breaks existing tests': 50}
runs=10 kept={'good': 600, 'flaky': 43} rejected={'tests pass without a fix': 120, 'reference fix fails': 187, 'reference fix breaks existing tests': 50}
flaky survival 0.9^r: {1: 0.9, 3: 0.729, 10: 0.349, 29: 0.047} runs for 95% rejection at f=0.1: 29
SWE-rebench yield: post-filter 0.341, final/post-filter 0.139, overall 0.0474
LM Modify cost per valid bug = 0.68 cents
Procedural cost per valid bug = 0.00 cents
LM Rewrite cost per valid bug = 11.23 cents
PR Mirror cost per valid bug = 16.36 cents
image storage per task: SWE-Gym 2.46 GB, SWE-smith 5.9 MB
Deterministic defects are caught on the first run whatever the repeat count, so repeats exist only for flakiness. With one run, 133 of 150 flaky tasks are kept; three runs still keep 109, and ten keep 43, in line with the expected 135, 109 and 52 given sampling noise. Twenty-nine runs would be needed to reject 95% of them, which is why flake detection continues during training, where every rollout of a task is another sample of its tests. The last lines reproduce the funnel and cost figures: an overall SWE-rebench yield of 4.7%, synthetic bugs from a fraction of a cent to 16 cents each, and a 400-fold storage difference between per-task and per-repository images.
In production, mining is a continuously running service rather than a one-off dataset build, because the same pipeline that produced the training pool keeps producing fresh tasks for contamination-resistant evaluation. Its components map onto the stages in the figure: harvesters that track repository activity, cheap metadata filters, an installation agent with a bounded repair budget (SWE-rebench allows up to three recipes refined from error logs), a build farm that pushes images to a registry by digest, validation workers, and an annotation step. The output is consumed through a task-set API that hides grading material until scoring, as Prime Intellect's aggregation of about 365K tasks behind one interface does (Prime Intellect 2026).
- Image granularity is the main cost decision. One image per repository version with per-task diffs applied at reset keeps the registry small and the node cache warm; per-task images are simpler but multiply storage and pull time. Image placement, lazy loading and warm pools are covered in Sandboxes.
- The image, not the recipe, is the artifact of record. Pinned dependencies get yanked and mirrors change, so a recipe that built last month may not build today. Tasks reference immutable digests, and recipes are rebuilt periodically only to detect rot.
- Re-validate on every change. A new base image, sandbox runtime, validator version or test runner can change verdicts. Published task sets should be re-validated before use: Prime Intellect's pass reduced one upstream SWE set from 32,079 to 6,275 usable tasks.
- Treat build and test execution as untrusted code. Install scripts and test suites from arbitrary repositories run with network egress limited to package mirrors, no credentials in the build environment, and resource limits; license filtering happens before any code is executed.
- Monitor yields per stage. A falling installation success rate or a rising flake rate usually signals an upstream change (a package index, a language toolchain) rather than a change in repositories, and is caught on a stage-yield dashboard long before it shows up as fewer tasks.
- Plan build and validation capacity. Builds and test runs are the expensive stages, so their worker pools are sized from the candidate arrival rate, the stage yields and the measured build and test durations, with installation jobs given hard time limits so a few pathological repositories cannot stall the farm.
- Decontaminate at ingestion. Every task records its repository, commit and creation date; tasks from repositories or time windows that overlap an evaluation suite in use are excluded or routed to the evaluation side, and near-duplicates are removed by patch and issue text.
- Keep flake detection running in training. Tasks whose outcomes disagree across identical rollouts, or that produce infrastructure errors, are quarantined; infrastructure failures are labelled, never scored as reward 0.
Human review remains the scarce input. SWE-smith reports 3–20 minutes of review per installed repository alongside about $0.72 of agent cost, so pipelines spend people on repositories and recipes, which are shared by many tasks, and leave per-task decisions to execution-based checks.
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 that are generated, executed and checked separately: a state backend (usually a database), a tool layer (typed functions exposed through MCP or an API) and 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 and rewards come from inspecting the database.
Five systems illustrate the design space.
- DeepSeek-AI (2025) built the general-agent portion of DeepSeek-V3.2's RL data this way. An agent in a sandbox generates or retrieves data for a task category and stores it in a database, writes task-specific tools as functions, then 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. Keeping only instances with non-zero pass@100 left 1,827 environments and 4,417 tasks. RL on these synthetic tasks alone improved Tau2Bench, MCP-Mark and MCP-Universe over the SFT checkpoint, while RL restricted to code and search did not.
- Wang et al. (2026) made Agent World Model (AWM) a fully synthetic, open pipeline: 1,000 scenarios expanded from 100 seed domains, 10 tasks each, a SQLite schema generated from the tasks and filled so that every task is executable, and a Python MCP interface averaging 35 tools per environment. Verification code diffs the database before and after a rollout, and an LLM judge combines those signals with the trajectory into completed, partially completed, agent error or environment error.
- Tu et al. (2026) built ScaleEnv from scratch with explicit checks on the environment itself: procedural tests for tool reliability, and tool-dependency-graph expansion plus executable action verification to show each task is complete and solvable. Training transferred to unseen τ²-Bench and VitaBench.
- Cai et al. (2025) proposed AutoForge, a unified pipeline for simulated environments with hard but easily verified tasks, plus an RL method that estimates advantages per environment and damps the noise introduced by unstable simulated users.
- Xu et al. (2026) went the other way on scale with EnvFactory: 85 verified, stateful environments across 7 domains built from authentic resources, from which 2,575 multi-turn trajectories with implicit user intent were synthesized. The authors report gains on BFCLv3, MCP-Atlas and conversational benchmarks with roughly a fifth as many environments as comparable work, suggesting that quality and realism can partly substitute for count.
| System | State backend | Tool layer | Success criteria | Scale reported |
|---|---|---|---|---|
| DeepSeek-V3.2 general agent | Sandbox database of gathered data | Generated Python functions | Generated verifier function; pass@100 > 0 filter | 1,827 environments, 4,417 tasks |
| Agent World Model | SQLite, ~18.5 tables per environment | MCP, ~35 tools per environment | DB diff + LLM judge; partial credit | 1,000 environments, 10,000 tasks |
| ScaleEnv | Synthesized from scratch | Procedurally tested tools | Dependency-graph and execution checks | Scaled by number of domains |
| AutoForge | Simulated environments | Synthesized tools | Easily verified tasks; simulated users | Not stated in abstract |
| EnvFactory | Built from authentic resources | Explored and verified tools | Calibrated multi-turn trajectories | 85 environments, 7 domains |
Table. Environment-synthesis pipelines by component, as reported in each paper.
A synthesized environment can be written as a tuple \(\mathcal{E} = (\mathcal{S}, s_0, \mathcal{F}, \mathcal{T})\). The state space \(\mathcal{S}\) is the set of database instances that satisfy a generated schema, \(s_0\) is the seeded snapshot every episode starts from, and \(\mathcal{F}\) is a set of tools, each a deterministic program \(f : \mathcal{S} \times \mathcal{X}_f \to \mathcal{S} \times \mathcal{O}\) that takes the state and typed arguments and returns a new state and an observation. A task is a triple \(\tau = (x, \sigma, V)\): an instruction \(x\), a reference solution \(\sigma\) that is a program composed only of calls to \(\mathcal{F}\), and a verifier \(V : \mathcal{S} \to \{0, 1\}\) (or \([0, 1]\) when partial credit is allowed). An episode applies the agent's tool calls in sequence, \((s_{t+1}, o_t) = f_{a_t}(s_t, \text{args}_t)\), and the reward is \(r = V(s_H)\), read from the final state.
Validation predicates. The checks in the generate-validate-repair loop are predicates on this tuple: non-triviality \(V(s_0) = 0\); solvability \(V(\sigma(s_0)) = 1\), with \(\sigma\) restricted to \(\mathcal{F}\) so the task is solvable through the agent's own interface; and tool self-tests. They are necessary, not sufficient: a verifier can accept \(\sigma(s_0)\) and still accept many end states that do not satisfy \(x\).
The pass@k filter. Let \(p_\tau\) be the current policy's success probability on \(\tau\). From \(n\) rollouts with \(c\) successes the unbiased pass@k estimator is \(1 - \binom{n-c}{k} / \binom{n}{k}\) (Chen et al. 2021). Keeping tasks with non-zero pass@100 from 100 rollouts keeps a task with probability \(1 - (1 - p_\tau)^{100}\): 0.39 at \(p_\tau = 0.005\), 0.63 at 0.01 and 0.95 at 0.03. The filter therefore removes broken or hopeless tasks while keeping tasks down to roughly a 1% success rate.
The upper bound. A group-relative estimator with \(G\) rollouts per task produces a non-zero advantage only when outcomes are mixed, which happens with probability \(P_{\text{inf}}(p) = 1 - p^G - (1-p)^G\). For \(G = 8\) this is 0.99 at \(p = 0.5\) and 0.34 at \(p = 0.05\) or \(0.95\); at \(p \in \{0, 1\}\) it is zero and the rollouts are wasted. This is the formal reason to discard solved tasks and to raise difficulty once a task passes.
Verifier error. If a generated verifier has false-positive rate \(\alpha\) and false-negative rate \(\beta\), the observed reward has expectation \(\mathbb{E}[\hat r \mid \tau] = \alpha + (1 - \alpha - \beta)\, p_\tau\). When \(\alpha\) and \(\beta\) do not depend on the policy, the gradient is scaled by \(1 - \alpha - \beta\) but keeps its direction. The harmful case is a false positive reachable by a specific strategy: then \(\alpha\) depends on \(\pi\), and optimization moves probability toward that strategy. Testing the verifier against the initial state and against near-miss states targets exactly this case.
Yield. If a generation attempt passes validation with probability \(v\) and a validated task survives the pass-rate band with probability \(k\), the expected generation cost per kept task is \(c_{\text{gen}} / (v k)\), and the filtering cost is \(n\) policy rollouts per candidate. With \(n = 100\), filtering rather than generation usually dominates the budget.
The three components fit in a few dozen lines when the state backend is SQLite: a schema and seed rows that are reloaded for every episode, tools that are plain functions over the connection, and a task made of an instruction, a reference solution that only calls tools, and a verifier that reads the end state. The script then runs the two validation checks and estimates the pass rate of a stand-in policy to apply the keep rule \(0 < c < n\).
import sqlite3, random
SCHEMA = """CREATE TABLE orders(id INTEGER PRIMARY KEY, customer TEXT, status TEXT, total REAL);
CREATE TABLE refunds(order_id INTEGER, amount REAL);"""
SEED = [(1, "ana", "delivered", 40.0), (2, "ben", "shipped", 25.0), (3, "ana", "delivered", 15.0)]
def reset(): # state backend: fresh snapshot per episode
db = sqlite3.connect(":memory:"); db.executescript(SCHEMA)
db.executemany("INSERT INTO orders VALUES (?,?,?,?)", SEED); return db
TOOLS = { # tool layer: typed functions over the state
"list_orders": lambda db, customer: db.execute(
"SELECT id, status, total FROM orders WHERE customer=?", (customer,)).fetchall(),
"refund": lambda db, order_id: (db.execute(
"INSERT INTO refunds SELECT id, total FROM orders WHERE id=? AND status='delivered'", (order_id,)),
db.execute("UPDATE orders SET status='refunded' WHERE id=? AND status='delivered'", (order_id,)), "ok")[-1],
}
def call(db, name, **kw): return TOOLS[name](db, **kw)
# task: instruction, reference solution (tools only), verifier over the end state
INSTRUCTION = "Refund every delivered order of customer ana."
def solution(db):
for oid, status, _ in call(db, "list_orders", customer="ana"):
if status == "delivered": call(db, "refund", order_id=oid)
def verifier(db):
left = db.execute("SELECT COUNT(*) FROM orders WHERE customer='ana' AND status='delivered'").fetchone()[0]
paid = db.execute("SELECT COALESCE(SUM(amount),0) FROM refunds").fetchone()[0]
return int(left == 0 and paid == 55.0)
# validation: rejects the initial state, accepts the reference solution
db = reset(); print("verifier(initial) =", verifier(db))
db = reset(); solution(db); print("verifier(solution) =", verifier(db))
def random_policy(db, rng, steps=3): # stand-in for policy rollouts
for _ in range(steps):
call(db, "refund", order_id=rng.choice([1, 2, 3]))
rng = random.Random(0); n = 100
c = sum(verifier((lambda d: (random_policy(d, rng), d)[1])(reset())) for _ in range(n))
print(f"pass rate {c}/{n}; keep task: {0 < c < n}")
$ python3 synth_env.py
verifier(initial) = 0
verifier(solution) = 1
pass rate 51/100; keep task: True
The script prints the verifier on the initial and solved states (0 and 1, so the task is non-trivial and solvable through its tools) and the stand-in policy's pass rate, which falls inside the keep band. In a real pipeline the generator writes the schema, tools, solution and verifier, the stand-in policy is the model being trained with 100 or more rollouts, and a failed check sends the offending component back to the generator for repair. Two details carry over directly: the state is rebuilt from the same snapshot for every episode, and the refund tool enforces its own precondition (status='delivered'), so a policy that calls it on the wrong order changes nothing rather than corrupting the state.
In production each synthesized environment is treated as a build artifact: schema, seed data, tool code, tasks and verifiers are packaged together with the generator model and prompt that produced them, content-hashed and versioned, so that a training run can name exactly which environments it saw and a broken one can be withdrawn. Tool code typically runs as an MCP server per environment; tool exceptions and timeouts are returned to the agent as observations rather than crashing the episode.
Reset and determinism. Thousands of episodes run in parallel, so reset must be cheap: an in-memory or copied SQLite file per episode, or a template database or transaction rollback for Postgres-backed environments. Clocks are frozen, ID generators seeded and query results ordered, because a verifier that compares states is only reliable when the same actions always produce the same state.
Validation as gates. The checks run cheapest first: the schema compiles and tools type-check; tools pass self-tests; the reference solution succeeds through tools only; the verifier rejects the initial state and mutated near-miss states; finally, policy rollouts place the task inside the pass-rate band. The band is re-evaluated as the policy improves, because tasks saturate. DeepSeek-V3.2's loop raises difficulty after a pass, and AWM's judge separates environment error from agent error; tracking the environment-error rate per environment and quarantining outliers keeps broken tools from teaching the policy that failure is normal.
| Failure mode | Symptom | Check |
|---|---|---|
| Lax verifier | Reward rises while held-out benchmarks stay flat | Mutation tests; audit a sample of rewarded trajectories |
| Answer leakage | Solved in one or two calls; tool descriptions or seed data name the answer | Minimum-call statistics; search descriptions for task strings |
| Schema fitted to tasks | Each task maps to a single tool call | Distribution of reference-solution length |
| Near-duplicate environments | Nominal count far above effective diversity | Cluster schemas and tool sets; count clusters |
| Benchmark overlap | Generated domains resemble airline or retail evaluation suites | Embedding similarity of scenarios to benchmark tasks |
| Non-determinism | Same actions, different verdicts | Replay the reference solution several times |
Table. Common failure modes of synthesized environments and the checks that catch them.
Monitoring and cost. Useful dashboards show the pass-rate histogram per environment family, the environment-error rate, the distribution of tool calls (a tool never called or one tool dominating both signal a design problem) and training reward against held-out benchmarks. On cost, generation is a few LLM calls and sandbox minutes per environment, while a pass@100 filter costs 100 policy rollouts per candidate task; budgets are therefore set by filtering and training rollouts, not by synthesis. EnvFactory's result with 85 environments is a reminder that spending on fidelity per environment can buy as much as spending on count.
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. AWM trained a 4B agent on 10, 100 and 526 environments: 10 environments degraded performance on every benchmark, which the authors attribute to overfitting, while 100 gave large gains and 526 improved further (Wang et al. 2026). Szot et al. (2026) fit scaling laws across 849 models trained on 458,752 synthetic tasks in total and found that, as the data budget grows, adding tool and database diversity beats adding tasks, and that more complex data yields larger gains. ScaleEnv reports a similar effect of domain count. None of these studies extends beyond a few thousand environments, so the shape of the curve at frontier scale is an extrapolation.
A simple hierarchical model explains why environment count should matter more than tasks per environment. Let the training signal from task \(j\) of environment \(e\) be \(y_{ej} = \mu + b_e + w_{ej}\), where \(b_e \sim (0, \sigma_b^2)\) is what is specific to the environment (its schema, tools and conventions) and \(w_{ej} \sim (0, \sigma_w^2)\) is task-level variation. The target is \(\mu\), the behaviour that transfers to an unseen environment. Pooling \(E\) environments with \(n\) tasks each gives an estimate with variance
\[ \operatorname{Var}(\hat\mu) = \frac{\sigma_b^2}{E} + \frac{\sigma_w^2}{E n}. \]Under a fixed task budget \(B = E n\) this becomes \(\sigma_b^2 / E + \sigma_w^2 / B\). The second term is set by the budget; only the first depends on how the budget is split, and it falls only with \(E\). At fixed budget, more environments always reduce error on held-out environments, while more tasks per environment cannot reduce the environment-specific term at all. With very small \(E\) the model can also fit the \(b_e\) themselves, which is a formal reading of AWM's observation that 10 environments degraded performance.
Fitting curves. Empirical curves are often summarized by a saturating power law \(S(E) = S_\infty - A E^{-\gamma}\), fitted by regressing \(\log(S_\infty - S)\) on \(\log E\). Extrapolation is fragile: an error \(\delta\gamma\) in the exponent multiplies the predicted remaining gap by \((E_{\text{target}}/E_{\text{max}})^{\delta\gamma}\). Extrapolating from 500 to 50,000 environments with \(\delta\gamma = 0.1\) changes the predicted gap by a factor of \(100^{0.1} \approx 1.58\), and \(S_\infty\) itself is rarely identified from a few points. This is why curves that stop at a few thousand environments say little about frontier scale.
The hierarchical model can be checked by simulation. Each environment draws an offset, each task adds noise, and the "learned" quantity is the pooled mean over a fixed budget of 1,000 tasks split across \(E\) environments. The script measures squared error against the population mean, which is what matters for an unseen environment, and compares it with the closed form \(\sigma_b^2/E + \sigma_w^2/B\).
import numpy as np
rng = np.random.default_rng(0)
sb, sw, B, trials = 1.0, 1.0, 1000, 4000 # between-env sd, within-env sd, task budget
def heldout_error(E): # E environments x B/E tasks each
n = B // E
mu_env = rng.normal(0, sb, (trials, E)) # each environment's true offset
tasks = mu_env[..., None] + rng.normal(0, sw, (trials, E, n))
est = tasks.mean(axis=(1, 2)) # what training "learns": the pooled mean
return np.mean(est ** 2) # squared error vs the population mean (0)
Es = [10, 20, 50, 100, 250, 500]
err = [heldout_error(E) for E in Es]
for E, e in zip(Es, err):
print(f"E={E:4d} tasks/env={B//E:4d} MSE={e:.4f} theory={sb**2/E + sw**2/B:.4f}")
slope, icpt = np.polyfit(np.log(Es[:4]), np.log(np.array(err[:4]) - sw**2 / B), 1)
print(f"fitted exponent on E (excess error) = {slope:.2f}")
$ python3 env_scaling.py
E= 10 tasks/env= 100 MSE=0.0999 theory=0.1010
E= 20 tasks/env= 50 MSE=0.0527 theory=0.0510
E= 50 tasks/env= 20 MSE=0.0208 theory=0.0210
E= 100 tasks/env= 10 MSE=0.0109 theory=0.0110
E= 250 tasks/env= 4 MSE=0.0051 theory=0.0050
E= 500 tasks/env= 2 MSE=0.0031 theory=0.0030
fitted exponent on E (excess error) = -1.01
The script prints the measured and predicted error for each split and an exponent fitted to the excess error. At the same budget, 500 environments with 2 tasks each give about 30 times lower error than 10 environments with 100 tasks each, and the excess error falls as \(E^{-1}\). Real curves have smaller exponents and a ceiling, because environments are not independent draws and the policy is not a mean, but the budget argument holds in the same form.
A useful environment-scaling study holds out environment families rather than tasks, matches token budgets across arms, and runs more than one seed, since differences between runs can rival differences between arms. Madan et al. (NeurIPS 2026) found that the choice of training environment alone shifted held-out pass@1 by up to 11.4 points at matched token budgets, so a comparison that changes both count and composition cannot attribute its gain to count.
Nominal count overstates diversity. Synthesis pipelines expand seed domains, and many generated environments share schemas, tool names and task templates; clustering environments by schema and tool-set embeddings and reporting the number of clusters gives an effective count that is more comparable across papers. Diversity of tools and databases, the axis Szot et al. found most valuable, can be tracked directly as the number of distinct tool signatures and table structures in the training mix.
In practice the budget is allocated by family: a minimum number of environments per family to avoid the small-set overfitting seen at 10 environments, a few tasks per environment, and new families added before new tasks. Curves are re-measured whenever the generator changes, because a new generator shifts both quality and diversity at once.
LLM-Simulated Environments and Users
The cheapest environment is one with no implementation at all: a language model plays the environment, reading the action and writing the next observation, and sometimes 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)\), where \(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 or 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, because 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, executed by a tool simulator that maintains state and injects 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. Li et al. (2025) showed with Simia that a reasoning model can produce environment feedback for both SFT data and RL, with fine-tuned open models surpassing GPT-4o on τ²-Bench. Chen et al. (2025) built DreamGym, a reasoning-based experience model grounded by a replay buffer seeded with real data and paired with curriculum task generation; it matched GRPO and PPO in costly environments using only synthetic interactions, and policies pretrained in it needed far fewer real interactions afterwards.
- Simulated users. Yao et al. (2024) made an LLM user part of τ-bench, with success judged by comparing the final database state to an annotated goal. Qian et al. (2025) turned simulated users into training environments with UserRL and found that a stronger user simulator such as GPT-4o made training more effective, while 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, and found that every model tested was near-perfect when the state did not change but 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 length matters: if each simulated step is consistent with probability \(q\) and errors are independent, 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 and a 100-step episode about 37% of the time. Real errors are correlated, but the direction holds: long episodes amplify simulator error.
| Use of simulation | Usually acceptable when | Main risk | Mitigation |
|---|---|---|---|
| SFT trajectory generation | Trajectories are filtered by a judge and the target skill is tool-calling form, not exact state | Plausible but impossible tool outputs in training data | Rubric filtering; mix with real-sandbox data |
| RL warm start | Followed by RL in real or code-backed environments | Policy exploits simulator quirks | Short simulated phase; ground with real replay data |
| Simulated users | Reward is computed from environment state, not from the user's words | Over-cooperative or leaky users inflate success | Strong simulator; persona constraints; audit transcripts |
| Full RL environment | Episodes are short and state changes are few | State drift; reward on states that cannot exist | Prefer a database-backed backend; check consistency |
| Coding, terminal, anything executable | Rarely; execution is cheap and exact | Rewarding code that would not run | Use 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 (user behaviour, rare external APIs, the long tail of tool responses) and execute what is cheap and exact (code, databases, file systems). The AWM authors make the same argument for code-driven, database-backed state over LLM-generated state, and DreamGym's best results come from using simulation as a warm start rather than a replacement.
Let \(P(s' \mid s, a)\) be the real transition function and \(\hat P_\phi(s' \mid s, a)\) the simulator, with \(s\) the environment state, \(a\) the agent's action and \(\phi\) the simulator's parameters. Under a policy \(\pi\), define the per-step simulator error as the expected total-variation distance on the states the policy visits, \(\varepsilon_t = \mathbb{E}_{(s,a) \sim d_t^\pi}\big[\operatorname{TV}(\hat P_\phi(\cdot \mid s,a),\, P(\cdot \mid s,a))\big]\). Replacing one real step at a time with a simulated one and summing the differences gives a bound on the whole trajectory distribution:
\[ \operatorname{TV}\big(p^{\pi}_{P},\, p^{\pi}_{\hat P}\big) \;\le\; \sum_{t=0}^{H-1} \varepsilon_t \;\le\; H \bar\varepsilon . \]For any reward in \([0, 1]\) computed from the trajectory, such as a success indicator, the return in the simulator and in reality therefore differ by at most \(H\bar\varepsilon\): \(|J_P(\pi) - J_{\hat P}(\pi)| \le H \bar\varepsilon\). The bound grows linearly with horizon, which is the formal version of the observation that long episodes amplify simulator error.
Consistency of whole episodes. If each step is consistent with probability \(q = 1 - \varepsilon\) and errors are independent, an episode is clean with probability \(q^H \approx e^{-H\varepsilon}\). At \(q = 0.99\) this is 0.904 for \(H = 10\) and 0.366 for \(H = 100\). If a step changes \(m\) state variables and each is updated correctly with probability \(p\), the step is correct with probability \(p^m\), which is consistent with simulators that are near-perfect when nothing changes and much weaker when several variables change at once.
Optimization against the simulator. A policy trained on \(\hat P_\phi\) maximizes \(J_{\hat P}\). Because \(\varepsilon_t\) is measured under the policy's own visitation \(d_t^\pi\), optimization can move the policy toward exactly the states where the simulator errs in its favour, so the error at the end of training can be far larger than the error measured on the initial policy. A worst-case guarantee needs the uniform bound \(\sup_\pi |J_P(\pi) - J_{\hat P}(\pi)|\), which gives \(J_P(\hat\pi) \ge J_P(\pi^*) - 2 \sup_\pi |J_P(\pi) - J_{\hat P}(\pi)|\).
Simulated users add a second learned component, a user policy \(\mu_\psi\). If reward is computed from the final environment state, \(r = V(s_H)\), errors in \(\mu_\psi\) change which states are reached but cannot directly certify success. If reward depends on the user's words, the user model becomes part of the reward function and its errors pass straight into the objective.
Three properties of simulated environments can be shown with a few lines of NumPy: step accuracy falls as more state variables change at once, episode-level consistency decays geometrically with horizon, and a policy trained on simulator reward converges to whatever the simulator mis-scores. The last part uses REINFORCE on a two-action problem in which the simulator accepts an unsupported claim that the task is done.
import numpy as np
rng = np.random.default_rng(0)
def sim_step_ok(m, p_var=0.97): # simulator updates each of m changed variables correctly w.p. p_var
return bool((rng.random(m) < p_var).all())
for m in [0, 1, 3]:
print(f"vars changed={m}: step accuracy {np.mean([sim_step_ok(m) for _ in range(20000)]):.3f}")
q = 0.99 # per-step consistency, independent errors
for H in [10, 100]:
clean = np.mean((rng.random((20000, H)) < q).all(axis=1))
print(f"H={H:3d}: clean episodes {clean:.3f} (q^H = {q**H:.3f})")
# a policy trained on simulator reward finds the action the simulator mis-scores
real = {"solve": 0.6, "claim_done": 0.0} # true success probability
sim = {"solve": 0.6, "claim_done": 0.9} # simulator accepts an unsupported "done"
logits = np.zeros(2); acts = list(real)
for _ in range(3000): # REINFORCE with a mean baseline, simulator reward
p = np.exp(logits) / np.exp(logits).sum(); a = rng.choice(2, p=p)
r = float(rng.random() < sim[acts[a]]); b = sum(p[i] * sim[acts[i]] for i in range(2))
logits += 0.1 * (r - b) * (np.eye(2)[a] - p)
p = np.exp(logits) / np.exp(logits).sum()
print("policy:", {a: round(float(x), 3) for a, x in zip(acts, p)},
f"sim return {p @ [sim[a] for a in acts]:.2f}, real return {p @ [real[a] for a in acts]:.2f}")
$ python3 sim_env.py
vars changed=0: step accuracy 1.000
vars changed=1: step accuracy 0.970
vars changed=3: step accuracy 0.914
H= 10: clean episodes 0.903 (q^H = 0.904)
H=100: clean episodes 0.366 (q^H = 0.366)
policy: {'solve': 0.007, 'claim_done': 0.993} sim return 0.90, real return 0.00
The script prints step accuracy for 0, 1 and 3 changed variables, the fraction of clean 10-step and 100-step episodes next to \(q^H\), and the final policy with its simulated and real returns. The trained policy puts almost all probability on the action that the simulator rewards and reality does not: simulated return 0.90, real return 0.00, against 0.60 for the honest action in both. The same pattern appears whenever reward is read from simulator text rather than checked against state.
Production systems rarely use a pure LLM environment for training. The common design is a hybrid: an action router sends code, database and file operations to an executable backend, and sends user turns and rare external APIs to an LLM simulator that reads and writes the same backend state. Reward is computed from that state, not from the simulator's text. τ-bench's comparison of the final database with an annotated goal follows this pattern; Kimi K2's tool simulator, which maintains state and injects controlled failures, moves part of the way toward it.
Failure modes. Simulated users tend to be over-cooperative, volunteer the goal, or end the conversation early; each inflates success. A subtler hazard is injection: the agent's message is the simulator's input, so a policy can learn to write text that makes the simulator report success. Passing the simulator structured actions rather than free text, keeping reward state-based and auditing a sample of transcripts per training step contain both. Each simulated step adds a second model call and its latency to every turn, so simulators are usually served as a separate endpoint with their own capacity plan, and their outputs are logged as part of each trajectory so that any reward can be reproduced.
Fidelity gates. A simulator release is evaluated like any model release: an EnvSimBench-style suite of state-transition cases, scored separately for steps that change zero, one and several variables, plus a canary set of tasks with known outcomes. During training the gap between simulated reward and reward on a small real or code-backed subset is tracked; a widening gap means the policy has found the simulator's errors. UserRL's finding that a stronger user simulator trains better, while a cheaper open model still transfers, frames the usual trade: a strong simulator for the RL phase, a cheaper one for SFT data generation, and a short simulated phase followed by training in executable environments.
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: can it be solved, does the verifier accept exactly the right outcomes, is it at a useful difficulty, is it independent of evaluation suites, and 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, which proves the action space is sufficient (DeepSeek-AI 2025).
Verifier audits. Validation proves the verifier accepts one correct solution; it does not prove it rejects wrong ones or accepts other correct ones. Human audits of public benchmarks show how often this fails. When 93 developers annotated 1,699 SWE-bench samples, 61.1% were flagged for unit tests that could reject valid solutions and 38.3% for underspecified issues, and 68.3% of samples were filtered out in building the 500-task Verified set (OpenAI 2024). Training environments rarely get that scrutiny, so sampled human review and red-teaming verifiers with deliberately wrong solutions belong in the pipeline (see Verifiers and Rewards).
Difficulty calibration. Difficulty is measured as the current policy's pass rate \(p\) over repeated rollouts. With group-relative methods such as GRPO, a group of \(G\) rollouts produces a gradient only if it contains both a success and a failure, which 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 is about 0.73; at \(G = 128\) 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), and 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: keep collecting fresh tasks with the same pipeline and evaluate only on those created after a model's training cutoff, which 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, and any change to one of them creates a new task version rather than silently editing the old one (storage in The Trajectory Data Model).
Each of the five questions has a quantitative form, and each form says how much testing a task needs before its rewards can be trusted.
Solvability and stability. Let the verifier \(V\) return 1 or 0, let \(s_0\) be the task's initial state and \(g\) its reference solution. Acceptance requires \(V(s_0)=0\) and \(V(g)=1\) in each of \(n\) independent resets. If a nondeterministic component makes the gold run fail with probability \(f\) per run, \(n\) runs expose it with probability \(1-(1-f)^n\): for \(f=0.1\), 0.27 at \(n=3\) and 0.65 at \(n=10\). Repeated validation removes grossly flaky tasks but admits mildly flaky ones, whose residual \(f\) becomes reward noise; the flake rate measured during training is the complementary check.
Verifier error rates. Write \(\alpha = \Pr[V=1 \mid \text{wrong}]\) for the false-acceptance rate and \(\beta = \Pr[V=0 \mid \text{correct}]\) for the false-rejection rate. A policy whose true success probability is \(p\) observes the pass rate
\[ \tilde p = \alpha + (1-\alpha-\beta)\,p , \]so the signal about real success is scaled by \(1-\alpha-\beta\) and the remainder rewards whatever the verifier happens to accept. \(\alpha\) is not a constant: optimization searches for accepted wrong solutions, so \(\alpha\) measured on random mistakes understates \(\alpha\) on the policy's own. Audits with deliberately wrong solutions bound it. If \(m\) independent negatives are all rejected, then at confidence \(1-\delta\)
\[ \alpha \le \frac{\ln(1/\delta)}{m}, \]the rule of three (\(\alpha \lesssim 3/m\) at 95%): about 300 rejected negatives are needed to bound \(\alpha\) near 1%. The SWE-bench annotation that flagged 61.1% of samples for tests that could reject valid solutions (OpenAI 2024) is a task-level measurement of how often \(\beta > 0\).
Difficulty. For a group of \(G\) binary rewards, the group-relative advantage \(\hat A_i = (r_i-\bar r)/\sigma_r\) is zero for every member when all \(r_i\) agree, which happens with probability \(p^G+(1-p)^G\). Hence
\[ \Pr[\text{signal}] = 1 - p^{G} - (1-p)^{G} \approx 1 - e^{-Gp} \quad (p \ll 1), \]and a target signal probability \(s\) needs \(G \ge \ln\frac{1}{1-s} \big/ \ln\frac{1}{1-p} \approx \ln\frac{1}{1-s}\big/p\): 114 rollouts at \(p=0.02\) and \(s=0.9\), inside the 64–128 range practitioners report (Denain and Barber 2026). Pass rates are themselves estimates. With \(k\) successes in \(n\) calibration rollouts and a uniform prior the posterior is \(\mathrm{Beta}(k+1,\, n-k+1)\); zero successes in 64 rollouts still leaves a 95% upper bound of 0.045, so a zero-pass filter discards some tasks that are hard but learnable. DeepSeek's non-zero pass@100 filter (DeepSeek-AI 2025) is the same test at \(n=100\).
Contamination. Overlap between a training task and an evaluation item is scored by the Jaccard similarity of their \(k\)-shingle sets, \(J(A,B) = |A\cap B|/|A\cup B|\). Inflation is measured temporally: if a model scores \(\hat a_o\) on \(n_o\) tasks created before its training cutoff and \(\hat a_n\) on \(n_n\) comparable tasks created after, then
\[ \hat\Delta = \hat a_o - \hat a_n, \qquad \mathrm{se}(\hat\Delta) = \sqrt{\tfrac{\hat a_o(1-\hat a_o)}{n_o} + \tfrac{\hat a_n(1-\hat a_n)}{n_n}} \]estimates contamination to the extent that the two sets match in difficulty. SWE-rebench's continuous collection with one pipeline exists to make that match plausible (Badertdinov et al. 2025).
Deduplication. MinHash makes Jaccard checks scale: for a random hash \(h\), \(\Pr[\min h(A) = \min h(B)] = J(A,B)\) (Broder 1997), so the agreement rate over \(n\) hashes estimates \(J\) with standard error \(\sqrt{J(1-J)/n}\). Splitting \(n = br\) values into \(b\) bands of \(r\) makes a pair a candidate with probability \(1-(1-J^r)^b\), a step near \(J^{*} \approx (1/b)^{1/r}\); with \(b=16\) and \(r=8\), pairs at \(J=0.8\) are caught 95% of the time and pairs at \(J=0.5\) 6%. Duplicates matter because sampling weight follows frequency: a template that forms a fraction \(q\) of the pool receives a fraction \(q\) of the updates, however few distinct skills it teaches.
Versioning. The reward is a function \(R_x(\tau; v)\) of the version tuple \(v = (\text{image}, \text{data}, \text{tools}, \text{verifier})\). Rewards, pass rates and calibration results are comparable only at fixed \(v\), so a task's identity is a content hash \(H(x, v)\) and every statistic above is keyed by it.
Quality control runs cheap checks before expensive ones. The first sketch applies the acceptance checks to a small task (deduplicate a list, keeping first occurrences) under two verifiers: a weak one that compares against the single example in the prompt, and a strong one with four tests. The gate rejects a verifier that accepts a trivial action, a reference solution that fails in any of several runs, any accepted wrong solution, and a rejected independent correct solution. A final loop adds a 10% per-run gold failure to measure how often repeats expose flakiness.
import random
# Task: dedupe(xs) returns xs without repeats, keeping first-occurrence order.
TESTS = [([3, 1, 3, 2, 1], [3, 1, 2]), ([], []), (["a", "a"], ["a"]), ([2, 2, 1], [2, 1])]
weak = lambda f: f([3, 1, 3, 2, 1]) == [3, 1, 2] # one visible example
strong = lambda f: all(f(list(x)) == y for x, y in TESTS)
gold = lambda xs: list(dict.fromkeys(xs))
alt = lambda xs: [x for i, x in enumerate(xs) if x not in xs[:i]] # independently written
negatives = {"empty": lambda xs: [], "no-op": lambda xs: xs,
"hard-coded": lambda xs: [3, 1, 2], "sorted-set": lambda xs: sorted(set(xs))}
def accept(verify, runs=3):
"""Run the cheap acceptance checks in order; return the first failure."""
if verify(negatives["no-op"]) or verify(negatives["empty"]):
return "reject: trivial action passes"
if not all(verify(gold) for _ in range(runs)):
return "reject: gold fails or is flaky"
bad = [n for n, f in negatives.items() if verify(f)]
if bad:
return f"reject: accepts negatives {bad}"
if not verify(alt):
return "reject: alternative correct solution fails"
return "accept"
print("weak: ", accept(weak))
print("strong:", accept(strong))
# A verifier whose gold run fails 10% of the time (e.g. a timing-dependent test).
random.seed(0)
flaky = lambda f: strong(f) and (f is not gold or random.random() > 0.1)
for runs in (3, 10):
caught = sum(accept(flaky, runs) != "accept" for _ in range(10_000)) / 10_000
print(f"flaky verifier caught with {runs} gold runs: {caught:.2f}")
Prints weak: reject: accepts negatives ['hard-coded'], strong: accept, then a catch rate of 0.27 with 3 gold runs and 0.65 with 10. The hard-coded answer is the false positive an optimizing policy finds; three repeats catch only large instabilities.
Difficulty calibration estimates each task's pass rate from probe rollouts and keeps tasks with at least one success and a rate below a ceiling. The sketch draws a pool whose true pass rates cluster near 0 and 1, as mined and synthesized pools tend to, and measures the fraction of size-16 groups that carry a gradient before and after filtering.
import numpy as np
def p_signal(p, G):
"""Probability a group of G binary rollouts has both a success and a failure."""
return 1 - p**G - (1 - p)**G
def min_group(p, target=0.9):
return int(np.ceil(np.log(1 - target) / np.log(1 - p))) # small-p bound, ignores p**G
print("p=0.02:", {G: round(p_signal(0.02, G), 2) for G in (8, 16, 64, 128)})
print("G for 90% signal:", {p: min_group(p) for p in (0.01, 0.02, 0.05)})
# Pool of tasks with true pass rates skewed toward easy/impossible, policy group size 16.
rng = np.random.default_rng(0)
p_true = rng.beta(0.3, 0.3, size=20_000)
G, n_probe, lo, hi = 16, 64, 0.02, 0.90
k = rng.binomial(n_probe, p_true) # calibration rollouts per task
keep = (k >= 1) & (k / n_probe <= hi) # at least one success, below the ceiling
print(f"kept {keep.mean():.1%} of tasks")
print(f"signal per group: all {p_signal(p_true, G).mean():.2f}, kept {p_signal(p_true[keep], G).mean():.2f}")
print(f"kept tasks truly outside [{lo}, {hi}]: {((p_true[keep] < lo) | (p_true[keep] > hi)).mean():.1%}")
Prints signal probabilities 0.15, 0.28, 0.73, 0.92 at \(p=0.02\) for \(G\) = 8, 16, 64, 128; 90%-signal group sizes 230, 114, 45; then 57.0% of tasks kept, signal per group rising from 0.57 to 0.84, and 8.5% of kept tasks truly outside the band because 64 probes estimate \(p\) imprecisely.
Near-duplicate detection and versioning complete the gate. MinHash over word 3-shingles estimates Jaccard similarity without comparing sets pairwise, and a content-addressed id changes whenever any versioned component changes.
import hashlib, json, re
import numpy as np
def shingles(text, k=3):
w = re.findall(r"\w+", text.lower())
return {" ".join(w[i:i + k]) for i in range(len(w) - k + 1)}
def minhash(s, n=128, seed=0):
rng = np.random.default_rng(seed)
a, b = rng.integers(1, 2**31 - 1, (2, n))
h = np.array([int(hashlib.md5(x.encode()).hexdigest()[:8], 16) for x in s])
return ((a[:, None] * h[None, :] + b[:, None]) % (2**31 - 1)).min(axis=1)
tasks = ["Write a function that removes duplicate items from a list while keeping the original order of first occurrence.",
"Write a function that removes duplicate entries from a list while keeping the original order of first occurrence.",
"Write a function that merges two sorted lists into one sorted list without using the built-in sort."]
S = [shingles(t) for t in tasks]; sig = [minhash(s) for s in S]
for i, j in [(0, 1), (0, 2)]:
jac = len(S[i] & S[j]) / len(S[i] | S[j])
print(f"tasks {i},{j}: Jaccard {jac:.2f}, MinHash estimate {(sig[i] == sig[j]).mean():.2f}")
def task_version(**parts):
"""Content-addressed id: changing any component yields a new task version."""
return hashlib.sha256(json.dumps(parts, sort_keys=True).encode()).hexdigest()[:12]
base = dict(image="sha256:9f1c", data="snap-2026-10-01", tools="1.4.2", verifier="2.0.0")
print(task_version(**base), task_version(**{**base, "verifier": "2.0.1"}))
Prints Jaccard 0.68 (MinHash 0.74) for the two rewordings of one task, 0.07 (MinHash 0.05) for the unrelated task, and two different ids for verifier 2.0.0 and 2.0.1. In a real pipeline the same signatures are computed on environment structure (schema and tool signatures) and on normalized reference solutions, not only on task text.
A full acceptance gate adds the checks a toy task cannot show, in roughly this order: the image builds from a pinned recipe with digest and lockfile recorded; two resets give identical database-dump and file-tree hashes; grading material is absent from the agent-visible filesystem and network access is limited to the task's needs; the gold solution passes through agent-facing tools only; calibration rollouts place the current policy's pass rate inside a band such as \(0.02 < p < 0.9\); no repository, text or solution overlaps an evaluation suite; timeouts and crashes are reported as environment errors rather than reward 0; and the record names a version tuple and an owner. These thresholds are starting points, not published standards.
In production, quality control is a staged ingestion pipeline in front of the task registry, ordered by cost. Static and build checks come first (pinned recipe, recorded digest, lockfile), then sandbox checks that need no model (reset hashes, isolation scan, no-op, gold runs, negatives), and calibration rollouts with the current policy last, because they consume inference capacity. At the scale of Prime Intellect's 2026 aggregation, about 365K tasks behind one API with grading material hidden from the agent until scoring, each stage must be automatic; humans review samples and disputes. For synthesized environments the gold check uses agent-facing tools only, which also catches tool layers that cannot express the solution (DeepSeek-AI 2025).
Verifier audits as regression tests. Each domain keeps a library of negative generators (deleted or edited tests, hard-coded outputs, partial edits, monkey-patched graders) and a sentinel set of known-wrong solutions that runs on every verifier release; any acceptance blocks the release. Audits do not end at ingestion. METR (2025) saw o3 overwrite a scorer's timer and monkey-patch an evaluator, so training dashboards watch for the fingerprints: one task family's reward rising while episodes shorten, or tool calls touching test files. Public benchmarks show the cost of skipping audits: OpenAI (2026) stopped reporting SWE-bench Verified after finding material test or specification problems in 59.4% of 138 audited problems.
Calibration that stays current. Pass rates go stale as the policy improves. Training groups are free calibration samples, so the registry can update each task's pass-rate estimate from every group and retire tasks that cross the ceiling, while periodic probes refresh tasks that have not been sampled recently. DAPO's dynamic sampling handles the remainder online by discarding all-equal groups and resampling (Yu et al. 2025). The design decision is where the filtering cost falls: offline probes spend inference before training, online filtering spends it during training as discarded groups.
Contamination and dedup at ingestion. The registry holds hashed evaluation tasks, repositories and reference solutions, and every candidate is checked against all of them, plus MinHash-LSH on text and hashes of schemas, tool signatures and normalized solutions. Repository-level separation is the strongest cheap defense, as in SWE-Gym's 11 repositories disjoint from SWE-bench (Pan et al. 2024). Dedup also pays off directly: removing near-duplicates from language-model training data let models emit memorized text about ten times less often and reach the same or better accuracy in fewer steps (Lee et al. 2022).
Versions, owners, dashboards. Versions are immutable and content-addressed; a patched verifier creates a new version, old rewards stay attached to the old one, and a task under investigation is quarantined rather than deleted so past runs remain reproducible. Per-version dashboards track pass rate, flake rate, environment-error rate (kept separate from reward 0), sentinel acceptance and time since last calibration, and each alert routes to the named owner. Typical failures are a silently edited verifier that mixes two reward definitions in one run, calibration computed against an old checkpoint, dedup on text only that misses template clones, and synthesized paraphrases of benchmark items that pass repository-level checks.
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 them per optimizer step, each created, reset and destroyed on the critical path of training, so sandboxing stops being a security detail and becomes the throughput limit of the whole run. The operating lesson reported from production stacks in 2026 is that cost and latency are driven less by which isolation technology is chosen than by how images are stored, moved and recycled (Kondragunta 2026).
The requirements follow from the environment definition: reset returns the world to a known state, episodes cannot see each other, and the agent, which is being optimized to find shortcuts, cannot reach the verifier's data or the host.
A sandbox can be written as a triple \((I, \rho, V)\): an image \(I\), a reset map \(\rho\) that produces the initial state \(s_0 = \rho(I)\), and a verifier \(V\) that maps the final state \(s_T\) to a reward. The environment definition imposes three conditions on it.
- Determinism of reset: \(\rho(I)\) is the same state for every lease, so two episodes of one task differ only through the policy and the sampler seed.
- Independence: for episodes \(i \neq j\) in one batch, \(\tau_i\) and \(\tau_j\) are conditionally independent given the policy; no write by one is observable by the other.
- Verifier secrecy: the hidden data \(D_V\) the verifier uses is not a function of anything the agent can observe, so \(P(o_t \mid D_V) = P(o_t)\) for every observation.
The cost side is a critical-path sum. Episode \(i\) holds a sandbox for \(h_i = c_i + e_i + v_i + r_i\) (create or lease, episode, verify, reset). A synchronous step over \(B\) episodes cannot finish before \(\max_i h_i\), while the fleet pays for \(\sum_i h_i\) sandbox-seconds. Only \(e_i\) produces training signal; \(c_i\) and \(r_i\) are overhead that sits on the GPU's clock whenever they are not hidden, which is why provisioning (Kondragunta 2026) rather than isolation strength sets throughput.
The sandbox contract is four calls: lease a fresh copy of a task image, execute agent commands inside it, verify its final state with data the agent never sees, and reset it to the image. The miniature below uses a temporary directory as the writable copy and a read-only template as the image; the hidden expected answer is held by the verifier and never copied into the image. A real system replaces the directory copy with a copy-on-write filesystem and the subprocess with an isolated process, VM or remote API, but the contract is unchanged.
"""A sandbox as lease -> exec -> verify -> reset over a disposable working copy.
The task image is a read-only template; hidden tests live outside the sandbox root."""
import os, shutil, subprocess, tempfile, pathlib
class Sandbox:
def __init__(self, image: pathlib.Path):
self.image = image # read-only template
self.root = pathlib.Path(tempfile.mkdtemp(prefix="sbx-"))
self.reset()
def reset(self): # known state, every episode
shutil.rmtree(self.root); shutil.copytree(self.image, self.root)
def exec(self, cmd: str, timeout=5):
p = subprocess.run(cmd, shell=True, cwd=self.root, capture_output=True, text=True,
timeout=timeout, env={"PATH": "/usr/bin:/bin", "HOME": str(self.root)})
return p.returncode, (p.stdout + p.stderr).strip()
def close(self): shutil.rmtree(self.root, ignore_errors=True)
def verify(sbx, hidden_tests): # runs outside the agent's view
return float((sbx.root / "answer.txt").exists() and
(sbx.root / "answer.txt").read_text().strip() == hidden_tests["expected"])
base = pathlib.Path(tempfile.mkdtemp()); image = base / "image"; image.mkdir()
(image / "task.md").write_text("Write the sum of 17 and 25 to answer.txt\n")
hidden = {"expected": "42"} # never copied into the image
sbx = Sandbox(image)
print(sbx.exec("cat task.md")[1])
print("agent looks for tests:", sbx.exec("ls; grep -r expected . || echo none found")[1].split("\n")[-1])
sbx.exec("echo 42 > answer.txt"); print("episode 1 reward:", verify(sbx, hidden))
sbx.reset(); print("after reset, files:", sorted(os.listdir(sbx.root)), "reward:", verify(sbx, hidden))
sbx.close(); shutil.rmtree(base)
It runs one episode, shows that the agent cannot find the hidden answer, scores the episode, and shows that reset removes the agent's write so the next episode starts clean. Output:
Write the sum of 17 and 25 to answer.txt
agent looks for tests: none found
episode 1 reward: 1.0
after reset, files: ['task.md'] reward: 0.0In production the sandbox is a service with a narrow API: create or lease, exec, read and write files, snapshot, and destroy. Every rollout worker calls it, so its latency and failure rate appear directly in step time and in the reward stream.
Four service-level objectives cover most of what matters: time from lease request to first command (tracked at p50, p99 and maximum, since a synchronous step waits for the maximum); lease success rate; reset correctness, checked by hashing the filesystem after reset against the image; and sandbox-seconds per optimizer step, the number that drives cost.
The characteristic failures are silent. A reset that misses a cache directory leaks state between episodes and correlates rewards. Hidden tests baked into the image turn into a reward hack once the policy learns to read them. An infrastructure error scored as zero reward is indistinguishable from a policy failure. The 2026 operating lessons point to the same remedies: keep environments dependency-light, move heavy tooling such as judges, browsers and databases behind service boundaries, and give every episode a status label that separates infrastructure failure from a scored outcome (Kondragunta 2026).
Isolation Options
Isolation technologies trade the strength of the boundary between agent and host against start-up time, density and compatibility, and in practice the choice is set by how much the agent is allowed to do.
Containers share the kernel, so a kernel exploit escapes them. gVisor serves system calls from an application kernel written in Go, keeping container ergonomics at some system-call overhead. Agache et al. (2020) built Firecracker, the minimal virtual machine monitor behind AWS Lambda; its launch announcement gave start-up under 125 ms and under 5 MiB of memory overhead per microVM (AWS 2018). Kata Containers puts such VMs behind the standard container runtime so Kubernetes schedules them like pods.
| Option | Boundary | Start / reset | Density | Fits | Examples |
|---|---|---|---|---|---|
| Rootless namespaces + overlay | Shared kernel, seccomp, Landlock | Milliseconds | Highest | Trusted clusters, SWE/terminal | NitroBox |
| Containers (runc) | Shared kernel | Sub-second+; image pull dominates | High | Single tenant, inside a VM | Docker; DSec (in VMs) |
| User-space kernel | gVisor application kernel | Sub-second | High | Multi-tenant Kubernetes | GKE Agent Sandbox pools, Modal |
| MicroVM | Hardware virtualization, own guest kernel | ~100–200 ms boot | Medium–high | Untrusted code, root agents | Firecracker, Kata |
| Full VM | Hypervisor | Seconds to minutes | Low | Desktops, GPUs | OSWorld-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 them. DSec runs containers inside VMs as an outer boundary beside Firecracker microVM and full-VM backends, with AppArmor and eBPF network allowlists per sandbox (Huang et al. 2026); Prime Intellect runs every sandbox as a hardware-virtualized microVM with its own guest kernel (Prime Intellect 2026).
Each option can be described by three quantities: per-sandbox memory overhead \(m_o\), a per-system-call cost \(\delta\) added by the boundary, and a probability \(q\) that the boundary fails against an exploit the agent attempts. On a node with memory \(M\) and CPU \(C\), with workload requests \(m_w\) and \(c_w\), density is
\[ n \;=\; \Big\lfloor \min\Big( \frac{M}{m_w + m_o},\; \frac{C}{c_w + c_o} \Big) \Big\rfloor . \]For a microVM, \(m_o\) under 5 MiB (AWS 2018) is small beside a workload that requests gigabytes, so density is set mostly by what the task requests, not by the boundary. Run time is \(t = t_{\text{cpu}} + k\,\delta\) for \(k\) system calls; a user-space kernel such as gVisor raises \(\delta\), which matters for syscall-heavy tasks (builds, package installs, test suites touching many files) and little for compute-bound ones.
Risk scales with volume. Over \(N\) episodes, with probability \(p\) that an episode attempts an escape, the expected number of escapes is \(N p q\). At millions of episodes per day, as DSec reports (Huang et al. 2026), even small \(p q\) is not negligible, and an optimizer rewarded for shortcuts makes \(p\) grow over training. Layering independent boundaries multiplies failure probabilities, \(q = q_1 q_2\), which is the argument for containers inside VMs.
Resource limits are not an isolation boundary, since a process under limits still shares the host kernel and filesystem, but every boundary needs them: an agent that spins the CPU, allocates memory without bound, fills a disk or hangs must be stopped without stalling the step. The snippet runs untrusted Python under POSIX resource limits (CPU seconds, address space, file size, process count) with a cleared environment and a wall-clock timeout, and reports how each misbehaving program ends.
"""Resource limits are not an isolation boundary, but every boundary needs them:
run untrusted commands with CPU, memory, file-size and process caps and a wall-clock timeout."""
import resource, subprocess, sys
def limits(cpu_s=2, mem_mb=256, fsize_mb=8, nproc=64):
def apply():
resource.setrlimit(resource.RLIMIT_CPU, (cpu_s, cpu_s))
resource.setrlimit(resource.RLIMIT_AS, (mem_mb << 20, mem_mb << 20))
resource.setrlimit(resource.RLIMIT_FSIZE, (fsize_mb << 20, fsize_mb << 20))
resource.setrlimit(resource.RLIMIT_NPROC, (nproc, nproc))
return apply
def run(code, wall_s=5):
try:
p = subprocess.run([sys.executable, "-I", "-c", code], preexec_fn=limits(),
capture_output=True, text=True, timeout=wall_s, env={})
last = (p.stderr.strip().splitlines() or [""])[-1][:48]
return f"exit={p.returncode:>4} {last}"
except subprocess.TimeoutExpired:
return "killed by wall-clock timeout"
cases = {
"normal": "print(sum(range(10**6)))",
"cpu spin": "while True: pass",
"memory hog": "x = bytearray(1 << 30)",
"disk fill": "open('/tmp/big.bin','wb').write(b'0' * (64 << 20))",
"sleeper": "import time; time.sleep(60)",
}
for name, code in cases.items(): print(f"{name:<11} {run(code)}")
Each case prints its exit status and last error line: the CPU spinner is killed by the CPU limit, the memory and disk hogs fail inside the process, and the sleeper, which uses no CPU, is caught only by the wall-clock timeout. Output:
normal exit= 0
cpu spin exit= -9
memory hog exit= 1 MemoryError
disk fill exit= 1 OSError: [Errno 27] File too large
sleeper killed by wall-clock timeoutThe choice follows the threat model, set by what the agent may do. Agents that run arbitrary binaries as root, install packages or open sockets need a hardware boundary: Firecracker or Kata Containers, which Kubernetes schedules through a runtime class. Terminal and SWE tasks on a trusted, single-tenant cluster can run in rootless namespaces or containers, provided the nodes are themselves VMs. Desktops and GPU tasks usually need full VMs.
Production fleets layer controls around whichever boundary they pick: seccomp and AppArmor or Landlock profiles, eBPF egress allowlists per sandbox as in DSec (Huang et al. 2026), no credentials inside the sandbox, and verifier data held outside it.
Operational constraints often decide more than security analysis does. MicroVMs need KVM, so cloud nodes must be bare-metal or allow nested virtualization. gVisor has compatibility gaps for some system calls and pays the most on filesystem-heavy workloads. Shared-kernel options require a fast kernel patch cadence. Denied system calls and blocked egress should be logged and reviewed: they are security events and, just as often, the first visible sign of reward hacking.
Image Economics and Lifecycle
Most of a sandbox's start-up cost is moving its filesystem, not booting its kernel, because 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: provisioning is dominated by image economics and lifecycle; environments should stay dependency-light, with heavy tooling moved behind service boundaries; and infrastructure failures must be labeled rather than scored.
Three techniques recur across the published systems:
- Load lazily. DSec converts OCI images offline to EROFS, keeps metadata local and fetches data blocks from its 3FS distributed filesystem on demand. Runtime access covered only 4.2% to 13.3% of image data in the sampled images, and in an 8,192-container burst 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 is discarding the 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).
Let a step request \(B\) sandboxes for tasks \(t_1,\dots,t_B\), with image sizes \(S_t\). Under eager pulling the bytes moved are \(\sum_{i \in \text{miss}} S_{t_i}\), summed over requests whose image is not already on the chosen node. Under lazy loading only the blocks read move, \(\sum_{i \in \text{miss}} a_{t_i} S_{t_i}\), where \(a_t\) is the fraction of the image touched at run time; DSec measured \(a_t\) between 0.042 and 0.133 (Huang et al. 2026). Burst time is roughly bytes moved divided by the smaller of registry bandwidth and aggregate node bandwidth.
Placement sets the miss rate. With \(T\) task images, \(N\) nodes and a per-node cache of \(C\) images, random placement hits only when the node happens to hold the image, roughly \(C/T\) in steady state. Image-aware placement assigns each task to a fixed node, so each node serves about \(T/N\) images and the hit rate approaches \(\min(1, C N / T)\).
Reset cost follows the same logic. Recreating a sandbox costs \(O(|I|)\) in image size; a copy-on-write reset costs \(O(|\Delta|)\) in the bytes the episode wrote, or \(O(1)\) when the upper layer is renamed and deleted asynchronously.
The simulation below holds 3,000 task images (one per task, median 2 GB), 64 nodes with a 40-image cache each, and 512 sandboxes per step. It counts the gigabytes moved per step under eager pulling and under lazy loading of 10% of each image, for random placement and for image-aware placement that sends each task to a fixed node.
"""Bytes moved per training step for a suite with one image per task:
eager pull vs lazy block fetch, with random vs image-aware node placement (per-node LRU caches)."""
import numpy as np
from collections import OrderedDict
rng = np.random.default_rng(0)
T, NODES, CACHE, BATCH, STEPS = 3000, 64, 40, 512, 50 # tasks, nodes, images/node, sandboxes/step
size_gb = rng.lognormal(np.log(2.0), 0.6, T) # one image per task, median 2 GB
def simulate(placement, frac_read):
caches = [OrderedDict() for _ in range(NODES)]; moved = []
for _ in range(STEPS):
tasks, gb = rng.choice(T, BATCH, replace=False), 0.0
for t in tasks:
n = t % NODES if placement == "image-aware" else rng.integers(NODES)
c = caches[n]
if t in c: c.move_to_end(t); continue # hit: nothing to move
gb += size_gb[t] * frac_read # miss: pull all, or only blocks read
c[t] = True
if len(c) > CACHE: c.popitem(last=False)
moved.append(gb)
return np.mean(moved[10:]) # skip cache warm-up
for placement in ["random", "image-aware"]:
for name, f in [("eager", 1.0), ("lazy 10%", 0.10)]:
print(f"{placement:<12} {name:<9} {simulate(placement, f):8.0f} GB per step")
It prints the mean bytes moved per step after cache warm-up; laziness and placement each cut traffic several-fold and their effects multiply. Output:
random eager 1177 GB per step
random lazy 10% 118 GB per step
image-aware eager 198 GB per step
image-aware lazy 10% 20 GB per stepAn image pipeline for an environment suite has four stages, all off the critical path. Images are built in CI keyed by task id and pinned by digest, so a trajectory can always name the exact filesystem it ran on. They share base layers, since many SWE tasks differ only in the repository layer above a common OS and language runtime. They are converted offline to a lazy format such as EROFS, with hot blocks optionally prefetched from a profiling run. And they are placed on nodes before rollouts ask for them, as GKE's Agent Sandbox SDK does (Shi & Glottmann 2026).
Placement has to balance affinity against hot spots, because a popular task pinned to one node concentrates load there. Garbage collection must retire images of removed tasks without evicting those of the next step.
Failure modes appear under burst: registry throttling when thousands of nodes miss at once, stale node caches serving an old digest after a task is fixed, and lazy-fetch stalls that move latency from start-up into the middle of an episode, where it must be timed and labeled rather than charged to the policy. Keeping environments dependency-light, with heavy tools behind service boundaries (Kondragunta 2026), is the cheapest way to keep images small.
Cold Start, Warm Pools and Snapshots
Cold start matters for its tail more than its mean, because a synchronous training step waits for the slowest sandbox in the batch. GKE reported that warm pools, off-path hydration and a rate-limited controller cut worst-case time to first command from about 7.5 minutes to under 10 seconds (the "45×" headline) while the average fell roughly tenfold, on 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 and built NitroBox: daemonless, rootless namespace sandboxes with copy-on-write initialization and optional CRIU checkpoints for branching.
- Against Docker, creation was 10.6× faster, reset 24.6× and deletion 19.1×.
- 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. They branch: several trajectories continue from one intermediate state (GKE pod snapshots, NitroBox's CRIU path). They preempt: DSec saves a microVM's memory and state and frees the host, then restores it later. And they author: DSec's incremental disk diff of a live sandbox can be reused as a new environment.
A synchronous step over \(B\) sandboxes with independent start latencies \(L_i \sim F\) waits for \(\max_i L_i\), and
\[ P\big(\max_i L_i \le t\big) = F(t)^B . \]The median step is reached where \(F(t) = 0.5^{1/B}\); for \(B = 1024\) this is the 0.99932 quantile of a single sandbox. Step time is therefore governed by the far tail of start latency, which is why GKE reports the worst-case time to first command alongside the mean (Shi & Glottmann 2026).
A warm pool removes the tail from the critical path, and its size follows from Little's law: the mean number of sandboxes held is \(L = \lambda W\), with \(\lambda\) the episode start rate and \(W\) the mean holding time (episode, verification, reset). The pool must also cover provisioning delay \(D\) and a fraction \(f\) of leases that fail health checks:
\[ N_{\text{pool}} \;\approx\; \frac{\lambda\,(W + D)}{1 - f} \;+\; H, \]where \(H\) is burst headroom for the start of a synchronous step. At 2,000 starts per minute, \(W = 6\) min, \(D = 1\) min and \(f = 0.03\), the pool needs about 14,400 sandboxes before headroom. \(W\) should come from a high percentile because episode time is heavy-tailed, and density should be computed from requests, not use: Sandman found sampled pods used about 10.5% of requested CPU and 1.9% of requested memory (Yan, Wang et al. 2026). The practical floor is one sandbox per in-flight rollout (Liu et al. 2026).
Snapshots change the arithmetic of branching: continuing \(k\) trajectories from state \(s_t\) costs one snapshot and \(k\) restores instead of \(k\) replays of \(t\) steps.
The simulation compares cold starts (log-normal around 20 seconds, with 3% of starts hitting a slow node or registry) against leases from a warm pool (about 0.4 seconds, with 2% of leases failing a health check and being replaced). For batches of 1,024 sandboxes it reports the mean, the p99, and the expected wait of a synchronous step, which is the batch maximum. It then sizes a pool with Little's law.
"""A synchronous step waits for its slowest sandbox: compare the batch maximum of
cold starts with warm-pool leases, then size the pool with Little's law."""
import numpy as np
rng = np.random.default_rng(0)
def cold(n): # pull + boot; 3% hit a slow node or registry
t = rng.lognormal(np.log(20), 0.5, n)
slow = rng.random(n) < 0.03
return np.where(slow, t + rng.exponential(240, n), t)
def warm(n, f_bad=0.02): # lease a checked sandbox; a bad lease is replaced
t = rng.lognormal(np.log(0.4), 0.3, n)
return t + (rng.random(n) < f_bad) * rng.lognormal(np.log(0.4), 0.3, n)
B = 1024
for name, gen in [("cold", cold), ("warm pool", warm)]:
s = gen(200 * B).reshape(200, B) # 200 steps of B sandboxes
print(f"{name:<9} mean {s.mean():6.1f} s p99 {np.quantile(s, .99):6.1f} s "
f"step waits (mean of max) {s.max(1).mean():6.1f} s")
print(f"per-sandbox quantile that sets the median step at B={B}: {0.5 ** (1 / B):.5f}")
def pool_size(lam_per_min, hold_min, provision_min, f_fail, burst):
return lam_per_min * (hold_min + provision_min) / (1 - f_fail) + burst
print("pool for 2000 starts/min, 6 min held, 1 min provision, 3% failed leases:",
round(pool_size(2000, 6, 1, 0.03, 0)))
It prints per-sandbox latency statistics and the mean batch maximum for each regime, the per-sandbox quantile that sets the median step, and the pool size for the stated load. Output:
cold mean 29.7 s p99 284.2 s step waits (mean of max) 984.5 s
warm pool mean 0.4 s p99 0.9 s step waits (mean of max) 1.2 s
per-sandbox quantile that sets the median step at B=1024: 0.99932
pool for 2000 starts/min, 6 min held, 1 min provision, 3% failed leases: 14433A warm-pool controller keeps a target number of booted, health-checked sandboxes per image or image family, sized from forecast rollout demand and raised just before each step's burst. Creation is rate-limited to protect the control plane: an unthrottled controller that asks for thousands of pods at once overloads the Kubernetes API server and the registry and lengthens the tail it is meant to cut. GKE combined warm pools, off-path hydration and a rate-limited controller to cut worst-case time to first command from about 7.5 minutes to under 10 seconds (Shi & Glottmann 2026).
Lighter runtimes shrink the work a pool hides. NitroBox drops the container daemon and resets by swapping an overlay upper directory (Nie et al. 2026; NitroBox package docs). Snapshots add branching, preemption, as when DSec frees a host and restores the microVM later (Huang et al. 2026), and authoring of new environments from a live state. Process checkpoints through CRIU do not cover every resource; open network connections and devices need care, and GPU state usually forces a full-VM path.
The dashboard tracks time to first command at p50, p99 and maximum, pool depth and miss rate, health-check rejections and reset time. Two failure modes recur: a pool drained at the start of each synchronous step, and a pool still holding sandboxes from an old image digest after a task fix, which must be drained whenever the environment version changes.
Providers and In-House Fleets
Sandbox supply has split into managed providers, Kubernetes primitives and in-house fleets, and the published in-house systems now run at hundreds of thousands of concurrent sandboxes. Managed services sell fast start and an SDK: per a 2026 comparison, E2B runs Firecracker microVMs, Daytona hardened containers or VMs, Modal gVisor, and Northflank Kata with Cloud Hypervisor (Upstash 2026); labs that train at frontier scale have described building their own.
| System | Isolation | Reported scale or speed | Notable mechanism |
|---|---|---|---|
| DSec (DeepSeek, 2026) | Containers in VMs, Firecracker microVMs, full VMs | 380,000+ concurrent; ~3M per day | Lazy EROFS images; snapshot preemption |
| Sandman (Amazon, 2026) | Pods on EKS | ~3.1M in two weeks; peak 11,858 concurrent | Exec daemon mounted into unmodified images |
| GKE Agent Sandbox (2026) | gVisor pool in benchmarks | Tail time to first command from ~7.5 min to <10 s | Warm pools, image streaming, forks |
| Prime Sandboxes (2026) | MicroVM | ~30M created; 20,000+ concurrent in a dashboard | Immutable task images |
| Modal (2026) | gVisor (per Upstash) | Start in hundreds of ms (vendor claim) | Snapshots skip setup |
| NitroBox (2026) | Rootless namespaces | Reset 24.6× faster than Docker | Daemonless; 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: in a 10,000-request burst, half the sandboxes were usable after 116 seconds and all of them only after 308; estimated availability per session start was 91.16% to 99.73% across three production campaigns, while in a fourth only 69.5% of recorded starts obtained a pod (Yan, Wang et al. 2026). Losing a few percent of leases is normal, so the rollout layer must treat failure as an outcome.
Three quantities govern supply. Availability: if a single lease attempt succeeds with probability \(a\) and failures are independent, a lease with \(k\) retries succeeds with probability \(1 - (1-a)^{k+1}\), and a GRPO group of \(G\) rollouts is complete with probability \(\big(1-(1-a)^{k+1}\big)^G\). At Sandman's lowest campaign availability, \(a = 0.695\) (Yan, Wang et al. 2026), a group of 8 without retries is complete about 5% of the time.
Bias: if a lease failure is scored as reward 0 rather than labeled, the measured pass rate is \(\hat p = a\,p\), not \(p\), and the error falls unevenly on tasks with heavy images or slow starts, which are exactly the tasks whose leases fail most. Dropping labeled failures keeps \(\hat p\) unbiased when failure is independent of outcome.
Cost: a managed service at \(c_m\) per sandbox-hour competes with an in-house fleet at fixed cost \(F\) plus \(c_h / u\) per sandbox-hour at utilization \(u\). In-house is cheaper beyond \(H^* = F / (c_m - c_h/u)\) sandbox-hours, provided \(c_m > c_h/u\). Because pods use a small fraction of what they request (Yan, Wang et al. 2026), the effective \(u\) depends on overcommit policy as much as on hardware.
Lease failure is an outcome to be handled, not an exception. The simulation draws GRPO groups of 8 rollouts with a true pass rate of 0.40 at three per-attempt availabilities (the range reported across production campaigns) with and without two retries. It reports the fraction of rollouts that obtained a sandbox, the fraction of complete groups, and the pass rate measured two ways: folding failures into reward 0, or labeling them as infrastructure errors and dropping them.
"""Sandbox leases fail at a measurable rate. Retry, then label what still fails as an
infrastructure error instead of scoring it, and track how many GRPO groups survive."""
import numpy as np
rng = np.random.default_rng(0)
G, PROMPTS, TRUE_PASS = 8, 20000, 0.40
def campaign(avail, retries):
ok = np.zeros((PROMPTS, G), bool)
for _ in range(1 + retries): ok |= rng.random((PROMPTS, G)) < avail # each try may lease
passed = rng.random((PROMPTS, G)) < TRUE_PASS
scored_as_zero = (passed & ok).mean() # failures folded into reward 0
labeled = passed[ok].mean() # failures dropped, others scored
return ok.mean(), ok.all(1).mean(), scored_as_zero, labeled
print("avail retries leased full groups pass if fail=0 pass if labeled")
for a in [0.9973, 0.9116, 0.695]:
for k in [0, 2]:
l, g, z, lab = campaign(a, k)
print(f"{a:.4f} {k:^7} {l:.4f} {g:^11.3f} {z:^14.3f} {lab:^15.3f}")
Retries restore complete groups; folding failures into reward 0 biases the pass rate down in proportion to unavailability, while labeling leaves it at 0.40. Retries are modeled as independent; correlated failures in a node or zone make real retries less effective. Output:
avail retries leased full groups pass if fail=0 pass if labeled
0.9973 0 0.9973 0.979 0.399 0.400
0.9973 2 1.0000 1.000 0.400 0.400
0.9116 0 0.9106 0.473 0.365 0.401
0.9116 2 0.9993 0.994 0.402 0.402
0.6950 0 0.6947 0.054 0.278 0.399
0.6950 2 0.9723 0.799 0.389 0.400Managed providers suit work whose concurrency fits within their quotas and that values a fast start and an SDK over control. Per a 2026 comparison, E2B runs Firecracker microVMs, Daytona hardened containers or VMs, Modal gVisor and Northflank Kata (Upstash 2026). In-house fleets pay off at hundreds of thousands of concurrent sandboxes, when snapshot preemption or custom image formats are needed, or when sandboxes must sit next to the training cluster: DSec reports over 380,000 concurrent (Huang et al. 2026) and Prime Intellect runs every sandbox as a microVM (Prime Intellect 2026).
The useful evaluation questions are concrete: the boundary and its kernel, tail time to first command at the target concurrency (not the mean at low load), concurrency quotas, a snapshot and fork API, egress control, regions near the GPUs, pricing per vCPU-second and GiB-second, and how failures are reported to the client.
Whatever the source, the rollout layer retries on a different node or zone, labels what still fails, and alerts when the labeled rate rises. Sandman's numbers show why: in a 10,000-request burst half the sandboxes were usable after 116 seconds and all only after 308, and one campaign obtained a pod for only 69.5% of starts (Yan, Wang et al. 2026). Some teams keep a second provider as failover for burst capacity, at the cost of maintaining two image pipelines.
Rollout Systems
A rollout system turns a policy checkpoint, a task set and a sandbox fleet into scored trajectories, and in agentic RL it is split across three independently scaled services: inference engines that sample tokens, an environment fleet that executes actions and verifies outcomes, and a trainer that updates weights. Almost every efficiency problem in the field (idle GPUs, stale samples, lost episodes) is a coordination problem between those three.
A rollout system can be modeled as three pools sharing one stream of episodes. Let \(\lambda\) be the rate at which episodes start, \(W_g\) the engine slot-time an episode consumes, \(W_e\) the time it holds a sandbox (execution, verification and reset), and \(B\) the trainer's batch size in episodes. By Little's law each pool's average occupancy is its arrival rate times its holding time, so the sustainable rate is set by the tightest pool:
\[ \lambda^{*} \;=\; \min\Big(\frac{S_g}{W_g},\; \frac{S_e}{W_e},\; \frac{B}{t_{\text{train}}}\Big), \]with \(S_g\) engine slots, \(S_e\) sandboxes and \(t_{\text{train}}\) the time of one optimizer step. Every other pool is partly idle at \(\lambda^{*}\), and synchronization adds idle time on top. The quantity training cares about is goodput: scored, complete episodes within the staleness bound, per GPU-hour.
Little's law sizes the environment fleet directly. The script below starts episodes at two per second with log-normal sandbox holding times (median 120 s) and compares the law's prediction with the simulated number of sandboxes in use.
import numpy as np
rng = np.random.default_rng(0)
lam = 2.0 # episodes started per second
hold = rng.lognormal(np.log(120), 0.8, 200_000) # seconds a sandbox is held per episode
start = np.cumsum(rng.exponential(1 / lam, hold.size))
t = np.linspace(start[1000], start[-5000], 2000) # sample the fleet in steady state
in_use = [np.sum((start <= x) & (start + hold > x)) for x in t]
print(f"Little's law L = lam*W = {lam * hold.mean():.0f}; simulated mean {np.mean(in_use):.0f}, p99 {np.percentile(in_use, 99):.0f}")
It prints the predicted and simulated mean occupancy and the 99th percentile:
Little's law L = lam*W = 331; simulated mean 330, p99 375
The mean matches \(\lambda W\); the 99th percentile sits about \(2.5\sqrt{L}\) above it, close to the \(2.33\sqrt{L}\) margin of a Poisson count, which is what the number of busy sandboxes is when starts are Poisson. That margin is the headroom a fleet needs so that leases rarely queue.
In production the three services are deployed and scaled separately: engine replicas behind a gateway on inference GPUs, the environment fleet on CPU nodes or a managed sandbox service, and the trainer on a training cluster, joined by an orchestrator and a trajectory store. Each has its own service-level objectives: sandbox lease latency, engine queue time per request, the share of episodes ending in an infrastructure status, sample staleness and trainer idle time. Trainer idle time is the summary signal; when it rises, another pool is the bottleneck. Liu et al. (2026) recommend at least one sandbox per in-flight rollout, and Tinker's RL logs record tokens discarded, sampler–trainer KL and staleness alongside reward, which is the minimum telemetry for diagnosing the coordination problems below.
The Three-Way Split
The 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.
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 and 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).
Why generation and training separate. A decode step for a batch of \(b\) sequences reads every one of the \(P\) parameters once (about \(2P\) bytes in BF16) and performs about \(2P\) floating-point operations per sequence, so its arithmetic intensity is roughly \(b\) FLOPs per byte, plus the key–value cache reads that grow with context. An H100 SXM delivers about 989 dense BF16 TFLOPS against 3.35 TB/s of memory bandwidth, so it becomes compute bound only near 300 FLOPs per byte; decode at realistic batch sizes is bandwidth bound. Training processes whole sequences at about \(6P\) FLOPs per token over large token batches and is compute bound. Environments need no GPU at all. Provisioning each pool for its own bottleneck is cheaper than one homogeneous cluster.
Why sessions are sticky. In a multi-turn episode with prompt \(c_0\) tokens, actions of \(a\) tokens and observations of \(o\) tokens, turn \(k\) sends a context of \(c_k = c_0 + k(a+o)\). If every turn reaches the engine that holds the episode's prefix cache, only new tokens are prefilled, about \(c_0 + (K-1)\,o\) over \(K\) turns. Without any cache reuse the engine prefills each full context,
\[ \sum_{k=0}^{K-1} c_k \;=\; K c_0 + \tfrac{K(K-1)}{2}(a+o), \]which is quadratic in the number of turns. With \(c_0 = 1{,}500\), \(a = 150\), \(o = 600\) and \(K = 20\), the sticky cost is 12,900 prefill tokens per episode and the no-reuse cost 172,500, a factor of about 13.
The routing decision can be checked with a prefix-cache simulation. Each engine remembers how many tokens of each episode it has cached; a request prefills only the part of its context that the chosen engine has not seen. The script compares sticky routing (episode bound to one engine) with random routing over eight engines for 512 twenty-turn episodes.
import numpy as np
rng = np.random.default_rng(0)
E_N, EPISODES, TURNS = 8, 512, 20
prompt, act, obs = 1500, 150, 600 # tokens: system+task prompt, model action, tool observation
def prefill_tokens(route):
cache = [dict() for _ in range(E_N)] # engine -> {episode: cached prefix length}
total = 0
for ep in range(EPISODES):
ctx = prompt
for turn in range(TURNS):
e = route(ep, turn)
total += ctx - cache[e].get(ep, 0) # only the uncached suffix is prefilled
ctx += act # decode appends the action (cached as it is produced)
cache[e][ep] = ctx
ctx += obs # the observation arrives with the next request
return total
sticky = prefill_tokens(lambda ep, turn: ep % E_N)
rr = prefill_tokens(lambda ep, turn: rng.integers(E_N))
print(f"prefill tokens sticky {sticky:,} random {rr:,} ratio {rr / sticky:.1f}x")
It prints total prefill tokens under both policies:
prefill tokens sticky 6,604,800 random 43,476,300 ratio 6.6x
Random routing still gets occasional cache hits when a turn lands on the engine that served an earlier one, so it sits between the sticky cost and the quadratic no-reuse bound. The sticky total equals \(512 \times (1{,}500 + 19 \times 600)\) exactly, which is a useful assertion for a router's test suite.
Coupling choices. Colocated designs, such as veRL's hybrid engine, switch the same GPUs between generation and training and avoid copying weights across a network, but they cannot overlap the two phases. Disaggregated designs, such as slime's Megatron trainer and SGLang rollout joined by a data buffer, overlap them at the cost of a weight transfer after every update and two memory footprints. The choice of framework follows from who owns the agent loop: veRL's agent loop and SkyRL's agent layer run it inside the training framework; an unmodified product harness owns it itself, and only a capturing gateway sees the tokens.
Operating the split. The gateway is the component most often underestimated. It must keep session affinity, record token ids and log-probabilities, tag each request with the weight version that served it, and retry a request on another replica when an engine dies, which costs a full re-prefill but keeps the episode alive. Useful per-pool signals are prefix-cache hit rate per session (a drop indicates broken affinity), engine KV-cache utilization and preemption count, sandbox lease latency at the 99th percentile, weight-sync duration, and trainer idle fraction. When the trainer waits and engines are saturated, add engines; when engines wait on observations, the environment fleet or its tools are the bottleneck.
Synchronous and Asynchronous RL
In synchronous RL every rollout in a batch is generated by the current weights and the trainer waits for the last one; in asynchronous RL generation never stops, and the trainer consumes whatever has finished, accepting samples that are a few policy versions old. Synchronous training is simpler and exactly on-policy, but its utilization collapses when episode lengths vary, which agentic episodes always do.
The cost of waiting is easy to state. If a batch has \(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.
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.
Writing \(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 while keeping data close to on-policy. A trajectory sampled under several weight versions is why behavior logprobs must be recorded at generation time.
Synchronous utilization. Let \(N\) episodes have i.i.d. exponential durations with mean \(m\). By memorylessness, the gaps between successive finishing times are independent exponentials with rates \(N/m, (N-1)/m, \dots, 1/m\), so
\[ \mathbb{E}\big[\max_{i\le N} T_i\big] = m\Big(\frac1N + \frac1{N-1} + \dots + 1\Big) = m\,H_N , \qquad U(N) = \frac{1}{H_N}. \]If each episode also has a fixed part \(a\,m\) (prompt processing, environment setup), \(T_i = m(a + X_i)\) with \(X_i\) exponential, and \(U(N) = (a+1)/(a+H_N)\); with \(a = 1\) this is \(2/(1+H_N)\). Since \(H_N \approx \ln N + 0.577\), utilization falls logarithmically with batch size and never recovers.
Staleness under streaming. In an asynchronous system the trainer publishes a version every \(\Delta = B/\lambda\) seconds. An episode of duration \(D\) that starts at a uniformly random phase spans \(\lfloor D/\Delta + U\rfloor\) version boundaries, \(U \sim \mathrm{Unif}(0,1)\), so its expected lag is \(D/\Delta\). A staleness bound \(k - v(\tau) \le \eta\) therefore removes episodes with \(D \gtrsim \eta\Delta\): the longest ones, which makes a hard bound a length filter.
Correcting stale samples. AReaL's decoupled PPO separates the behavior policy \(\mu = \pi_{v(\tau)}\) from a recent proximal policy \(\pi_{\text{prox}}\) that anchors the trust region:
\[ J(\theta) = \mathbb{E}_{\tau\sim\mu}\Big[\sum_t \frac{\pi_{\text{prox}}(y_t)}{\mu(y_t)} \min\big(r_t \hat A_t,\ \operatorname{clip}(r_t, 1-\epsilon, 1+\epsilon)\,\hat A_t\big)\Big], \quad r_t = \frac{\pi_\theta(y_t)}{\pi_{\text{prox}}(y_t)} . \]With in-flight weight updates, as in PipelineRL, \(\mu\) changes within a sequence: token \(t\) is drawn from \(\pi_{v_t}\), so the behavior probability in the weight must be the one recorded for that token at sampling time.
Both halves of the trade-off can be simulated in a few lines. The first loop measures synchronous utilization (mean duration over expected maximum) and compares it with \(1/H_N\) and \(2/(1+H_N)\). The second runs a streaming system with 512 slots that refill immediately, where the trainer publishes a new version after every 512 finished episodes, and records how many versions elapsed while each episode ran.
import numpy as np
rng = np.random.default_rng(0)
H = lambda n: np.sum(1 / np.arange(1, n + 1))
# Synchronous: each slot runs one episode, the step ends at the slowest one.
for N in (8, 64, 512):
T = rng.exponential(1.0, (2000, N))
U_sim = T.mean() / T.max(1).mean()
Tf = 1.0 + rng.exponential(1.0, (2000, N)) # fixed part equal to the mean random part
print(f"N={N:4d} exp: sim {U_sim:.3f} vs 1/H_N {1 / H(N):.3f} fixed+exp: sim {Tf.mean() / Tf.max(1).mean():.3f} vs 2/(1+H_N) {2 / (1 + H(N)):.3f}")
# Asynchronous streaming: N slots refill immediately; the trainer takes a step every B finished episodes.
N, B, n = 512, 512, 200_000
finish, version, starts_v = [], [], []
clock = np.zeros(N); done = 0; v = 0
import heapq
heap = [(rng.exponential(1.0), i, 0) for i in range(N)]
heapq.heapify(heap)
lags, durs = [], []
t_start = np.zeros(N)
while done < n:
t, i, v_start = heapq.heappop(heap)
lags.append(v - v_start); durs.append(t - t_start[i]) # versions elapsed while the episode ran
done += 1
if done % B == 0: v += 1 # trainer consumes a batch, publishes new weights
t_start[i] = t
heapq.heappush(heap, (t + rng.exponential(1.0), i, v))
lags, durs = np.array(lags[N:]), np.array(durs[N:])
print("async staleness (versions) share:", {k: round(float(np.mean(lags == k)), 3) for k in range(4)}, "max", lags.max())
keep = lags <= 2
print(f"bound eta=2 drops {1 - keep.mean():.3f} of episodes; mean duration kept {durs[keep].mean():.2f}, dropped {durs[~keep].mean():.2f}")
It prints simulated and analytic utilization, the staleness distribution and the effect of a bound of two versions:
N= 8 exp: sim 0.367 vs 1/H_N 0.368 fixed+exp: sim 0.537 vs 2/(1+H_N) 0.538
N= 64 exp: sim 0.210 vs 1/H_N 0.211 fixed+exp: sim 0.346 vs 2/(1+H_N) 0.348
N= 512 exp: sim 0.147 vs 1/H_N 0.147 fixed+exp: sim 0.255 vs 2/(1+H_N) 0.256
async staleness (versions) share: {0: 0.367, 1: 0.402, 2: 0.146, 3: 0.054} max 16
bound eta=2 drops 0.085 of episodes; mean duration kept 0.77, dropped 3.41
The simulation reproduces both formulas to the third decimal. Streaming keeps every slot busy, but about 8.5% of episodes are more than two versions old, and those dropped by the bound last on average more than four times as long as those kept: the staleness bound is a length filter, as the analysis predicts.
When to go asynchronous. The deciding input is the measured distribution of episode durations. Plugging it into the utilization formula shows the idle fraction a synchronous step pays; with short, uniform single-turn episodes the loss is small and synchronous training's exact on-policy semantics are worth keeping. Agentic episodes, whose durations span minutes to hours, almost always justify streaming. The comparison that settles it is held-out accuracy per GPU-hour, not tokens per second: AReaL reported up to 2.77× speedup with equal or better accuracy (Fu et al. 2025), and PipelineRL about twice as fast learning on 128 H100s (Piché et al. 2025). ScaleRL's recipe used PipelineRL with a maximum off-policyness of 8 steps, and its ablations found that the choice among off-policy schemes mainly changes compute efficiency rather than the final asymptote (Khatri et al. 2025).
Engineering requirements. Every token needs a weight-version tag and its behavior log-probability recorded when sampled; the buffer needs backpressure so that engines cannot run arbitrarily far ahead of a slow trainer; and weight loading must not drain the engines, or the synchronization stall returns in another place. veRL exposes rollout importance-sampling corrections as configuration (veRL docs).
Failure modes and monitoring. A staleness histogram per step should be flat over time; a growing tail means the trainer is falling behind. A rising sampler–trainer KL after a deploy points at a kernel or precision change rather than staleness. A bound that silently drops long episodes biases the batch toward short answers, so the share of episodes dropped for staleness, broken down by length, belongs on the same dashboard.
Long-Tail Episodes, Partial Rollouts and Preemption
Episode lengths in agentic RL are heavy-tailed, so a small fraction of episodes 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 and the longest responses were 25–32× the median.
- Their tail batching launches more prompts than needed in short rounds, keeps the first to finish and defers aborted long prompts to dedicated long rounds.
- With adaptive parallelism and asynchronous rewards (including adaptive code-sandbox timeouts), RollPacker trained 2.03–2.56× faster than veRL on 7B–32B models.
Partial rollouts split long episodes across steps instead. Kimi k1.5 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, and some segments can be excluded from the loss (Kimi Team 2025). 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, so a preempted trainer reconnects without replaying commands, and preempted microVMs are snapshotted rather than killed (Huang et al. 2026).
How tails set step time. For exponential durations the expected maximum of \(N\) episodes grows as \(\ln N\); for a Pareto tail with index \(\alpha > 1\) it grows as \(N^{1/\alpha}\), so a heavier tail makes the slowest episode dominate faster as the batch grows.
Over-provisioning. Launching \(N + k\) episodes and keeping the first \(N\) replaces the maximum by the \(N\)-th order statistic. For exponential durations with mean 1,
\[ \mathbb{E}\big[T_{(N:N+k)}\big] = \sum_{j=k+1}^{N+k} \frac1j = H_{N+k} - H_k \approx \ln\frac{N+k}{k}, \]so \(N = 256\) and \(k = 32\) cut the expected wait from \(H_{256} \approx 6.1\) to about 2.2 mean durations. The kept episodes are a biased sample, shorter on average than the population; tail batching avoids discarding them by deferring the aborted prompts to dedicated long rounds.
Partial rollouts. With a per-iteration budget of \(b\) tokens, a response of length \(\ell\) spans \(\lceil \ell/b\rceil\) iterations, and each segment may be generated under a different policy version.
Preemption. If preemptions arrive as a Poisson process with rate \(\nu\) and an interrupted episode restarts from scratch, the expected time to finish an episode of length \(D\) is \((e^{\nu D} - 1)/\nu\), exponential in \(D\). Keeping state outside the preemptible pool reduces the loss to the reconnection time.
The script checks the over-provisioning formula by simulation and then measures, for log-normal response lengths with median 2,000 tokens, how many responses a partial-rollout budget splits and into how many segments.
import numpy as np
rng = np.random.default_rng(0)
H = lambda n: np.sum(1 / np.arange(1, n + 1))
N, R = 256, 4000
# Over-provisioning: launch N+k episodes, keep the first N to finish (exponential durations, mean 1).
for k in (0, 32, 128):
T = np.sort(rng.exponential(1.0, (R, N + k)), axis=1)
wait = T[:, N - 1].mean()
kept_mean = T[:, :N].mean()
print(f"k={k:3d} step wait {wait:.2f} (theory {H(N + k) - H(k) if k else H(N):.2f}) mean kept duration {kept_mean:.2f}")
# Heavy tail: lognormal output lengths, partial rollouts with a per-iteration token budget.
L = rng.lognormal(np.log(2000), 1.0, 100_000).astype(int) + 1
print(f"lengths: median {np.median(L):.0f}, p99 {np.percentile(L, 99):.0f}, max/median {L.max() / np.median(L):.0f}x")
for budget in (4096, 8192, 16384):
segs = np.ceil(L / budget)
print(f"budget {budget:5d}: {np.mean(segs > 1):.3f} of responses span >1 iteration, max {segs.max():.0f} segments")
It prints the step wait and the mean kept duration for three values of \(k\), then the length tail and segment counts:
k= 0 step wait 6.14 (theory 6.12) mean kept duration 1.00
k= 32 step wait 2.18 (theory 2.18) mean kept duration 0.73
k=128 step wait 1.09 (theory 1.10) mean kept duration 0.45
lengths: median 1997, p99 20913, max/median 66x
budget 4096: 0.239 of responses span >1 iteration, max 33 segments
budget 8192: 0.081 of responses span >1 iteration, max 17 segments
budget 16384: 0.018 of responses span >1 iteration, max 9 segments
Thirty-two spare episodes cut the wait by almost two thirds, but the kept episodes are 27% shorter than the population, the selection effect that deferral is designed to remove. With a 4,096-token budget, about a quarter of responses become multi-segment, and the longest spans 33 iterations and therefore up to 33 policy versions.
Remedies in order of cost. A tighter length or turn cap is cheapest but truncates long correct work and biases the reward against length. Over-provisioning with deferral (RollPacker's tail batching, Gao et al. 2025) keeps every prompt but needs a deferred queue and dedicated long rounds. Tail-aware synchronous scheduling stays on-policy: Seer splits groups into chunks, schedules the longest first and drafts speculative tokens from sibling responses, reporting 74–97% higher rollout throughput than synchronous veRL; it also found that the last 10% of requests can take up to half of rollout time (Qin et al. 2025). Partial rollouts and full asynchrony remove the tail from the step entirely but make trajectories multi-version.
Agent-specific costs. A partial agent rollout must hold or snapshot its sandbox between segments. Holding raises the sandbox holding time and with it the fleet size by Little's law; snapshotting costs storage and restore time. Preemptible GPUs are attractive for rollout but only when, as in DSec (Huang et al. 2026), the sandbox and worker state live outside the preemptible pool.
Monitoring. Episode-duration percentiles per task family, the age of the oldest deferred prompt (a starvation guard), segments per trajectory, the truncated share, and the reward–length correlation of deferred versus kept episodes. A deferred queue that only grows means long prompts are never trained on.
Infrastructure Failures Are Labeled, Not Scored
An episode that ends because a sandbox died, an image failed to pull or the verifier crashed says nothing about the policy, and 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 implement it in their interfaces: GKE's SDK surfaces failed sandboxes as retriable instead of dropping them, and OpenEnv's 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. A command the agent ran that hangs is the agent's doing and comes back as an observation; an exhausted turn budget is the agent's outcome and is scored. 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. If infrastructure failures correlate with the task (a heavy repository that runs out of memory, a verifier that crashes on one output format), discarding the failed attempts quietly removes hard tasks, so infra-failure rates belong on per-task dashboards. And group-relative estimators such as GRPO need complete groups: refill or drop a group that loses members rather than normalizing over fewer samples.
Scoring failures as zero. Let task \(i\) have pass rate \(p_i\) and infrastructure-failure probability \(f_i\). Scoring a failure as reward 0 gives an observed mean of \(p_i(1 - f_i)\) and, in a group-relative estimator, assigns negative advantage to failed attempts that would have succeeded. Failures are rarely independent of behavior: if a sandbox fails at hazard rate \(h\) per second, an episode of duration \(D\) fails with probability \(1 - e^{-hD}\), so scoring failures as zero acts as an implicit penalty on long episodes.
Dropping failures. Labeling and discarding removes the bias in the reward but reweights the task distribution by \(1 - f_i\) per sample, and if groups must be complete, by \((1 - f_i)^G\) per group. With \(G = 8\), a task at \(f = 0.02\) completes a group 85% of the time and a task at \(f = 0.4\) only 1.7% of the time: heavy tasks vanish from training unless groups are refilled.
Retries and estimates. With up to \(r\) retries an attempt eventually succeeds with probability \(1 - f^{\,r+1}\), at an expected \((1 - f^{\,r+1})/(1 - f)\) attempts. Per-task failure rates are binomial estimates; flagging a task when the lower end of its Wilson interval exceeds the fleet baseline avoids alarms on tasks seen only a few times.
The batch-assembly step is where the status label becomes training data. The function below keeps only scored episodes, emits complete groups of \(G\), lists the refills each task needs and computes per-task infrastructure-failure rates. The simulation gives 10% of tasks a 40% failure rate and the rest 2%, and measures how many positive advantages would flip sign if failures were scored as zero.
import numpy as np
from collections import defaultdict
rng = np.random.default_rng(0)
def assemble_groups(episodes, G):
"""episodes: dicts with task_id, status, reward. Returns complete groups of G scored episodes,
the tasks that need refills, and per-task infra-failure rates for the dashboard."""
by_task, fails, seen = defaultdict(list), defaultdict(int), defaultdict(int)
for e in episodes:
seen[e["task_id"]] += 1
if e["status"] == "ok":
by_task[e["task_id"]].append(e["reward"])
elif e["status"] in ("infra_error", "verifier_error"):
fails[e["task_id"]] += 1 # labeled, never scored
groups = {t: np.array(r[:G]) for t, r in by_task.items() if len(r) >= G}
refill = {t: G - len(by_task[t]) for t in seen if len(by_task[t]) < G}
return groups, refill, {t: fails[t] / seen[t] for t in seen}
def grpo_adv(r):
s = r.std()
return (r - r.mean()) / s if s > 0 else np.zeros_like(r)
n_tasks, G = 2000, 8
p = rng.beta(2, 2, n_tasks) # true pass rate per task
f = np.where(np.arange(n_tasks) < 200, 0.4, 0.02) # 10% heavy tasks hit infra failures often
eps, flipped, positive = [], 0, 0
for t in range(n_tasks):
succ, infra = rng.random(G) < p[t], rng.random(G) < f[t]
eps += [{"task_id": t, "status": "infra_error" if x else "ok", "reward": float(s)} for s, x in zip(succ, infra)]
a_true, a_zero = grpo_adv(succ * 1.0), grpo_adv(np.where(infra, 0.0, succ * 1.0))
flipped += np.sum((a_true > 0) & (a_zero < 0)); positive += np.sum(a_true > 0)
groups, refill, fail_rate = assemble_groups(eps, G)
heavy = [t for t in groups if t < 200]
print(f"scoring infra as 0 flips {flipped / positive:.3f} of positive advantages to negative")
print(f"complete groups: heavy {len(heavy)}/200, other {len(groups) - len(heavy)}/1800; tasks needing refills {len(refill)}")
print(f"dashboard infra-failure rate: heavy {np.mean([fail_rate[t] for t in range(200)]):.3f}, other {np.mean([fail_rate[t] for t in range(200, n_tasks)]):.3f}")
It prints the share of flipped advantages, the complete groups per task class and the dashboard failure rates:
scoring infra as 0 flips 0.056 of positive advantages to negative
complete groups: heavy 5/200, other 1539/1800; tasks needing refills 456
dashboard infra-failure rate: heavy 0.399, other 0.020
Without refills only 5 of 200 heavy tasks produce a complete group, against 1,539 of 1,800 others: discarding failures is safe for the reward but not for the task mix, which is why the refill list matters as much as the filter.
Where labels are set. The orchestrator, not the environment, assigns the final status, because only it sees lease, engine and verifier errors together. This follows Kondragunta (2026), and the published interfaces agree: GKE's SDK reports failed sandboxes as retriable (Shi & Glottmann 2026), and OpenEnv's Harbor integration (OpenEnv 2026) distinguishes a verifier that never ran from a score of zero. Every attempt is logged, including retried ones, so that failure patterns can be audited.
Operating the boundary. Resource limits belong to the task specification: an agent command that exceeds them returns an error observation, whereas a sandbox killed by host pressure is infrastructure. A cheap health check after lease and reset (a smoke command, a verifier dry run) catches broken images before any tokens are generated, since every failure after generation wastes engine time. Retry budgets and circuit breakers per image and per node prevent retry storms when a registry or node pool fails.
Dashboards and alerts. Infrastructure- and verifier-error rates by task, image, node pool and verifier version; retries per episode; groups refilled or dropped; and the task mix of the trained batch against the task mix of the queue. Tasks whose failure rate stays high are quarantined and repaired rather than silently retried, since each retry costs a full episode of generation.
Capturing Trajectories Exactly
The trainer must compute gradients on exactly the token sequence the inference engine sampled, under the same context, with 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, because text is decoded, parsed, re-rendered through chat templates and re-encoded between turns, and each step can change token ids while leaving the visible text identical.
Policy-gradient methods estimate \(\nabla_\theta J(\theta) = \mathbb{E}_{x\sim\mathcal{D},\,y\sim\pi_\theta(\cdot\mid x)}\big[R(x,y)\,\nabla_\theta \log \pi_\theta(y\mid x)\big]\) from samples, and the estimator is unbiased only when the gradient is evaluated at the sampled pair \((x, y)\). Let \(D\) map token ids to text and \(E\) map text to ids. A text-based pipeline instead evaluates \(\nabla_\theta \log \pi_\theta(\tilde y \mid \tilde x)\) with \(\tilde y = E(D(y))\) and \(\tilde x\) the re-rendered context, while the reward \(R(x,y)\) still belongs to the sampled episode. Whenever \(\Pr[(\tilde x,\tilde y)\neq(x,y)] > 0\) the expectation of this estimator differs from \(\nabla_\theta J\), and the bias has no closed form because it depends on which sequences drift.
Drift compounds with episode length. If each turn drifts independently with probability \(p\), an episode of \(T\) turns is affected with probability \(1-(1-p)^T\): with \(p = 0.02\), about 18% of 10-turn episodes and 64% of 50-turn episodes. Single-turn RL has \(T = 1\) and never re-encodes, so \(p = 0\) by construction.
The smallest reproduction needs a tokenizer whose decoding is many-to-one and a policy that assigns probabilities to token ids. The vocabulary below contains "a", "b" and the merged token "ab". The engine samples the pair, and greedy re-encoding of the decoded text returns the merged token instead. The text is identical; the ids, their number and their total log-probability are not, so a trainer that re-encodes text computes the gradient of a sequence the policy never sampled.
import numpy as np
VOCAB = ["a", "b", "ab", "c", " "] # "ab" is one token, but "a"+"b" is also valid
ID = {s: i for i, s in enumerate(VOCAB)}
def encode(text): # greedy longest match: the canonical tokenization
out, i = [], 0
while i < len(text):
for L in (2, 1):
if text[i:i+L] in ID: out.append(ID[text[i:i+L]]); i += L; break
return out
decode = lambda ids: "".join(VOCAB[i] for i in ids)
rng = np.random.default_rng(0)
logits = rng.normal(0, 1, (len(VOCAB), len(VOCAB))) # toy policy: next token depends on previous
logits[ID["a"], ID["b"]] += 2.0 # the policy likes "b" right after "a"
logp_table = logits - np.log(np.exp(logits).sum(1, keepdims=True))
def seq_logp(ids, start=ID[" "]):
prev, lps = start, []
for t in ids: lps.append(logp_table[prev, t]); prev = t
return np.array(lps)
sampled = [ID["a"], ID["b"], ID["c"], ID["a"], ID["b"]] # what the engine actually sampled
reencoded = encode(decode(sampled))
print("text :", repr(decode(sampled)))
print("sampled :", sampled, "sum logp", round(seq_logp(sampled).sum(), 3))
print("re-encoded:", reencoded, "sum logp", round(seq_logp(reencoded).sum(), 3))
print("same text, same ids?", decode(reencoded) == decode(sampled), reencoded == sampled)
Output: the same string yields five sampled ids but three re-encoded ids, with different sequence log-probabilities.
text : 'abcab'
sampled : [0, 1, 3, 0, 1] sum logp -8.832
re-encoded: [2, 3, 2] sum logp -6.252
same text, same ids? True False
In production the requirement becomes an interface contract between the rollout fleet and the trainer: every trained token arrives with its id, the behavior log-probability recorded by the engine, a loss-mask bit and the weight version that sampled it, and no component between engine and trainer tokenizes text. Frameworks built for multi-turn agents, such as veRL's agent loop, the Miles session servers, NeMo Gym and OpenEnv's Harbor integration, enforce the contract at one boundary rather than inside each environment.
Violations are silent. A text-path pipeline produces valid-looking batches, losses and reward curves; the symptoms are learning curves that are less stable than expected and an engine–trainer log-probability gap larger than numeric noise. The defense is a conformance test per model, template and harness before a run, plus counters during it: calls whose prompt does not extend the previous call, completions without log-probabilities, and the mean per-token log-ratio between trainer and engine before the first update. Hosted APIs that return neither ids nor log-probabilities serve evaluation, not on-policy training.
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:
- Retokenization. Decoding is many-to-one, so decode-then-encode can return different ids for the same string.
- Chat-template rewriting. Templates are not always prefix-preserving. 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, so appending a tool message changes earlier tokens (18 of 19 tested families were prefix-preserving).
- 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.
The Agent Lightning team reported unstable learning curves from drift and noted that token-level importance sampling cannot correct it, 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, which is why its agent loop is token-in, token-out by design (veRL docs).
Each failure mode has a short formal statement.
- Retokenization. Decoding \(D\) is surjective but not injective: many id sequences decode to the same string. A deterministic tokenizer returns one canonical sequence per string, so \(E\circ D\) is a projection onto canonical tokenizations, \(E(D(E(D(y)))) = E(D(y))\), and \(E(D(y)) = y\) holds only when \(y\) was already canonical. Nothing in \(\pi_\theta\) restricts sampling to canonical sequences.
- Prefix preservation. A template maps a message list \(m_{1:k}\) to ids. It is prefix-preserving if \(\mathrm{render}(m_{1:k})\) is a prefix of \(\mathrm{render}(m_{1:k'})\) for every \(k < k'\). A template that shows reasoning only on the last assistant turn violates this as soon as another turn follows an assistant turn that had reasoning.
- Lossy re-rendering. With a parser \(P\) and serializer \(S\), \(S(P(s)) = s\) holds only for strings already in the serializer's canonical form; whitespace, line breaks and key order are not preserved in general.
Importance weighting cannot repair any of these. The truncated weight \(w_t = \min\{\pi_\theta(y_t\mid c_t)/\pi_{\text{roll}}(y_t\mid c_t),\, C\}\) corrects for scoring the same token in the same context \(c_t\) under two slightly different distributions. Under drift the trainer scores \(\tilde y_t\) in a context \(\tilde c_t \neq c_t\) that the sampler never conditioned on, so no ratio of recorded quantities describes the change: the mismatch lies in the conditioning event, not in a density.
The script reproduces each drift source in isolation: a three-token vocabulary for retokenization, a toy chat template that can drop reasoning from earlier assistant turns, and Python's JSON round trip for re-rendering a tool call. The template check renders every prefix of the conversation that ends on an assistant turn and tests whether it is a prefix of the full rendering, which is the property a multi-turn trainer relies on when it concatenates turns into one sequence.
import json
VOCAB = {"a": 0, "b": 1, "ab": 2}
def encode(s): # greedy longest match
out, i = [], 0
while i < len(s):
L = 2 if s[i:i+2] in VOCAB else 1
out.append(VOCAB[s[i:i+L]]); i += L
return out
decode = lambda ids: "".join({v: k for k, v in VOCAB.items()}[i] for i in ids)
def render(msgs, keep_old_reasoning):
"""Toy chat template; like several real ones it can drop reasoning from earlier assistant turns."""
last = max(i for i, m in enumerate(msgs) if m["role"] == "assistant")
out = ""
for i, m in enumerate(msgs):
think = m["role"] == "assistant" and (keep_old_reasoning or i == last)
out += f"<|{m['role']}|>" + (f"<think>{m['reasoning']}</think>" if think else "") + m["content"] + "<|end|>"
return out
def non_prefix_turns(msgs, **kw):
"""Turn counts k (ending on an assistant turn) whose rendering is not a prefix of the full rendering."""
full = render(msgs, **kw)
return [k for k in range(2, len(msgs) + 1)
if msgs[k - 1]["role"] == "assistant" and not full.startswith(render(msgs[:k], **kw))]
sampled_call = '{"name": "grep", "args": {"pattern":"TODO"}}' # the model's own spacing
msgs = [{"role": "user", "content": "find TODOs"},
{"role": "assistant", "reasoning": "use grep", "content": sampled_call},
{"role": "tool", "content": "a.py:3: TODO"},
{"role": "assistant", "reasoning": "done", "content": "Found one."}]
ids = [0, 1]
print("1 retokenization :", ids, "->", repr(decode(ids)), "->", encode(decode(ids)))
print("2 template drops old reasoning, non-prefix at k =", non_prefix_turns(msgs, keep_old_reasoning=False))
print(" template keeps old reasoning, non-prefix at k =", non_prefix_turns(msgs, keep_old_reasoning=True))
rer = json.dumps(json.loads(sampled_call)) # parse, then serialize again
print("3 lossy re-render:", repr(sampled_call), "->", repr(rer), "| equal:", rer == sampled_call)
Output: the template that drops earlier reasoning breaks the prefix property after the first assistant turn, and the JSON round trip changes the model's spacing.
1 retokenization : [0, 1] -> 'ab' -> [2]
2 template drops old reasoning, non-prefix at k = [2]
template keeps old reasoning, non-prefix at k = []
3 lossy re-render: '{"name": "grep", "args": {"pattern":"TODO"}}' -> '{"name": "grep", "args": {"pattern": "TODO"}}' | equal: False
Each source has a different owner in a training stack. Retokenization is owned by whoever touches text between engine and trainer; the fix is to never re-encode sampled text and to count completions whose decode–encode round trip differs, which is harmless only while nothing re-encodes them. Template behavior is owned by the model release: a new model revision or tokenizer config on a model hub can change prefix preservation without any change to the training code. Re-rendering is owned by the harness, whose tool-call parser and message objects are convenient views but must not become the source of truth.
Practical rules follow. Keep a registry of templates with their prefix-preservation test results, rerun it when the model, tokenizer or template revision changes, and record those versions in every episode. When a template is not prefix-preserving, choose explicitly: train each turn as its own sample with its exact prompt (correct but costly), or mask earlier tokens. Store the raw completion ids and string alongside any parsed tool call. Watch for drift introduced by routine dependency upgrades in harness libraries, which reformat tool calls without failing any test.
Capture at the Gateway
The robust fix is to record tokens where they are produced, which is also the design that Kondragunta (2026) recommends 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_idsfrom 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 and 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, tokenizes only new messages, and 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, which they estimate 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
TrainingTraceholds 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.
Exact capture changes the cost of training on multi-turn episodes. Suppose each of \(T\) turns adds about \(\ell\) tokens of model output and tool observation. Without a bit-exact prefix, each turn must be trained as a separate sample whose prompt is that turn's exact context, so the trainer processes \(\sum_{k=1}^{T} k\ell = \ell\,T(T+1)/2\) tokens. With an exact prefix, the whole episode is one sequence of \(T\ell\) tokens. The ratio is \((T+1)/2\): 15.5 at 30 turns and 25.5 at 50, consistent with the Miles team's estimate of about an order of magnitude on 30–50-turn tasks.
On that single sequence the loss is masked so that only sampled tokens receive gradient:
\[ \mathcal{L}(\theta) = -\frac{1}{\sum_t m_t}\sum_t m_t\, w_t\, \hat A\, \log \pi_\theta(y_t \mid y_{<t}), \qquad m_t = \begin{cases} 1 & y_t \text{ sampled by the policy} \\ 0 & y_t \text{ from prompt or tool} \end{cases} \]where \(\hat A\) is the episode advantage and \(w_t\) the behavior correction. If the harness rewrites history at position \(\tau\), tokens before \(\tau\) were sampled under a context that later calls no longer see; masking \(m_t = 0\) for \(t \le \tau\) keeps only tokens with exact conditioning and discards a fraction \(\tau/L\) of the sequence. Branching is handled by prefix matching: call \(j\) is a child of call \(i\) when its prompt starts with \(i\)'s prompt followed by \(i\)'s completion.
A gateway session keeps three aligned arrays per episode: token ids, behavior log-probabilities and a loss mask. Context added by the harness (system prompt, user turn, tool output) is tokenized once, as new tokens only, and masked; engine output is appended exactly as returned. Each engine call conditions on the buffer itself, so consecutive prompts satisfy the prefix property by construction and the episode becomes one training sequence. The engine here is a stub standing in for an OpenAI-compatible server that returns token ids and log-probabilities.
import numpy as np
from dataclasses import dataclass, field
@dataclass
class Session:
"""Append-only token buffer for one episode, kept by the gateway between the harness and the engine."""
ids: list = field(default_factory=list)
logprobs: list = field(default_factory=list) # behavior logprob per token (0.0 where not sampled)
mask: list = field(default_factory=list) # 1 = model-sampled token (trained), 0 = prompt/tool
calls: int = 0
def append_context(self, new_ids): # only NEW messages are tokenized, never the prefix
self.ids += new_ids; self.logprobs += [0.0] * len(new_ids); self.mask += [0] * len(new_ids)
def generate(self, engine):
prompt = list(self.ids) # exact ids the engine will condition on
out_ids, out_lp = engine(prompt)
self.ids += out_ids; self.logprobs += out_lp; self.mask += [1] * len(out_ids)
self.calls += 1
return prompt, out_ids
rng = np.random.default_rng(0)
def toy_engine(prompt): # stands in for vLLM with return_token_ids + logprobs
n = int(rng.integers(3, 7))
return rng.integers(100, 200, n).tolist(), np.log(rng.uniform(0.2, 1.0, n)).round(4).tolist()
s, prompts = Session(), []
s.append_context([1, 11, 12, 13, 2]) # system + user turn, tokenized once
for turn in range(3):
prompt, out = s.generate(toy_engine); prompts.append(prompt)
s.append_context([3] + list(range(50, 50 + 4 * (turn + 1))) + [2]) # tool output, masked out
# prefix property: each call's prompt extends the previous call's prompt + completion
ok = all(prompts[i + 1][:len(prompts[i])] == prompts[i] for i in range(len(prompts) - 1))
m = np.array(s.mask)
print(f"calls={s.calls} tokens={len(s.ids)} trained={m.sum()} masked={len(m) - m.sum()} prefix_ok={ok}")
print("one training sequence per episode:", len(s.ids) == len(s.logprobs) == len(s.mask))
Output: three calls, one 47-token sequence, 12 trained tokens, and the prefix property holds for every call.
calls=3 tokens=47 trained=12 masked=35 prefix_ok=True
one training sequence per episode: True
Gateway capture is mostly a deployment pattern. The product harness runs unmodified with its model base URL pointed at the gateway; the gateway forwards requests to the inference engine with token ids and log-probabilities enabled, appends results to the episode's buffer and writes the finished trace to storage for the trainer. OpenEnv's Harbor integration identifies the episode by using a per-rollout session id as the API key, which avoids any change to the harness.
The gateway is stateful, which sets its main design decisions. Buffers live in memory for speed, so a restart must not lose episodes: an append-only log per session, or failing the affected episodes as infrastructure errors, is required. Routing all calls of a session to the same engine replica keeps the shared prefix in the KV cache. Parallel tool calls, sub-agents and retries create branches; linking calls by token prefix and marking abandoned branches as discarded keeps them from inheriting the main path's reward. Summarization or truncation by the harness must be recorded as an event so the trainer can mask up to it. Operational metrics are the non-prefix call rate, branches per episode, masked-token fraction and gateway latency overhead. Because the gateway sees every prompt and tool output, it also needs the same access controls and secret redaction as any trace store.
Logprobs and the Inference–Training Mismatch
Even with identical tokens, engine and trainer compute slightly different probabilities (different kernels, parallelism and numerics), so the behavior policy's logprobs must 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 and 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, suggests token caps of roughly 1.5 to 5, and 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 requires the engine (vLLM, or a recent SGLang build) to return processed logprobs (after temperature and sampling transforms), checks at start-up by comparing logprob gaps at two temperatures, and downgrades captures with raw logprobs to evaluation-only. Hosted APIs without ids or logprobs yield evaluation traces only.
Let \(\rho_t = \pi_\theta(y_t\mid c_t)/\pi_{\text{roll}}(y_t\mid c_t)\) for a sampled token in context \(c_t\). The truncated weight \(w_t = \min(\rho_t, C)\) gives, for any per-token gradient term \(g_t\),
\[ \mathbb{E}_{\pi_{\text{roll}}}[w_t\, g_t] = \mathbb{E}_{\pi_\theta}[g_t] - \mathbb{E}_{\pi_{\text{roll}}}\big[(\rho_t - C)^{+} g_t\big], \]so the bias is confined to tokens whose ratio exceeds the cap, while the variance is bounded by \(C^2\,\mathbb{E}[g_t^2]\). Smaller \(C\) trades variance for bias. Sequence-level weights are unusable for long responses: \(\log \prod_t \rho_t = \sum_t \log\rho_t\) has variance growing linearly in length, so sequence-level schemes use the geometric mean \(\exp\big(\tfrac{1}{T}\sum_t \log\rho_t\big)\) inside a band.
The mismatch is monitored with the non-negative k3 estimator \(\widehat{\mathrm{KL}} = \tfrac{1}{T}\sum_t(\rho_t - 1 - \log\rho_t)\), unbiased for \(\mathrm{KL}(\pi_{\text{roll}}\,\|\,\pi_\theta)\) because \(\mathbb{E}_{\pi_{\text{roll}}}[\rho_t] = 1\). Li et al. (2025) bound the per-token log-probability gap by \(2\epsilon_{\max}(1-p)\) for a token of probability \(p\) under logit perturbation \(\epsilon_{\max}\), so rare sampled tokens carry most of it.
Processed log-probabilities matter because sampling at temperature \(\tau\) draws from \(\mathrm{softmax}(z/\tau)\); a raw \(\log\mathrm{softmax}(z)\) misstates the behavior policy by an amount that changes with \(\tau\), which is why comparing returned values at two temperatures detects it.
The first part is a capture conformance test to run on a few dozen recorded episodes for every new model, template or harness before training. It turns the failure modes of multi-turn capture into assertions: the prefix property between consecutive calls, one non-positive behavior log-probability per completion token, completions that are unsafe to re-encode, and template drift. The second part computes truncated per-token weights and mismatch diagnostics for a synthetic batch with small numeric noise and a few large tail-token gaps; the third detects an engine that returns raw instead of processed log-probabilities.
import torch
from types import SimpleNamespace as NS
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
class ToyTok: # ids 0..25 are letters; id 26 is the merged token "ab"
def decode(self, ids): return "".join("ab" if i == 26 else chr(97 + i) for i in ids)
def encode(self, text, add_special_tokens=False):
out, i = [], 0
while i < len(text):
if text[i:i + 2] == "ab": out.append(26); i += 2
else: out.append(ord(text[i]) - 97); i += 1
return out
tok = ToyTok()
c1 = NS(idx=0, prompt_ids=[7, 8], completion_ids=[3, 4], logprobs=[-0.1, -0.2], messages=None)
good = NS(idx=1, prompt_ids=[7, 8, 3, 4, 5], completion_ids=[0, 1], logprobs=[-0.3, -0.4], messages="m")
bad = NS(idx=1, prompt_ids=[7, 8, 9, 4, 5], completion_ids=[2], logprobs=[-0.3, 0.1], messages="m")
print("clean :", check_episode([c1, good], tok, lambda m: [7, 8, 3, 4, 5]),
"| retok-unsafe:", getattr(good, "retokenization_unsafe", False))
print("drifted:", check_episode([c1, bad], tok, lambda m: [7, 8, 3, 4, 5]))
# Truncated importance weights and mismatch diagnostics for one batch [B, T]
torch.manual_seed(0)
B, T, cap = 4, 2000, 2.0
logp_roll = torch.log(torch.rand(B, T) * 0.95 + 0.05) # recorded by the engine at sampling time
noise = 0.02 * torch.randn(B, T); noise[:, ::400] += 1.5 * torch.randn(B, (T + 399) // 400)
logp_train = logp_roll + noise # trainer recompute, same weights
d = logp_train - logp_roll
w = torch.exp(d).clamp(max=cap).detach() # w_t = min(pi_theta / pi_roll, C)
print(f"mean|d|={d.abs().mean():.4f} k3 KL={(torch.exp(d) - 1 - d).mean():.5f} "
f"frac>cap={(torch.exp(d) > cap).float().mean():.5f} max w={w.max():.2f}")
print("sequence log-ratios:", [round(x, 2) for x in d.sum(1).tolist()])
# Processed vs raw logprobs: returned logprobs must move with temperature
z = torch.tensor([2.0, 1.0, 0.0])
processed = lambda tau: torch.log_softmax(z / tau, -1)[0].item()
raw = lambda tau: torch.log_softmax(z, -1)[0].item()
for name, f in [("processed", processed), ("raw", raw)]:
gap = abs(f(0.6) - f(1.0))
print(f"{name:9s} logprob gap between tau=0.6 and 1.0: {gap:.3f} -> {'train' if gap > 1e-6 else 'eval-only'}")
Output: the clean episode passes but is flagged as unsafe to re-encode; the drifted one fails four checks; the weights stay within the cap while exact sequence log-ratios already spread over more than three nats at 2,000 tokens; raw log-probabilities do not move with temperature.
clean : [] | retok-unsafe: True
drifted: ['non-prefix at call 1', 'logprob length at call 1', 'positive logprob at call 1', 'template re-render differs from captured prompt (expected if non-prefix)']
mean|d|=0.0189 k3 KL=0.00335 frac>cap=0.00075 max w=2.00
sequence log-ratios: [-3.81, -1.47, -0.23, -1.17]
processed logprob gap between tau=0.6 and 1.0: 0.205 -> train
raw logprob gap between tau=0.6 and 1.0: 0.000 -> eval-only
Track per model and harness: non-prefix calls (zero unless rewriting is intended and masked), retokenization-unsafe completions, and the per-token ratio before the first weight update, which isolates numeric mismatch from staleness.
Mismatch is a production failure mode, not a rounding detail. He (2025) reported an RL run without importance weighting that collapsed with a loss spike while the same run with weighting held the sampler–trainer KL near 0.001, and a bitwise-consistent run held it at exactly zero. Every step should log the mean and maximum per-token log-ratio, the k3 mismatch KL, the fraction of tokens beyond the cap and the staleness histogram, ideally split by token-probability bucket. A slow upward KL trend that precedes a reward drop points to mismatch; a step change at a deploy points to a kernel, precision or engine-version change.
Remedies differ in cost. Token-level truncation is the near-free default for hybrid engine–trainer setups; sequence-level masking drops data but suits sequence-level rewards; staleness bounds discard old samples in asynchronous layouts; bitwise-consistent kernels remove the gap at a reported cost of about 9–12% rollout throughput (Bai and Shen 2026). Common bugs are capture bugs: log-probabilities computed before temperature, an off-by-one position shift between engine and trainer that looks like a large constant mismatch, trainer reference log-probabilities recomputed after the first optimizer step, and missing per-token log-probabilities for tokens generated across an in-flight weight update.
The Trajectory Data Model
A rollout becomes training data only after it is written down in a form that a trainer, a curation job and an engineer debugging a reward spike can all read. The trajectory data model is that form: what is stored per episode, per step and per token, which versions are pinned alongside it, and which fields are cheap enough to scan across millions of episodes versus heavy enough to load only at training time. 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: 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, which must not be scored alike (see Rollout Systems).
RLDS formalizes an episode as an ordered sequence of steps \((o_t, a_t, r_t, \gamma_t, \mathrm{last}_t, \mathrm{term}_t)\) with episode metadata. The two flags matter for value targets. For a final step that is terminal, the return ends there; for one that is last but not terminal, the target bootstraps from the value of the next state:
\[ G_t = r_t + \gamma\,G_{t+1}\quad (t < T), \qquad G_T = r_T + \gamma\,(1-\mathrm{term}_T)\,V(s_{T+1}), \]where step \(T\) is the one with \(\mathrm{last}_T = 1\).
For agents with outcome rewards, the analogous flag is a status \(s \in \{\text{scored}, \text{truncated}, \text{infra}\}\), and the estimator of a pass rate depends on it. Suppose a task's true success probability is \(p\) and an infrastructure failure occurs with probability \(q_1\) on episodes that would succeed and \(q_0\) on those that would fail. Counting failures as zero gives \(p(1-q_1)\); excluding them gives \(p(1-q_1)/\big(p(1-q_1) + (1-p)(1-q_0)\big)\). With \(p = 0.4\), \(q_1 = 0.05\), \(q_0 = 0.15\) these are 0.380 and 0.427: both are biased unless crashes are independent of outcome, which is why infra errors must be recorded separately and fixed or retried rather than silently scored.
The first function computes discounted return targets from RLDS-style flags: an episode that hit a time limit bootstraps from the value estimate of its last state, while a terminal one does not. The second part simulates outcome-reward agents whose infrastructure crashes are more likely on unsolved, harder tasks, and compares two ways of handling crashed episodes when estimating a pass rate: scoring them as zero, and excluding them. Neither recovers the true rate, which is the argument for a separate status field rather than a sentinel reward.
import numpy as np
def returns(rewards, is_last, is_terminal, values, gamma=0.99):
"""Discounted return targets for one episode. A last-but-not-terminal step bootstraps from V(s_T)."""
G = values[-1] if (is_last[-1] and not is_terminal[-1]) else 0.0
out = np.zeros(len(rewards))
for t in reversed(range(len(rewards))):
G = rewards[t] + gamma * G
out[t] = G
return out
r = [0.0, 0.0, 0.0]
print("terminal :", returns(r, [0, 0, 1], [0, 0, 1], values=[0.5, 0.5, 0.5, 0.8]).round(3))
print("time-cut :", returns(r, [0, 0, 1], [0, 0, 0], values=[0.5, 0.5, 0.5, 0.8]).round(3))
# Outcome-reward agents: status decides whether an episode is scored at all
rng = np.random.default_rng(0)
n, p_true = 4000, 0.40
solved = rng.random(n) < p_true
infra = rng.random(n) < np.where(solved, 0.05, 0.15) # crashes are likelier on hard, unsolved tasks
status = np.where(infra, "infra", "scored")
reward = np.where(status == "scored", solved.astype(float), np.nan)
print(f"true pass rate {p_true:.3f} | infra counted as 0: {np.nan_to_num(reward).mean():.3f}"
f" | infra excluded: {np.nanmean(reward):.3f} | infra share {infra.mean():.3f}")
Output: identical rewards give different targets depending on the terminal flag; with outcome-correlated crashes, both pass-rate estimates miss the true 0.400.
terminal : [0. 0. 0.]
time-cut : [0.776 0.784 0.792]
true pass rate 0.400 | infra counted as 0: 0.381 | infra excluded: 0.431 | infra share 0.116
In production the data model is the contract between four groups: the rollout fleet that writes it, the trainer that consumes token fields, curation jobs that filter episodes, and engineers who debug reward and stability problems. It is easiest to get right at write time and expensive to repair later, because episodes recorded without versions or status cannot be rescored.
The status field drives several decisions. Trainers drop infra-error episodes and, for group-based estimators, either drop or resample the affected group; truncated episodes get an explicit, versioned reward policy (zero, a length penalty, or exclusion) rather than whatever the verifier returns on a partial state. Dashboards report the status mix per environment, and the infra-error rate is an SLO in its own right because crashes correlate with task difficulty. Lossless recording has a storage cost, so practice is to keep raw records immutable and derive views (SFT exports, training batches, dashboards) from them, with retention set per level.
Episode, Step and Token Fields
Agent trajectories have three levels with 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 and are by far the largest.
| Level | Typical fields | Main consumers | Size driver |
|---|---|---|---|
| Episode | ids; environment, image, verifier, harness and model versions; sampler settings; reward and breakdown; status (scored, truncated, infra error); turns, tokens, time, cost | Curation, dashboards, batch packing, audits | Bytes to kilobytes; scales with number of episodes |
| Step | role, message, reasoning, tool calls, observations, timestamps, tool exit codes | Trace review, replay, SFT export, monitors | Observation size (logs, page snapshots, screenshots) |
| Token | prompt and completion token ids, sampler log-probabilities, loss mask (model tokens vs. tool tokens), optional routing or teacher states | Trainer (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. The Agent Trajectory Interchange Format (ATIF), in the v1.7 subset that NeMo Gym supports, carries an agent block (name, version, model, tool definitions), a list of steps (message, reasoning, tool calls, observation) and per-step metrics that can include token ids and log-probabilities. Strict validation, with explicit extra fields for extensions, keeps records from drifting apart across harnesses.
The three levels have different size laws. For \(N\) episodes of \(T\) turns and \(L\) tokens, episode records cost \(O(N)\) bytes, step records about \(N\,T\,(\bar s_{\text{msg}} + \bar s_{\text{obs}})\), and token records \(N L b\), where \(b\) is bytes per token. With a 4-byte id, a 4-byte log-probability and a 1-bit mask, \(b \approx 8\). Optional fields change \(b\) sharply: replaying mixture-of-experts routing stores \(k\) expert ids for each of \(L_{\text{moe}}\) layers, adding \(k\,L_{\text{moe}}\) bytes per token with one-byte ids (384 bytes for top-8 routing over 48 layers, 48 times the ids and log-probabilities), and distillation targets that keep the teacher's top-\(K\) log-probabilities add about \(8K\) bytes per token.
The token level defines the training objective directly. With completion ids \(y_{1:L}\), behavior log-probabilities \(\ell^{\text{roll}}_t\) and mask \(m_t\), every quantity the trainer needs is a function of these arrays and the current parameters: \(\rho_t = \exp(\log\pi_\theta(y_t\mid y_{<t}) - \ell^{\text{roll}}_t)\) and the masked token-mean loss over \(\{t : m_t = 1\}\). Step and episode fields never enter the gradient; they enter selection, weighting and debugging.
The script builds the three levels for one synthetic 12-turn coding episode: an episode row with identity, versions, status and reward; step records with reasoning, tool calls and observations; and token arrays with ids, behavior log-probabilities and a loss mask. It reports the serialized size of each level, exports chat messages for supervised fine-tuning from the step level, and estimates the extra cost of storing mixture-of-experts routing decisions per token, an optional field used to replay expert choices during training.
import json, numpy as np
rng = np.random.default_rng(0)
steps = [] # step level: what a reviewer or SFT export reads
for t in range(12):
steps.append({"role": "assistant", "reasoning": "check the failing test " * 8,
"tool_call": {"name": "bash", "args": {"cmd": f"pytest -k case{t}"}}})
steps.append({"role": "tool", "observation": "E AssertionError\n" * 40, "exit_code": 1})
L = 30_000 # token level: the trainer's view
tokens = {"ids": rng.integers(0, 151_000, L, dtype=np.int32),
"logprobs": np.log(rng.uniform(0.05, 1, L)).astype(np.float32),
"loss_mask": rng.random(L) < 0.3} # model tokens trained, tool tokens masked
episode = {"episode_id": "ep-000123", "task_id": "repo-417/issue-88", "env": "swe-sandbox",
"env_version": "2.1.0", "verifier_version": "v7", "harness_version": "h3",
"policy_step": 412, "status": "scored", "reward": 1.0, "turns": 12,
"tokens": L, "tool_errors": 11, "payload_uri": "s3://traj/ep-000123.npz"}
size = {"episode": len(json.dumps(episode)), "step": len(json.dumps(steps)),
"token": sum(a.nbytes for a in tokens.values())}
print({k: f"{v/1024:.1f} KiB" for k, v in size.items()})
sft = [{"role": s["role"], "content": json.dumps(s.get("tool_call") or s.get("observation"))} for s in steps]
print("SFT messages from step level:", len(sft), "| trained tokens:", int(tokens["loss_mask"].sum()))
# Optional MoE routing replay: top-k expert ids per MoE layer per token (uint8 ids)
layers, k = 48, 8
print(f"routing states add {layers * k} B/token = {layers * k * L / 2**20:.1f} MiB for this episode")
Output: each level is roughly one to two orders of magnitude larger than the one above it, and routing states alone would exceed the rest of the record.
{'episode': '0.3 KiB', 'step': '13.4 KiB', 'token': '263.7 KiB'}
SFT messages from step level: 24 | trained tokens: 8992
routing states add 384 B/token = 11.0 MiB for this episode
Each level gets its own storage and retention policy. Episode rows go to a columnar table partitioned by run and policy step, kept indefinitely because they are small and answer most questions. Step records go to compressed JSON or a typed interchange format such as ATIF, kept long enough for trace review and SFT exports; screenshots and page snapshots dominate their size in computer-use environments and belong in object storage referenced by URI. Token payloads are kept until consumed by training plus an audit window.
Schema discipline matters more than format. Strict validation with explicit extension fields, as in ATIF, prevents each harness from inventing its own field names. Typical failure modes are a token payload whose length disagrees with its mask, step records that store parsed tool calls but not the raw completion, observations that contain credentials or personal data (redact at write time, at the step level, before anything is indexed), and optional fields such as teacher log-probabilities or routing states that are enabled without a storage estimate and silently multiply the payload.
Light Metadata, Heavy Tokens
The most useful physical design choice is to split each rollout into a small metadata record and a large per-token payload that is loaded only when a trainer consumes it. The DeepSeek-V4 report (2026) describes exactly this decomposition for its RL infrastructure:
- Metadata for an entire rollout set is loaded up front to plan global shuffling and sequence packing; heavy per-token fields go through a shared-memory loader and are freed after each mini-batch.
- A token-granular write-ahead log lets a preempted rollout resume where it stopped; regenerating from scratch would bias data toward short responses, which finish uninterrupted more often.
- Its sandbox platform, DSec, keeps a globally ordered trajectory log per sandbox, which makes tool execution part of the record and supports replay.
A back-of-the-envelope size check shows why. INTELLECT-3 (Prime Intellect, 2025) reports RL steps of 256 prompts with 16 rollouts each and a 65,536-token context limit. That is 4,096 rollouts and, at the limit, about 268 million tokens per step; a 4-byte token id plus a 4-byte log-probability per token gives a ceiling near 2 GB per step before any text or screenshots. Token payloads therefore belong in blob or columnar storage keyed by episode id, while the metadata table stays small enough to query interactively.
The storage ceiling for one RL step is \(P \cdot G \cdot L_{\max} \cdot b\) for \(P\) prompts, \(G\) rollouts per prompt, context limit \(L_{\max}\) and \(b\) bytes per token. For the INTELLECT-3 configuration, \(256 \cdot 16 \cdot 65{,}536 \cdot 8 \approx 2.1\times10^{9}\) bytes. The metadata row is a few hundred bytes per episode, so planning from metadata alone reads about three orders of magnitude less data than loading payloads at the context limit.
Planning is a bin-packing problem: sequence lengths \(L_i\) must be assigned to rows of capacity \(C\) to minimize the number of rows, with utilization \(\sum_i L_i / (R\,C)\) for \(R\) rows. First-fit decreasing is a standard heuristic with a classical worst-case guarantee of at most \(\tfrac{11}{9}\mathrm{OPT} + \tfrac{6}{9}\) rows, and it needs only the lengths.
The write-ahead log removes a length bias. If preemptions arrive as a Poisson process with rate \(\lambda\) and decoding runs at \(r\) tokens per second, a response of length \(L\) finishes uninterrupted with probability \(e^{-\lambda L / r}\). Regenerating from scratch keeps the first uninterrupted sample, so kept lengths follow the tilted density \(f(L)\,e^{-\lambda L/r} / Z\) instead of \(f(L)\); resuming from the log keeps \(f\).
The script writes each episode's heavy fields (token ids and log-probabilities) to its own blob file and its light fields (id, length, reward, blob URI) to a structured array. A global shuffle and a first-fit-decreasing packing plan are computed from the metadata alone; payloads are then loaded one packed row at a time and released. The last two parts compute the per-step payload ceiling for an INTELLECT-3-shaped step and simulate the length bias of restarting preempted generations from scratch.
import os, tempfile, numpy as np
rng = np.random.default_rng(0)
root = tempfile.mkdtemp()
N, CTX = 64, 16_384
lengths = np.minimum(rng.lognormal(8.0, 0.8, N).astype(int) + 200, CTX)
meta = np.zeros(N, dtype=[("episode", "i4"), ("tokens", "i4"), ("reward", "f4"), ("uri", "U64")])
for i, L in enumerate(lengths): # writer: heavy payload to a blob, light row to the table
uri = os.path.join(root, f"ep{i}.npz")
np.savez(uri, ids=rng.integers(0, 151_000, L, dtype=np.int32),
logprobs=np.log(rng.uniform(0.05, 1, L)).astype(np.float32))
meta[i] = (i, L, float(rng.random() < 0.4), uri)
def pack_plan(tokens, capacity):
"""First-fit decreasing over metadata only: bins of episode indices whose lengths sum <= capacity."""
bins, loads = [], []
for i in np.argsort(-tokens):
for b in range(len(bins)):
if loads[b] + tokens[i] <= capacity: bins[b].append(i); loads[b] += tokens[i]; break
else: bins.append([i]); loads.append(tokens[i])
return bins, np.array(loads)
order = rng.permutation(N) # global shuffle planned on metadata
bins, loads = pack_plan(meta["tokens"][order], CTX)
print(f"{N} episodes, {meta['tokens'].sum():,} tokens -> {len(bins)} packed rows, "
f"utilization {loads.sum() / (len(bins) * CTX):.3f} (lower bound {int(np.ceil(meta['tokens'].sum() / CTX))} rows)")
peak = 0
for b in bins[:4]: # trainer: load heavy fields per mini-batch, then free
batch = [np.load(meta["uri"][order[i]]) for i in b]
peak = max(peak, sum(x["ids"].nbytes + x["logprobs"].nbytes for x in batch))
del batch
print(f"metadata table {meta.nbytes / 1024:.1f} KiB | peak payload per packed row {peak / 1024:.1f} KiB")
# Ceiling for one INTELLECT-3-shaped step: 256 prompts x 16 rollouts x 65,536 tokens x (4 + 4) bytes
print(f"per-step token payload ceiling: {256 * 16 * 65_536 * 8 / 1e9:.2f} GB")
# Restart-from-scratch after preemption biases kept samples toward short responses
lam, rate = 1 / 600, 40.0 # preemptions per second, tokens per second
true_L = rng.lognormal(8.0, 0.8, 200_000)
survive = rng.random(true_L.size) < np.exp(-lam * true_L / rate)
print(f"mean length: all {true_L.mean():,.0f} | finished without preemption {true_L[survive].mean():,.0f}")
Output: packing reaches the lower bound on rows from metadata alone; the trainer holds one packed row of payload at a time; and restart-from-scratch shortens the mean kept response.
64 episodes, 274,407 tokens -> 17 packed rows, utilization 0.985 (lower bound 17 rows)
metadata table 16.8 KiB | peak payload per packed row 127.9 KiB
per-step token payload ceiling: 2.15 GB
mean length: all 4,121 | finished without preemption 3,607
The DeepSeek-V4 report describes the production form: rollout metadata loaded up front for shuffling and packing, heavy per-token fields served through a shared-memory loader and freed after each mini-batch, a token-granular write-ahead log for preempted rollouts, and a globally ordered trajectory log per sandbox. The general design is an object store for payloads keyed by episode id and a columnar metadata table that curation, dashboards and the batch planner query.
Write ordering prevents most failures. The payload is written and checksummed first and the metadata row committed last, so the table never points to a missing blob; orphaned payloads from crashed writers are garbage-collected by a periodic sweep. Loader bandwidth is a capacity question: at the ceiling above, a step reads gigabytes of payload, which must arrive within the step's data-loading budget. Monitored quantities are packing utilization, loader stall time, the fraction of metadata rows whose blob is missing or fails its checksum, and the length distribution of resumed versus uninterrupted rollouts, which should match if resumption is unbiased.
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, and the record must 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 because internet-hosted dependencies had changed, and 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")
Write the expected reward of an episode as \(\mu(\theta, e)\), where \(\theta\) is the policy checkpoint and \(e\) bundles the pinned versions: task, image, verifier and harness. A comparison between two evaluations at \((\theta_0, e_0)\) and \((\theta_1, e_1)\) estimates
\[ \hat\Delta = \underbrace{\mu(\theta_1, e_1) - \mu(\theta_0, e_1)}_{\text{policy}} + \underbrace{\mu(\theta_0, e_1) - \mu(\theta_0, e_0)}_{\text{environment}} + \text{noise}, \]and only the first term is usually of interest. Two estimators isolate it. Restricting both sides to tasks whose pins are identical removes the environment term at the cost of sample size; with \(n\) episodes per side and pass rates \(\hat p_0, \hat p_1\), the standard error is \(\sqrt{\hat p_0(1-\hat p_0)/n + \hat p_1(1-\hat p_1)/n}\). A paired design evaluates the old checkpoint on the new environment to estimate the environment term directly.
The Terminal-Bench 2.1 release changed 28 of 89 tasks, 31% of the set, so an unrestricted comparison across that release mixes the two terms for almost a third of the tasks.
The script derives a comparability key by hashing the pinned versions of each record, simulates a benchmark release in which 30 of 100 tasks are revised and become easier, and compares a policy improvement of two points before and after the release. The naive difference of mean rewards mixes the policy gain with the environment change; restricting to records whose keys appear on both sides removes the environment change and leaves an estimate within sampling error of the true gain.
import hashlib, json, numpy as np
def pin_key(rec):
"""Comparability key: rewards are comparable only between episodes that share every pinned version."""
pins = {k: rec[k] for k in ("task_id", "env_version", "image_digest", "verifier_version", "harness_version")}
return hashlib.sha256(json.dumps(pins, sort_keys=True).encode()).hexdigest()[:12]
rng = np.random.default_rng(0)
tasks = [f"t{i:03d}" for i in range(100)]
revised = set(rng.choice(tasks, 30, replace=False)) # 30 tasks change in the new release
p_task = rng.uniform(0.1, 0.9, 100)
def run(policy_gain, version, k=8):
recs = []
for t, p in zip(tasks, p_task):
moved = version == "2.1" and t in revised
q = np.clip(p + policy_gain + (0.25 if moved else 0.0), 0, 1) # fixed dependency makes it easier
for _ in range(k):
recs.append({"task_id": t, "env_version": version if moved else "2.0", "image_digest": "sha256:ab",
"verifier_version": "v3", "harness_version": "h1", "reward": float(rng.random() < q)})
return recs
old, new = run(0.00, "2.0"), run(0.02, "2.1") # true policy gain: +0.02
naive = np.mean([r["reward"] for r in new]) - np.mean([r["reward"] for r in old])
common = {pin_key(r) for r in old} & {pin_key(r) for r in new}
pm = lambda rs: np.mean([r["reward"] for r in rs if pin_key(r) in common])
n = 8 * len(common); se = np.sqrt(pm(new) * (1 - pm(new)) / n + pm(old) * (1 - pm(old)) / n)
print(f"naive delta {naive:+.3f} | matched delta on {len(common)} tasks {pm(new) - pm(old):+.3f} (SE {se:.3f})"
f" | true policy gain +0.020")
print("example key:", pin_key(new[0]))
Output: the naive comparison overstates the gain about fivefold; the version-matched comparison is within about one standard error of the true +0.020.
naive delta +0.104 | matched delta on 70 tasks +0.041 (SE 0.030) | true policy gain +0.020
example key: 23b1fb5e8977
Pinning is cheap and its absence is expensive. Production records pin images by content digest rather than mutable tags, treat verifiers and harnesses as versioned artifacts with their own release notes, and also pin the tokenizer and chat-template revision, because a template change alters training data without touching the environment. Episode tables carry these fields as columns so that dashboards, curation and evaluations can group by them by default.
The common failure modes are floating dependencies (packages or web resources fetched at run time, the cause of nine of the Terminal-Bench 2.1 revisions), verifier hotfixes deployed in the middle of a run, and harness upgrades pulled in by a dependency update. Each shows up as a reward step change with no matching change in the policy. Operating rules follow: refuse writes without complete pins, annotate every environment release on reward dashboards, re-baseline the current checkpoint on a new environment version before comparing checkpoints across it, and keep old images available so that past results can be reproduced.
Curating Rollouts
Raw rollouts serve two consumers with different filters. The online RL update wants groups that carry gradient signal: tasks the policy sometimes solves and sometimes fails. Offline uses (fine-tuning, distillation, verifier training) 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.
Let each stored rollout be a record \(e = (x, \mathcal{E}, v, s, r)\): task \(x\), environment \(\mathcal{E}\), version tuple \(v\) (environment, verifier, harness, policy step), status \(s \in \{\text{scored}, \text{truncated}, \text{infra}\}\) and reward \(r\), defined only when \(s\) is scored. Curation is a pair of selection functions over these records.
- Online filter. A group \(\{e_1,\dots,e_G\}\) of one task enters the RL batch only if its scored rewards are not all equal, \(\operatorname{Var}(r_1,\dots,r_G) > 0\). Each record carries a mask \(m_i = \mathbb{1}[s_i = \text{scored}]\), and the gradient estimate is \(\hat g = \big(\sum_i m_i\big)^{-1} \sum_i m_i \hat A_i \nabla_\theta \log \pi_\theta(\tau_i)\).
- Offline selector. A map from the whole store to a dataset \(D\), with constraints such as a cap of \(c\) items per task and one item per distinct final state; failures stay in the store as candidates for verifier and reward-model data.
Both functions need \(s\) and \(v\): without them, a crashed sandbox is indistinguishable from a wrong answer, and pass rates measured under two verifier versions are averaged as if they were one quantity.
The sketch routes a batch of raw rollouts to both consumers. Episodes are grouped by task; infra errors are counted and masked, never scored as zero; every scored episode, success or failure, goes to the offline store; and only tasks whose scored rewards differ form RL groups. Task b (all pass) and task c (all fail plus two crashes) are therefore excluded from the update but kept for offline use.
from dataclasses import dataclass
from enum import Enum
from collections import defaultdict
class Status(Enum):
SCORED = "scored"; TRUNCATED = "truncated"; INFRA_ERROR = "infra"
@dataclass
class Ep:
task_id: str
status: Status
reward: float | None
def route(episodes):
"""Split raw rollouts into an RL batch (mixed-outcome groups) and an offline store."""
groups = defaultdict(list)
for e in episodes:
groups[e.task_id].append(e)
rl, offline, masked = [], [], 0
for task, eps in groups.items():
scored = [e for e in eps if e.status is Status.SCORED]
masked += len(eps) - len(scored) # infra errors: masked, never scored as 0
offline.extend(scored) # successes and failures both kept offline
if len({e.reward for e in scored}) > 1: # mixed outcomes carry gradient signal
rl.append(task)
return rl, offline, masked
S, I = Status.SCORED, Status.INFRA_ERROR
eps = ([Ep("a", S, 1.0)] * 4 + [Ep("a", S, 0.0)] * 4 + # mixed
[Ep("b", S, 1.0)] * 8 + # all pass
[Ep("c", S, 0.0)] * 6 + [Ep("c", I, None)] * 2 + # all fail + crashes
[Ep("d", S, 0.0)] * 7 + [Ep("d", S, 1.0)]) # mixed
rl, offline, masked = route(eps)
print("RL groups:", rl, "| offline episodes:", len(offline), "| masked:", masked)
Prints RL groups: ['a', 'd'] | offline episodes: 30 | masked: 2.
In a production pipeline the two consumers sit at different points. The online filter runs inside the rollout loop, at the moment a group completes and before it enters the trainer queue; it must be cheap and must use pass rates from the current policy. The offline selectors run as batch jobs over the trajectory store, usually nightly or per training phase, and can afford deduplication, judging and decontamination.
Three design rules follow. Every record is keyed by its version tuple, so pass rates and selections can be recomputed after a verifier fix. Filtering never deletes: a group dropped from the update is still written to the store. And the curation rules are themselves versioned, so a dataset can be traced to the rules that built it. The dashboards that matter are the share of groups dropped per environment, the masked share by reason, and store growth per training day.
Zero-Variance Groups and Pass-Rate Filtering
Group-relative methods such as GRPO learn nothing from a task whose sampled group is all successes or all failures, yet such groups cost full rollout compute. Filtering them out, and steering sampling toward tasks of intermediate pass rate, is the first and cheapest curation step.
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 (AIME 2024 average accuracy 42 to 50), and convergence took fewer steps despite the extra sampling.
Production systems combine an offline filter with an online one. INTELLECT-3 annotated datasets offline with a small Qwen3-4B model's solve rate to drop items that are too easy, then during training kept easy, normal and hard pools by observed solve rate, stopped resampling prompts with pass rate 1, and discarded rollouts from prompts the model always solved or always failed. 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.
For binary rewards and a task with pass rate \(p\), the group of \(G\) independent rollouts is uninformative with probability \(p^G + (1-p)^G\). If pool pass rates follow a distribution \(\pi\), the informative fraction is
\[ f_G = 1 - \mathbb{E}_{p\sim\pi}\big[\,p^G + (1-p)^G\,\big]. \]Filling a batch with \(B\) informative groups needs a geometric number of draws per group, so the expected number of tasks rolled out is \(B/f_G\) and the rollout cost is \(G\,B/f_G\). If half the pool is solved, \(f_G < 1/2\) for any \(G\) and each batch costs more than twice its nominal compute; retiring solved tasks raises \(f_G\) directly, while over-sampling only pays for the waste.
Group size acts mostly on rare successes. The chance of at least one success is \(1-(1-p)^G\): at \(p=0.05\) it is about 34% with \(G=8\) and 56% with \(G=16\), which argues for a per-tier \(G\).
For a sampler, the expected squared magnitude of the unnormalized group-relative signal is proportional to the Bernoulli variance \(p(1-p)\), maximal at \(p = 1/2\); sampling tasks with weight \(w_x \propto \hat p_x (1-\hat p_x)\) concentrates compute where groups are informative. The estimate itself is noisy: from \(k\) rollouts, \(\hat p = c/k\) has standard error \(\sqrt{p(1-p)/k}\), about 0.11 at \(k=8\), \(p=0.1\). A Beta posterior \(\mathrm{Beta}(1 + c, 1 + k - c)\) with exponential decay of old counts keeps the estimate both smoothed and fresh as the policy moves.
The script computes \(f_G\) for a skewed pool (40% nearly solved, 20% nearly hopeless, the rest spread over \((0,1)\)), shows the effect of retiring the extremes, checks the closed-form over-sampling cost against a simulation of DAPO-style dynamic sampling, and verifies the rare-success figures.
import numpy as np
def informative_frac(p, G):
"""f_G = 1 - E[p^G + (1-p)^G] over a pool of per-task pass rates p."""
p = np.asarray(p, dtype=float)
return 1.0 - np.mean(p**G + (1 - p)**G)
rng = np.random.default_rng(0)
pool = np.concatenate([np.full(400, 0.98), np.full(200, 0.01), rng.beta(2, 2, 400)])
for G in (4, 8, 16):
f = informative_frac(pool, G)
print(f"G={G:2d}: f_G={f:.3f} rollouts per informative group={G / f:5.1f}")
kept = pool[(pool > 0.05) & (pool < 0.95)] # retire solved / hopeless tasks
print(f"after retiring solved/hopeless tasks: f_8={informative_frac(kept, 8):.3f}")
def dynamic_batch(pool, B, G, rng): # DAPO: draw until B mixed groups
drawn, kept = 0, 0
while kept < B:
p = rng.choice(pool); drawn += 1
r = rng.random(G) < p
kept += 0 < r.sum() < G
return drawn
d = np.mean([dynamic_batch(pool, 64, 8, rng) for _ in range(200)])
print(f"simulated tasks drawn for 64 mixed groups at G=8: {d:.1f} (theory {64 / informative_frac(pool, 8):.1f})")
for G in (8, 16):
print(f"p=0.05, G={G}: P(at least one success) = {1 - 0.95**G:.2f}")
Output:
G= 4: f_G=0.330 rollouts per informative group= 12.1
G= 8: f_G=0.435 rollouts per informative group= 18.4
G=16: f_G=0.528 rollouts per informative group= 30.3
after retiring solved/hopeless tasks: f_8=0.906
simulated tasks drawn for 64 mixed groups at G=8: 147.0 (theory 147.0)
p=0.05, G=8: P(at least one success) = 0.34
p=0.05, G=16: P(at least one success) = 0.56
Larger groups raise \(f_G\) but cost more rollouts per useful group; removing the extremes of the pool is the cheaper lever.
Pass-rate filtering is implemented at two places with different owners. The offline pass, as in INTELLECT-3, runs a small model over the dataset once and stores solve rates as task metadata; it belongs to environment acceptance and is cheap. The online pass runs in the rollout loop: DAPO's dynamic sampling over-generates and discards uniform groups, and open trainers expose this as a configuration option with a cap on how many generation rounds may be spent filling one training batch. The cap matters: without it, a pool that has drifted toward all-pass stalls the trainer instead of failing loudly.
In asynchronous systems the pass rate that decides a group's fate was measured on a policy several steps old, and filtering adds latency because a step waits until enough mixed groups arrive. Systems keep \(\hat p\) per task, environment version and verifier version in the metadata table, update it from every completed group, and move tasks between easy, normal and hard pools on that estimate.
The filter also hides faults. A verifier that rejects a valid answer format turns solvable tasks into all-fail groups that are silently dropped; a hackable verifier produces all-pass groups that are dropped too, so the hack never shows up in the reward curve. Dashboards therefore track, per environment: the zero-variance share, generation rounds per training step, the pass-rate histogram, and the count of tasks retired as all-pass or all-fail, with alerts on sudden jumps. All-pass groups go to a hacking audit sample, not just to the bin.
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 and adjust 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, which the authors attribute 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.
Let an environment expose a difficulty parameter \(d\), and let \(p(d)\) be the current policy's pass rate at that difficulty, assumed decreasing in \(d\). A target pass rate \(p^\star\) (near \(1/2\), where \(p(1-p)\) and the informative-group probability \(1 - p^G - (1-p)^G\) peak) defines the operating point \(d^\star\) with \(p(d^\star) = p^\star\). The stochastic-approximation update
\[ d_{t+1} = d_t + \eta_t\,\big(\hat p_t - p^\star\big), \]with \(\hat p_t\) the batch pass rate, is a Robbins–Monro iteration that tracks \(d^\star\) as the policy improves and \(p(\cdot)\) shifts. Constant \(\eta\) trades tracking speed against jitter.
Without a knob, the same logic acts on sampling weights over tiers \(k\): \(w_k \propto n_k\,\hat p_k(1-\hat p_k)\), with \(n_k\) the tier size, or a bandit that rewards learning progress \(|\hat p_k(t) - \hat p_k(t - \Delta)|\). In both cases the controlled quantity is the same: the fraction of groups whose rewards differ.
A toy run makes the drift visible. A policy has scalar skill \(s\); a task of difficulty \(d\) is solved with probability \(\sigma(s - d)\); skill grows only with the number of mixed groups in each batch. A static pool tuned to the starting policy is compared with one environment whose difficulty knob is moved toward a 50% pass rate.
import numpy as np
sig = lambda x: 1 / (1 + np.exp(-x))
G, B, STEPS, LR = 8, 64, 300, 0.004
def run(adaptive, seed=0):
rng = np.random.default_rng(seed)
skill, d = 0.0, 0.0
static = rng.uniform(-1.0, 2.0, B) # fixed pool, tuned to the start
log = []
for t in range(STEPS):
diff = d + rng.normal(0, 0.5, B) if adaptive else static
wins = rng.binomial(G, sig(skill - diff))
mixed = (wins > 0) & (wins < G)
skill += LR * mixed.sum() # learning only from mixed groups
if adaptive: # move knob toward 50% pass rate
d += 0.5 * (wins.sum() / (B * G) - 0.5)
if t % 100 == 99:
log.append(f"{mixed.mean():.2f}")
return skill, log
for name, a in (("static pool", False), ("adaptive knob", True)):
skill, log = run(a)
print(f"{name:13s}: mixed-group share at steps 100/200/300 = {log}, final skill = {skill:.1f}")
Output:
static pool : mixed-group share at steps 100/200/300 = ['0.08', '0.02', '0.00'], final skill = 7.1
adaptive knob: mixed-group share at steps 100/200/300 = ['0.67', '0.64', '0.69'], final skill = 53.6
The static pool runs out of signal as every task becomes easy; the controlled environment keeps about two thirds of groups informative. Skill units are arbitrary.
A difficulty knob is only useful if difficulty is measured, not declared. Procedural environments such as those in RLVE-Gym expose generator parameters (input size, search depth, number of constraints or distractors) and adapt each environment's difficulty distribution from recent accuracy; the verifier must stay exact at every setting, because a checker that becomes approximate at high difficulty turns the curriculum into a reward-noise schedule.
Engineering choices: the controller state (current difficulty range, recent pass rates) is part of the training checkpoint, so a resumed run does not restart from easy tasks; each episode records the difficulty it was sampled at, so evaluation can stratify by it; and per-environment controllers are rate-limited so one environment cannot absorb the batch.
Typical failures are a knob that saturates (the generator's maximum difficulty is reached and the environment falls out of the useful band), a parameter that changes the kind of task rather than its hardness, and a curriculum that looks healthy on training pass rates while held-out scores stall. For environments without a knob, tiers are recomputed from the metadata table on a schedule, and the held-out evaluation set never moves with the curriculum.
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: how many copies of easy successes get in, and whose distribution the trajectories come from.
- Pan et al. (2024), in SWE-Gym, fine-tuned a 32B coder on 491 successful agent trajectories from stronger models and raised its SWE-bench Verified resolve rate 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%, so naive self-training did not yet help.
- Yang et al. (2025), in SWE-smith, kept only resolved trajectories from 17,906 expert attempts and 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, giving 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
Rejection-sampling fine-tuning maximizes the likelihood of accepted trajectories drawn from a sampling distribution \(q\):
\[ \max_\theta \; \mathbb{E}_{\tau\sim q}\big[R(\tau)\,\log \pi_\theta(\tau)\big], \qquad R(\tau)\in\{0,1\}. \]When \(q = \pi_\theta\) this has the same gradient as the policy-gradient objective with reward \(R\) and no baseline; when \(q\) is a stronger model or an older checkpoint it is off-policy imitation. Duplicates set the effective task weights: a task with pass rate \(p_x\) contributes about \(G p_x\) of \(G\) samples, so easy tasks dominate. A cap of \(c\) per task replaces that weight with \(\min(G p_x, c)\), flattening the task distribution.
Off-policy imitation trains on the teacher's state distribution. If the student errs with probability \(\epsilon\) per step in states the teacher visits, errors compound over a horizon \(T\) to a cost of order \(T^2\epsilon\), against \(T\epsilon\) when training covers the student's own states (Ross et al., 2011). On-policy distillation minimizes the reverse KL on student samples,
\[ \mathcal{L}(\theta) = \mathbb{E}_{y\sim\pi_\theta}\Big[\sum_t \log \pi_\theta(y_t\mid y_{<t}) - \log \pi_T(y_t\mid y_{<t})\Big], \]whose policy-gradient form gives each token the dense advantage \(A_t = -\big(\log \pi_\theta(y_t\mid y_{<t}) - \log \pi_T(y_t\mid y_{<t})\big)\) (Agarwal et al., 2024). Reverse KL is mode-seeking: the student is penalized for tokens the teacher finds unlikely, not for every teacher mode it omits.
Rejection-sampling selection over episode metadata: successes only, infra errors excluded, one trajectory per distinct final diff, shortest first, at most three per task.
import hashlib
from collections import defaultdict
from dataclasses import dataclass, field
from enum import Enum
class Status(Enum):
SCORED = "scored"; TRUNCATED = "truncated"; INFRA_ERROR = "infra"
@dataclass
class EpisodeMeta:
episode_id: str; task_id: str; env: str; env_version: str
status: Status; reward: float | None
reward_parts: dict = field(default_factory=dict); turns: int = 0; tokens: int = 0
def select_sft(episodes, cap_per_task=3):
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
S = Status.SCORED
mk = lambda i, task, r, st=S, turns=3, diff="a": EpisodeMeta(
f"e{i}", task, "crm", "1.0", st, r, {"final_diff": diff}, turns, 100)
eps = [mk(1, "t1", 1.0, turns=5, diff="a"), mk(2, "t1", 1.0, turns=3, diff="a"),
mk(3, "t1", 1.0, turns=4, diff="b"), mk(4, "t1", 1.0, turns=6, diff="c"),
mk(5, "t1", 1.0, turns=7, diff="d"), mk(6, "t1", 0.0),
mk(7, "t2", None, st=Status.INFRA_ERROR)]
print("SFT keep:", [e.episode_id for e in select_sft(eps)])
Prints SFT keep: ['e2', 'e3', 'e4']: the shorter of two identical diffs, then the next two distinct solutions, with the failure and the crash excluded.
On-policy distillation in miniature (PyTorch): the student samples its own tokens, a fixed teacher scores them, and the per-token negative reverse-KL estimate is the advantage of a policy-gradient step.
import torch
torch.manual_seed(0)
V, T, N = 50, 6, 512 # vocabulary, response length, samples
student = torch.randn(T, V, requires_grad=True)
teacher = torch.randn(T, V) * 2.0
opt = torch.optim.SGD([student], lr=2.0)
def exact_rkl(s, t): # KL(student || teacher), mean over positions
ps = torch.softmax(s, -1)
return (ps * (torch.log_softmax(s, -1) - torch.log_softmax(t, -1))).sum(-1).mean().item()
print(f"step 0: reverse KL {exact_rkl(student, teacher):.3f}")
for step in range(1, 31):
with torch.no_grad():
y = torch.distributions.Categorical(logits=student).sample((N,)) # (N, T)
idx = torch.arange(T)
logp_s = torch.log_softmax(student, -1)[idx, y]
logp_t = torch.log_softmax(teacher, -1)[idx, y]
adv = -(logp_s - logp_t).detach() # dense per-token advantage
loss = -(adv * logp_s).mean()
opt.zero_grad(); loss.backward(); opt.step()
if step % 10 == 0:
print(f"step {step}: reverse KL {exact_rkl(student, teacher):.3f}")
Prints reverse KL 3.060 at step 0, then 2.464, 1.698 and 1.342 at steps 10, 20 and 30.
A production rejection-sampling pipeline is a batch job over the trajectory store with five stages: select scored successes for a fixed environment and verifier version; deduplicate by a hash of the final state; cap per task; decontaminate against every evaluation set by task id and n-gram overlap; and record the selection rules and source checkpoints with the dataset. Teacher provenance is part of the record, since the terms of use of the model that produced the trajectories travel with the data.
In SWE-Gym, adding a model's own successes to stronger-model trajectories lowered a held-out score, which is the standing warning: a selection pipeline is validated by a held-out evaluation of the fine-tuned model, not by the acceptance rate of the filter.
On-policy distillation changes the serving shape. The student generates, as in RL, and the teacher runs only a prefill over the student's tokens to return log-probabilities, which is far cheaper per token than teacher generation. Teacher and student must share a tokenizer, or token-level scores need an alignment step. Reports such as DeepSeek-V4 use several domain-specialist teachers, so the router must send each student rollout to the right teacher pool. Monitors are the per-token reverse KL by domain and the student's held-out score. Because every student rollout is a training input, the store keeps student failures.
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, and 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:
- Advantages are normalized at the environment level rather than per question, which the authors argue reduces sensitivity to outliers in small groups.
- 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.
- Training over 10 synthesized environments with 1,078 tasks, with DAPO-style removal of all-pass and all-fail groups, 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, which only works if the record carries a status and a reason.
With environments \(e\) and per-question groups \(q\), GRPO normalizes within the group: \(\hat A_i = (r_i - \mu_q)/(\sigma_q + \varepsilon)\). For small \(G\) the group standard deviation \(\sigma_q\) is itself a noisy estimate, and a group whose rewards differ only by scoring jitter of size \(\delta\) is rescaled to advantages of order one regardless of \(\delta\). One environment-level alternative keeps the per-group centring but scales by a single spread for the environment,
\[ \hat A_i = \frac{r_i - \mu_{q(i)}}{\sigma_e + \varepsilon}, \qquad \sigma_e^2 = \frac{1}{N_e}\sum_{j \in e} m_j\,(r_j - \mu_{q(j)})^2, \]so jitter stays small when the environment has real reward differences elsewhere. Variants differ in detail; the principle is that the scale is estimated from many groups rather than one.
Masking enters the loss as a weight \(m_i \in \{0,1\}\): \(\mathcal{L} = -\big(\sum_i m_i |\tau_i|\big)^{-1}\sum_i m_i \sum_t \hat A_i \log \pi_\theta(a_{i,t}\mid h_{i,t})\), with \(\mu_q\) and \(\sigma_e\) computed over unmasked records only. Scoring a simulator error as \(r=0\) instead adds a term that pushes probability away from whatever actions preceded the error, so the policy learns to avoid the simulator's failure modes rather than the task's.
A retail-style environment with partial-credit reward: half the groups have real wins and losses, half are all-fail with scoring jitter of 0.01, and 10% of rollouts hit a simulated-user error flagged by a judge. The naive scheme scores errors as zero and normalizes per group; the alternative scales by one environment-wide spread and masks the errors.
import numpy as np
rng = np.random.default_rng(1)
G, Q, EPS = 4, 32, 1e-6
def per_question(r): # GRPO: mean/std within each group
return (r - r.mean(1, keepdims=True)) / (r.std(1, keepdims=True) + EPS)
def env_level(r, mask): # centre per group, scale by one env-wide std
x = np.where(mask, r, np.nan)
centred = x - np.nanmean(x, 1, keepdims=True)
return np.nan_to_num(centred / (np.nanstd(centred) + EPS)) # masked -> 0
real = (rng.random((Q // 2, G)) < 0.5).astype(float)
jitter = 0.2 + rng.normal(0, 0.01, (Q // 2, G))
r = np.vstack([real, jitter])
sim_err = rng.random((Q, G)) < 0.10 # simulated-user errors flagged by a judge
ok = ~sim_err
a_q = per_question(np.where(ok, r, 0.0)) # naive: errors scored 0, per-group std
a_e = env_level(r, ok) # env-level std, errors masked
half = slice(Q // 2, Q)
print(f"mean |A| on jitter-only groups: per-question {np.abs(a_q[half][ok[half]]).mean():.2f}, "
f"env-level {np.abs(a_e[half][ok[half]]).mean():.2f}")
print(f"advantage on simulator-error rollouts: naive {a_q[sim_err].mean():.2f}, masked {a_e[sim_err].mean():.2f}")
Output:
mean |A| on jitter-only groups: per-question 0.74, env-level 0.02
advantage on simulator-error rollouts: naive -1.40, masked 0.00
Per-group scaling turns noise into full-size advantages, and zero-scored simulator errors receive a strong negative signal the policy did not earn.
Multi-environment training is operated per environment. Each environment has its own dashboard row: batch share, reward mean and spread, zero-variance share, truncation rate, and masked share broken down by reason. The status vocabulary needs more than one error code: infra error, simulator error, verifier error and timeout are masked for different reasons and fixed by different teams.
Masking has a failure mode of its own. The judge that flags simulated-user errors, as in AutoForge, has a false-positive rate, and a judge that blames the simulator for confusion the agent caused hides real policy failures. Teams audit a labeled sample of flagged rollouts, cap the masked share per environment, and quarantine an environment whose infra or simulator error rate crosses a threshold rather than training through it.
Mixture weights are set from held-out evaluation, not training reward, since reward scales are not comparable across environments. That choice is consequential: Madan et al. (NeurIPS 2026) found the choice of training environment moved held-out pass@1 substantially at matched token budgets. Evaluations of simulated-user environments also fix and record the user model, because scores depend on it.
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 balanced between 1,318 successes and 1,318 failures; using it 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.
A trajectory verifier is a scorer \(s_\phi(\tau)\) trained to separate successes from failures. With balanced classes, the cross-entropy objective
\[ \mathcal{L}(\phi) = -\mathbb{E}\big[y \log \sigma(s_\phi(\tau)) + (1-y)\log(1-\sigma(s_\phi(\tau)))\big] \]cannot be minimized by predicting the majority class, and its ranking quality is summarized by the AUC, \(P\big(s_\phi(\tau^+) > s_\phi(\tau^-)\big)\). Pairs of a success and a failure on the same task give the Bradley–Terry form \(P(\tau^+ \succ \tau^-) = \sigma\big(s_\phi(\tau^+) - s_\phi(\tau^-)\big)\), with the failure as a hard negative.
At inference, best-of-\(K\) picks \(\arg\max_k s_\phi(\tau_k)\). Its success rate lies between pass@1 and the oracle ceiling
\[ \text{pass@}K = 1 - \mathbb{E}_x\big[(1-p_x)^K\big], \]reached only by a perfect ranker (Cobbe et al., 2021). The gap between the two measures how much of the policy's latent capability the verifier recovers, and it can only be trained from stored failures.
Simulated best-of-16 selection: tasks have skewed solve rates, the verifier score is \(\text{sep}\cdot\text{success} + \mathcal{N}(0,1)\), and the separation controls its AUC. The selected candidate's success rate is compared with pass@1 and the oracle pass@16.
import numpy as np
rng = np.random.default_rng(0)
TASKS, K = 5000, 16
p = rng.beta(0.4, 1.2, TASKS) # skewed per-task solve rates
ok = rng.random((TASKS, K)) < p[:, None] # which of K candidates succeed
def best_of_k(ok, sep, rng):
"""Verifier score = sep * success + N(0, 1); pick the highest-scoring candidate."""
score = sep * ok + rng.normal(0, 1, ok.shape)
return ok[np.arange(len(ok)), score.argmax(1)].mean()
def auc(sep, rng, n=200_000): # P(score of a success > score of a failure)
return np.mean(sep + rng.normal(0, 1, n) > rng.normal(0, 1, n))
print(f"pass@1 = {ok[:, 0].mean():.3f} oracle pass@16 = {ok.any(1).mean():.3f}")
for sep in (0.5, 1.0, 2.0, 4.0):
print(f"verifier AUC {auc(sep, rng):.2f}: best-of-16 success = {best_of_k(ok, sep, rng):.3f}")
Output:
pass@1 = 0.251 oracle pass@16 = 0.688
verifier AUC 0.64: best-of-16 success = 0.356
verifier AUC 0.76: best-of-16 success = 0.463
verifier AUC 0.92: best-of-16 success = 0.608
verifier AUC 1.00: best-of-16 success = 0.684
Keeping failures is a retention policy. Metadata rows (status, reason, reward parts, versions, policy step) are small and kept indefinitely; full payloads (token ids, log-probabilities, tool outputs, sandbox diffs) are tiered, hot for recent policy steps and compressed in object storage after that. Deletion, when needed for cost, samples within each environment and status rather than dropping failures wholesale.
The consumers of failures are concrete: verifier and reward-model training, which need balanced success and failure sets on the same tasks; on-policy distillation, which trains on student rollouts whatever their outcome; and reward-hacking audits, which search high-reward and failed trajectories for exploited checkers, as in METR's reports. Each needs the failure reason, so a failure stored without status is nearly useless.
Two governance points apply. Environments built on real user data or proprietary repositories carry their access and retention terms into the store, so payloads are tagged with their source. And verifiers trained on stored failures are themselves versioned and evaluated on held-out tasks, because a verifier that has seen the evaluation set's failures will overstate best-of-\(K\) gains.
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, so that three cases can be told apart quickly: the policy improved, the policy found a hole, or the environment changed.
Each finished episode emits a metadata record \(m=(e,v,s,r,\ell,z)\): environment \(e\), environment and verifier version \(v\), policy step \(s\), reward \(r\), length \(\ell\) and a status \(z\) (completed, truncated, infra failure). Every chart is an estimator over a slice of these records. The aggregate reward at step \(s\) is a mixture over environments,
\[ \bar r_s=\sum_{e} w_{e,s}\,\hat\mu_{e,s},\qquad \operatorname{SE}(\hat\mu_{e,s})=\sqrt{\mu_{e}(1-\mu_{e})/n_{e,s}}, \]with \(w_{e,s}\) the share of episodes drawn from \(e\). If one verifier breaks and its pass rate jumps from \(\mu_e\) to 1, the aggregate moves by only \(w_e(1-\mu_e)\): with 200 equally weighted environments at \(\mu_e=0.5\), that is 0.0025. The same break, measured in its own slice with \(n_e=256\) episodes, is a shift of \(0.5/0.031\approx16\) standard errors. Slicing is what makes a local failure visible.
The three explanations separate by comparing the policy's reward with the reward of a fixed reference (canary solutions or a frozen checkpoint) on the same environment version. An environment change moves both. Policy improvement and a newly found hole move only the policy's reward; telling those two apart requires evidence from the traces themselves.
The script below simulates one training step over 200 environments with 256 episodes each, then breaks one environment's verifier so that it passes every episode. It compares what the aggregate reward shows with a two-proportion z-test computed per environment, which is the group-by that an observability layer runs on every step.
import numpy as np
rng = np.random.default_rng(0)
E, n = 200, 256 # environments, episodes per environment per step
p = rng.uniform(0.2, 0.8, E) # true pass rate of each environment
def step(broken=None):
r = rng.binomial(n, p)
if broken is not None: # this environment's verifier now passes everything
r[broken] = n
return r / n
bad = 54
before, after = step(), step(broken=bad)
print(f"aggregate reward before {before.mean():.4f} after {after.mean():.4f}")
pool = (before + after) / 2 # two-proportion z-test per environment
z = (after - before) / np.sqrt(np.clip(2 * pool * (1 - pool) / n, 1e-6, None))
top = np.argsort(-np.abs(z))[:3]
print("broken env:", bad, "| top |z| envs:", top.tolist(), "z:", np.round(z[top], 1).tolist())
print("envs with |z| > 4:", int((np.abs(z) > 4).sum()))
Prints the aggregate before and after (0.5259 and 0.5268) and the per-environment test, which flags environment 54 with \(z=14.3\); the next largest is 2.4, and only one environment exceeds \(|z|>4\).
In production the observability layer is a column store of episode metadata, one row per episode and a few dozen fields, kept separate from the payload store of tokens, tool input and output, and sandbox logs. Metadata queries must answer in seconds over millions of episodes so that slicing by environment, version and step stays interactive; payloads are read only for sampled or flagged episodes.
- Mandatory attribution. Environment version, verifier version and image digest are written by the harness, not by the environment author, so no episode is unattributable.
- Infra failure is a status, not a zero reward. Dashboards and the loss both exclude it.
- Owners per environment. Alerts route to the team that owns the environment; at hundreds of environments a central team cannot triage everything.
- Quarantine as a mask. A bad window is excluded by version and time range, and can be re-included if the diagnosis was wrong.
The usual failure is alerting on the aggregate reward, which hides single-environment breaks; the second is slices of such high cardinality that queries become too slow for anyone to look.
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, plus readable transcripts for a sample of groups.
| Signal | What a change usually means | Slice by |
|---|---|---|
| Mean reward and pass-rate histogram | Learning, saturation, or a broken verifier (sudden jump or collapse) | Environment, version, difficulty tier |
| Fraction of zero-variance groups | Pool too easy or too hard for the current policy; wasted compute | Environment, task tier |
| Episode length and truncation rate | Shortcut (reward up, length down); looping or budgets too tight (length at cap) | Environment, outcome |
| Tool-error rate | Policy misusing tools, or a tool or API that changed | Tool name, environment version |
| Infra-failure rate | Sandbox, image or network trouble; must stay out of rewards | Image digest, cluster, region |
| Sampler vs. trainer log-prob gap | Engine mismatch or stale weights (see Capturing Trajectories) | Policy step, engine version |
| Monitor flag rate | Possible reward hacking; review flagged traces | Environment, monitor version |
Table. Core health signals for environment-based RL. Each is a group-by over episode metadata.
Each signal in the table is a statistic over episodes in a slice. With group size \(G\) and a task whose pass rate is \(p\), a group is uninformative when all rollouts agree, which has probability \(p^G+(1-p)^G\). Over the pool's distribution \(\mathcal D_e\) of pass rates the zero-variance fraction is
\[ Z_e=\mathbb E_{p\sim\mathcal D_e}\big[p^G+(1-p)^G\big]. \]With group-normalized advantages these groups contribute zero gradient, so \(1-Z_e\) is the share of rollout compute that carries signal; a rising \(Z_e\) means the pool has drifted too easy or too hard.
The sampler–trainer gap compares the sampling policy \(\mu\) with the trainer's \(\pi\) on tokens drawn from \(\mu\). With \(\rho_t=\pi(a_t\mid h_t)/\mu(a_t\mid h_t)\), two unbiased estimators of \(\mathrm{KL}(\mu\,\|\,\pi)\) are (Schulman 2020)
\[ k_1=-\log\rho_t,\qquad k_3=(\rho_t-1)-\log\rho_t\;\ge 0 , \]with \(k_3\) the lower-variance choice; \(\max_t|\log\rho_t|\) tracks the worst importance weight. Infra failures must be removed before averaging: counting a failure rate \(f\) as zero reward biases the pass rate to \((1-f)\,p\). A shortcut shows as reward and length moving in opposite directions within one environment, a correlation that the aggregate cannot show.
The script computes two of the dashboard's signals from raw episode data. It draws task pass rates from three Beta distributions, runs groups of eight rollouts and compares the observed zero-variance fraction with \(\mathbb E[p^G+(1-p)^G]\). It then perturbs per-token log-probabilities to imitate an inference–training engine mismatch and estimates the KL gap with the \(k_1\) and \(k_3\) estimators.
import numpy as np
rng = np.random.default_rng(1)
# 1) zero-variance groups: G rollouts per task, task pass rates p ~ Beta(a, b)
G, tasks = 8, 20000
for a, b in [(0.5, 0.5), (2, 2), (4, 1)]:
p = rng.beta(a, b, tasks)
wins = rng.binomial(G, p)
observed = np.mean((wins == 0) | (wins == G))
theory = np.mean(p**G + (1 - p)**G)
print(f"Beta({a},{b}): zero-variance fraction observed {observed:.3f} theory {theory:.3f}")
# 2) sampler vs trainer log-prob gap on sampled tokens
T = 200000
lp_s = np.log(rng.uniform(0.05, 1.0, T)) # sampler log-probs of the sampled tokens
for noise in [0.0, 0.02, 0.10]: # engine mismatch (std of per-token log-prob error)
lp_t = lp_s + rng.normal(-noise**2 / 2, noise, T)
logr = lp_t - lp_s # log(pi_train / pi_sampler)
k1 = np.mean(-logr) # unbiased for KL(sampler || trainer), high variance
k3 = np.mean(np.expm1(logr) - logr) # unbiased, always >= 0, low variance
print(f"noise {noise:.2f}: k1 {k1:+.5f} k3 {k3:.5f} max|logr| {np.abs(logr).max():.3f}")
Prints observed against theoretical zero-variance fractions (0.396 vs 0.395 for a polarized pool, 0.108 vs 0.110 for a balanced one) and KL estimates that track the true value \(\sigma^2/2\): about 0.0002 at noise 0.02 and 0.005 at noise 0.10.
A working dashboard has one panel per environment with the table's signals on a shared policy-step axis, plus a global panel for the sampler–trainer gap, staleness and cost. The Tinker RL logs are a useful template: per-environment reward, tokens sampled and discarded, KL estimates, cost and staleness, with readable transcripts for a sample of groups.
- Alerts on change, not level. Pass rates differ legitimately across environments; alerts fire on step-to-step shifts measured in standard errors of the slice.
- Mix effects. A curriculum that shifts sampling toward easier environments raises the aggregate reward while no environment improves. Mixture weights are charted beside the reward.
- Cost per environment. Sandbox-seconds and tokens per informative group expose environments that consume compute without signal.
- Log-probs at sampling time. The gap can only be measured if the sampler records per-token log-probs with the engine and weight version.
Typical failures are an infra outage that shows up as a reward collapse because failures were scored zero, and a version bump that silently merged two series.
Detecting Reward Hacking from Traces
Reward hacking leaves fingerprints in trajectories before it shows up in evaluations: rewards rise in one environment while episodes get shorter, tool calls touch test files or the grader, or reasoning discusses the scoring mechanism. Detection therefore runs over the trajectory store, combining metric anomalies with model-based monitors and human review of what they flag.
- 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.
- METR's MALT dataset (2025) labels 10,919 agent transcripts for reward hacking and sandbagging. The best prompted monitors reached an AUROC of 0.96 for reward hacking, though natural examples were few.
- Baker et al. (2025) showed that a weaker model reading a reasoning model's chain of thought detects hacking in agentic coding environments far better than one reading only actions. Putting that monitor into the reward taught the policy to hide its intent while still hacking, so monitors belong in detection and environment repair, not in the reward.
- Anthropic (2025) reported that a model that learned hacks such as exiting the test harness with a success code, in programming environments drawn from real Claude training runs, also became more misaligned on unrelated evaluations.
A monitor is a classifier with score \(m(\tau)\) and threshold \(c\). Its ranking quality is the AUROC, but what decides how useful it is in review is precision at the operating point, which depends on the base rate \(\pi\) of hacking:
\[ \text{precision}=\frac{\mathrm{TPR}\,\pi}{\mathrm{TPR}\,\pi+\mathrm{FPR}\,(1-\pi)} . \]An AUROC of 0.96, the best prompted-monitor result on MALT, can still give low precision when hacks are rare, which is why monitors narrow human review rather than replace it. Under a review budget that reads the top fraction \(q\) of episodes, the number of hacks found is \(\mathrm{TPR}(c_q)\,\pi N\).
Putting the monitor into the reward, \(R'(\tau)=R(\tau)-\lambda\,m(\tau)\), changes what the policy optimizes. Hacks that the monitor catches lose \(\lambda m\); hacks it misses keep their full reward. The gradient therefore moves probability toward undetected hacks, and the monitor's recall falls exactly where it is relied on, the outcome Baker et al. (2025) observed. Trace fingerprints are simple statistics: within an environment, a positive reward trend together with a negative length trend, or a rising rate of tool calls whose arguments reference test or grader paths.
The script holds a monitor's score distributions fixed (hacking episodes score two and a half standard deviations higher) and varies only the base rate of hacking. For each base rate it computes the AUROC with the rank-sum formula and the precision and recall when reviewers read the top 1% of episodes by monitor score.
import numpy as np
rng = np.random.default_rng(2)
N = 200000
for base in [0.20, 0.02, 0.002]: # fraction of episodes that hack
y = rng.random(N) < base
s = np.where(y, rng.normal(2.5, 1, N), rng.normal(0, 1, N)) # monitor score
order = np.argsort(s); ranks = np.empty(N); ranks[order] = np.arange(1, N + 1)
auroc = (ranks[y].sum() - y.sum() * (y.sum() + 1) / 2) / (y.sum() * (~y).sum())
thr = np.quantile(s, 0.99) # review budget: top 1% of episodes
flag = s > thr
ppv, tpr = y[flag].mean(), flag[y].mean()
print(f"base rate {base:.3f}: AUROC {auroc:.3f} precision@top1% {ppv:.2f} recall {tpr:.2f}")
Prints an AUROC near 0.96 at every base rate, while precision in the reviewed top 1% falls from 1.00 at a 20% base rate to 0.75 at 2% and 0.11 at 0.2%.
Detection runs as asynchronous jobs over the trajectory store, never on the training critical path. A typical pipeline has three stages: cheap metric anomalies per environment and version; an LLM monitor with a versioned prompt over a sample plus every anomalous slice, reading chain of thought where the model exposes it; and a human review queue for what the monitor flags.
- Labels feed back. Reviewer labels form a growing set, in the style of METR's MALT, for measuring each monitor version's recall on natural examples.
- Actions are on the environment. A confirmed hack leads to a verifier or environment fix, a version bump and quarantine of affected episodes; the monitor stays out of the reward.
- Cost control. Monitoring every transcript with a strong model can rival sampling cost, so monitors run on samples and anomalies.
Failure modes include reviewer fatigue from false positives, which METR (2025) found high for both detectors; monitors prompted on catalogued hacks that miss new ones; and treating caught hacks as local. Anthropic's 2025 finding that learned hacks generalized to broader misalignment is the reason they are fixed promptly.
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: did the agent do something clever, or did the environment hand 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%, an environment bug that would otherwise read as a capability limit.
An episode is a deterministic function of its inputs once all randomness is pinned. Write the environment as \(s_{t+1}=f(s_t,a_t;\xi_t)\) and the observation as \(o_t=g(s_t)\), with \(\xi_t\) external randomness (network responses, clocks, random seeds). Exact replay requires the initial state \(s_0\) (image digest and task seed), the exogenous inputs \(\xi_{0:T}\) (recorded tool outputs) and the actions \(a_{0:T}\) (recorded sampled tokens). Re-sampling the actions instead requires batch-invariant inference, so most replay systems force-decode the recorded tokens.
If the sandbox logs a state digest \(h_t=H(s_t)\) after each step, a replay with the same actions localizes a defect at the first divergence \(t^\ast=\min\{t: h'_t\neq h_t\}\); because the actions are identical, the divergence is in the environment. Replay also measures how much of a score is environment error. In Transluce's Docent analysis, fixing missing packages raised GPT-4o's InterCode solve rate from 68.6% to 78%, so 9.4 points of the original gap measured the environment rather than the model.
The script implements record and replay for a toy sandbox whose package-install output depends on a mirror. Recording stores each action, its output and a digest of the sandbox state. Replay feeds the same actions into a fresh sandbox and reports the first step where output or digest differs, here caused by a mirror that moved between recording and replay.
import hashlib, json
class FileEnv:
"""Toy sandbox: a dict filesystem; 'pip' output depends on a mirror unless pinned."""
def __init__(self, seed, pinned=True, mirror_version="1.4.2"):
self.seed, self.fs = seed, {"tests.py": "assert solve(2)==4"}
self.pinned, self.mirror = pinned, mirror_version
def step(self, action):
cmd, arg = action
if cmd == "write": self.fs[arg[0]] = arg[1]; out = "ok"
elif cmd == "pip": out = f"installed {arg}=={'1.4.2' if self.pinned else self.mirror}"
elif cmd == "run": out = "PASS" if "x*2" in self.fs.get("sol.py", "") else "FAIL"
self.fs["_log"] = self.fs.get("_log", "") + out
return out
def digest(self):
return hashlib.sha256(json.dumps(self.fs, sort_keys=True).encode()).hexdigest()[:12]
def record(env, actions):
return [(a, env.step(a), env.digest()) for a in actions]
def replay(env, trace):
for t, (a, out, h) in enumerate(trace):
o2 = env.step(a)
if (o2, env.digest()) != (out, h):
return t, out, o2
return None
actions = [("pip", "numpy"), ("write", ("sol.py", "def solve(x): return x*2")), ("run", None)]
trace = record(FileEnv(seed=7, pinned=False, mirror_version="1.4.2"), actions)
print("recorded:", [o for _, o, _ in trace], "final", trace[-1][2])
print("replay, same mirror :", replay(FileEnv(7, pinned=False, mirror_version="1.4.2"), trace))
print("replay, mirror moved:", replay(FileEnv(7, pinned=False, mirror_version="1.5.0"), trace))
Prints the recorded outputs, None for a faithful replay, and (0, 'installed numpy==1.4.2', 'installed numpy==1.5.0') when the mirror has moved: the divergence is at step 0 and lies in the environment.
Replay is a storage and retention decision taken before anything breaks. Each episode record needs the image digest, task seed, environment and verifier versions, the ordered command and tool log with outputs, the sampled tokens with log-probs, and the engine and weight version. DeepSeek-V4's DSec keeps a per-sandbox ordered trajectory log for this purpose (DeepSeek-AI 2026).
- Replay service. Boots the recorded image by digest, restores the task, feeds recorded actions and diffs outputs step by step; forking at step \(t\) with a fixed environment or another policy turns it into a counterfactual tool.
- Retention. Images referenced by episodes must not be garbage-collected from the registry while the episodes may be debugged.
- Redaction. Tool logs can contain credentials and must be scrubbed before analysts read them.
Common causes of unreplayable episodes are live web calls, wall-clock time and unseeded randomness inside tasks. At scale, transcript-analysis tools such as Docent cluster thousands of traces so that environment bugs surface before they are read as capability limits.
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, and 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.
Drift is a change in the environment's transition function \(f\) or verifier during a run. A canary is a reference solution whose pass probability \(q\) should be constant and near one. To detect a fall from \(q_0\) to \(q_1\), the Bernoulli CUSUM accumulates the log-likelihood ratio of each canary result \(x_t\in\{0,1\}\),
\[ S_t=\max\Big(0,\;S_{t-1}+x_t\log\tfrac{q_1}{q_0}+(1-x_t)\log\tfrac{1-q_1}{1-q_0}\Big), \]and alarms when \(S_t>h\). The threshold \(h\) trades detection delay against false alarms on healthy streams. Flaky canaries (\(q_0\) well below one) make that trade worse, which is the reason to pin dependencies before monitoring them.
Version-on-change makes attribution a difference of differences. If a version bump changes the policy's mean reward by \(\Delta_\pi\) and the canaries' by \(\Delta_{\text{ref}}\), the change attributable to the policy is about \(\Delta_\pi-\Delta_{\text{ref}}\), and a non-zero \(\Delta_{\text{ref}}\) is direct evidence of drift.
The script simulates a canary that passes 98% of the time until run 300, when an upstream change drops it to 70%. It runs a Bernoulli CUSUM with threshold \(h=9\) and reports the detection delay, then estimates the false-alarm probability by running the same detector on 2,000 healthy streams of 300 canary runs.
import numpy as np
rng = np.random.default_rng(3)
q0, q1, t0, T = 0.98, 0.70, 300, 600 # canary pass prob before/after drift at run t0
x = np.r_[rng.random(t0) < q0, rng.random(T - t0) < q1].astype(float)
# Bernoulli CUSUM on failures: log-likelihood ratio of "drifted" vs "healthy"
f = 1 - x
llr = f * np.log((1 - q1) / (1 - q0)) + (1 - f) * np.log(q1 / q0)
h, S, alarm = 9.0, 0.0, None
for t, l in enumerate(llr):
S = max(0.0, S + l)
if S > h: alarm = t; break
print(f"drift at run {t0}, CUSUM alarm at run {alarm} (delay {alarm - t0})")
# false alarms on healthy data only, over many simulated streams
fa = 0
for _ in range(2000):
S = 0.0
for l in np.where(rng.random(t0) < q0, np.log(q1 / q0), np.log((1 - q1) / (1 - q0))):
S = max(0.0, S + l)
if S > h: fa += 1; break
print(f"healthy streams of {t0} runs that raise a false alarm: {fa / 2000:.3f}")
Prints an alarm at run 317, a delay of 17 canary runs, and a false-alarm probability of 0.003 over 300 healthy runs; with \(h=5\) the delay is shorter but about a quarter of healthy streams alarm.
Containing drift is mostly build hygiene. Images reference dependencies by digest and lockfile, not by tag; wheels and packages are vendored or served from an internal mirror; web tasks run against snapshots or self-hosted replicas; simulated users pin model version, prompt and sampling parameters; third-party APIs are replaced by recorded or mocked services unless the task requires them live.
- Canary schedule. Every environment version gets reference solutions run on a timer and after every image rebuild; failures page the environment owner.
- Versioning. Any fix, rebuild or upstream change bumps the recorded version, so dashboards split and curation can drop the affected window.
- Audits. The Terminal-Bench 2.1 notes trace the largest per-task score changes to drift, resource mismatches and misspecification, a pattern that also holds for training pools.
The characteristic failure is a slow drift, such as a mirror updating one package, that lowers reward gradually and is read as a learning plateau.
Train/Eval Separation
The same environment machinery that produces training data also produces benchmark scores, which makes leakage between the two easy and its effects hard to see. Train/eval separation means keeping evaluation tasks, their solutions and close variants out of every training store, and measuring generalization at a distance that matches the claim being made: new tasks, new environments or entirely new families of environments.
Let \(\mathcal E\) be an evaluation set and \(\mathcal D\) the union of every training store. If a fraction \(c\) of evaluation items is leaked into \(\mathcal D\), the observed score is a mixture
\[ \hat s=(1-c)\,s_{\text{clean}}+c\,s_{\text{leak}},\qquad \hat s-s_{\text{clean}}=c\,(s_{\text{leak}}-s_{\text{clean}}), \]so a small leak with near-perfect recall on leaked items moves the headline score by almost \(c\). Separation also has a distance. Index evaluation splits by \(d\in\{\text{task},\text{environment},\text{family},\text{time}\}\); each gives a score \(s_d\), and the claim a result supports is limited by the largest \(d\) at which it was measured.
The first mechanical defense is a registry: normalized hashes of evaluation tasks, repositories and reference patches, plus a canary string embedded in every evaluation asset. The script builds such a registry and checks a small training store against it before a run, blocking any example whose task text, repository or content matches.
import hashlib, re
def norm(s): # normalize before hashing: lowercase, collapse whitespace, strip punctuation
return re.sub(r"\s+", " ", re.sub(r"[^\w\s]", "", s.lower())).strip()
def h(s): return hashlib.sha256(norm(s).encode()).hexdigest()
CANARY = "EVAL-CANARY-7f3c2a9e" # unique string embedded in every eval asset
eval_items = {"task": ["Fix the off-by-one error in paginate() so the last page is returned."],
"repo": ["github.com/acme/pager"],
"patch": ["- return items[start:end-1]\n+ return items[start:end]"]}
registry = {(k, h(v)) for k, vs in eval_items.items() for v in vs}
train_store = [
{"task": "Fix the off-by-one error in paginate() so the LAST page is returned!", "repo": "github.com/acme/pager"},
{"task": "Add retry logic to fetch_user().", "repo": "github.com/other/users"},
{"task": "Implement CSV export. " + CANARY, "repo": "github.com/third/export"},
]
for i, ex in enumerate(train_store):
hits = [k for k, v in ex.items() if (k, h(v)) in registry]
if CANARY in " ".join(ex.values()): hits.append("canary")
print(i, "BLOCK" if hits else "ok", hits)
Prints BLOCK ['task', 'repo'] for a reformatted copy of the evaluation task, ok for an unrelated task and BLOCK ['canary'] for an example that carries the canary string.
Separation is an organizational property enforced by tooling. Evaluation sets are owned by a team distinct from those building training environments, stored with access controls, and registered (task hashes, repositories, solutions, canaries, creation dates) in a service that every data and environment pipeline queries. A training run cannot start until its stores pass the registry check, and the check's result is recorded with the run.
The hard cases are indirect: an environment generator trained or prompted on benchmark items, a mined pool drawn from the same repositories as an evaluation set, a simulated user that has seen evaluation dialogues. Lineage metadata answers these, which is why generator, source repository and template are recorded for every environment. OpenAI (2026) moved toward privately authored evaluations for this reason.
How Contamination Enters
Contamination enters through pretraining crawls of public benchmarks, through mined training environments drawn from the same repositories as evaluation sets, and through synthesized tasks that paraphrase benchmark items. The SWE-bench line shows all three risks:
- OpenAI (February 2026) stopped reporting SWE-bench Verified. Auditing 138 problems that o3 did not solve consistently, it found material test or specification problems in 59.4%, and it 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.
- 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.
- 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 a registry of hashed evaluation tasks, repositories and reference solutions checked against every training store before a run; canary strings in evaluation assets; and time cutoffs so evaluation tasks postdate training data.
Detection operates at three granularities. Exact matching hashes normalized text and catches copies. Near-duplicate matching compares sets of word \(n\)-gram shingles \(S(x)\) by Jaccard similarity \(J(x,y)=|S(x)\cap S(y)|/|S(x)\cup S(y)|\). MinHash estimates it cheaply: for a random hash \(h\), \(\Pr[\min h(S(x))=\min h(S(y))]=J(x,y)\) (Broder 1997). Locality-sensitive hashing splits \(K=br\) MinHash values into \(b\) bands of \(r\) rows; a pair becomes a candidate with probability
\[ P(s)=1-(1-s^{r})^{b}, \]an S-curve with threshold near \((1/b)^{1/r}\). Paraphrases lower \(J\) and can escape text matching entirely, so the third granularity is provenance: repository, commit and reference-solution keys, and a time cutoff \(t_{\text{task}}>t_{\text{train}}\) for tasks that postdate all training data.
The script implements MinHash over 5-word shingles with 128 hash functions and compares a benchmark issue text with a verbatim copy, a light paraphrase, a new bug from the same repository and an unrelated task. It then prints the LSH candidate probability for 32 bands of 4 rows at three similarity levels.
import numpy as np, re, zlib
def shingles(s, n=5):
w = re.findall(r"\w+", s.lower())
return {" ".join(w[i:i + n]) for i in range(len(w) - n + 1)}
K = 128
rng = np.random.default_rng(4)
A, B, P = rng.integers(1, 2**31 - 1, K), rng.integers(0, 2**31 - 1, K), 2**31 - 1
def sig(s):
x = np.array([zlib.crc32(g.encode()) for g in shingles(s)], dtype=np.int64)
return ((A[:, None] * x[None, :] + B[:, None]) % P).min(axis=1)
def jaccard(a, b): sa, sb = shingles(a), shingles(b); return len(sa & sb) / len(sa | sb)
bench = ("The function paginate returns a list of items for the requested page but it drops "
"the final element of the last page when the number of items is not a multiple of the page size")
cands = {
"verbatim copy": bench,
"light paraphrase": bench.replace("drops", "omits").replace("requested", "given"),
"same repo, new bug": "The function paginate raises an error when the page size is zero instead of returning an empty list for the caller",
"unrelated": "Add exponential backoff and jitter to the HTTP client so retries do not synchronize across workers in the pool",
}
sb = sig(bench)
for name, c in cands.items():
print(f"{name:20s} Jaccard {jaccard(bench, c):.2f} MinHash est {np.mean(sig(c) == sb):.2f}")
# LSH: b bands of r rows; probability a pair with similarity s becomes a candidate
b, r = 32, 4
for s in [0.2, 0.5, 0.8]:
print(f"s={s}: P(candidate) = {1 - (1 - s**r)**b:.3f}")
Prints exact Jaccard and MinHash estimates (1.00/1.00 for the copy, 0.55/0.48 for the paraphrase, 0.00 for the other two) and candidate probabilities of 0.050, 0.873 and 1.000 at similarity 0.2, 0.5 and 0.8. The same-repository task is invisible to text matching and needs a repository key.
Production decontamination runs at the scale of the training corpus and the environment pool. Code is normalized (whitespace, comments, identifiers where appropriate) before shingling; LSH indices over training stores are rebuilt with each data release; and matches are reviewed in batches, since aggressive thresholds also remove legitimate training data.
- Provenance blocking. Mined environments exclude evaluation repositories by name, as SWE-Gym did by drawing from 11 disjoint repositories (Pan et al. 2024).
- Fresh tasks. Pipelines such as SWE-rebench collect tasks continuously, so evaluation can use items created after a model's data cutoff.
- Memorization probes. Asking a model to reproduce gold patches or problem details, as in OpenAI's SWE-bench Verified audit, tests leakage through pretraining that no training-store check can see.
Canary strings only help if crawlers and data filters honor them, so they complement registries rather than replace them.
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.
Wang et al. (2026) illustrate the strongest version of this split. Agent World Model trained only on synthetic SQL-backed environments (an RL subset of 3,315 tasks across 526 environments) and evaluated on τ²-bench, BFCLv3 and MCP-Universe, none of which its environments were built to imitate. The authors report strong out-of-distribution transfer and state what their environments omit (conversation, refusals, browsing, retrieval), which bounds the claim.
| Split | What it measures | Main risk |
|---|---|---|
| Held-out tasks, same environment | Fit to this environment without memorizing items | Shared templates and verifier quirks inflate scores |
| Held-out environments, same family | Transfer across tool sets and data within a domain | Near-duplicate environments from the same generator |
| Held-out families | General agentic skill | Too few families to estimate variance; family boundaries chosen after the fact |
| Fresh tasks after a time cutoff | Contamination-free capability on a live distribution | Small samples; distribution shift over time |
Table. Evaluation splits for environment-trained agents and what each can support.
Scores in a held-out set are nested: tasks inside environments inside families. A simple model writes the pass rate of task \(k\) in environment \(j\) of family \(i\) as
\[ p_{ijk}=\mu+\alpha_i+\beta_{ij}+\varepsilon_{ijk},\qquad \operatorname{Var}(\hat s)\approx\frac{\sigma_F^2}{F}+\frac{\sigma_E^2}{FE}+\frac{\sigma_T^2}{FET}, \]with \(F\) families, \(E\) environments per family and \(T\) tasks per environment. When the claim is general skill, the family term dominates: with four held-out families the score's uncertainty is set by four numbers, however many tasks there are. Treating tasks as independent underestimates the standard error, and a cluster bootstrap over families is itself unreliable with so few clusters. The generalization gap at each level, \(g_d=s_{\text{train-dist}}-s_d\), is informative only if the grouping that defines \(d\) (generator, repository, template) was fixed before training.
The script draws a held-out evaluation with four families, six environments per family and fifty tasks per environment, using family and environment random effects. It compares the naive standard error that treats all tasks as independent, a bootstrap over families, the true spread over repeated draws of families and the analytic value.
import numpy as np
rng = np.random.default_rng(5)
F, E, T = 4, 6, 50 # held-out families, environments per family, tasks per env
sF, sE = 0.12, 0.06 # std of family and environment effects on pass rate
def draw():
fam = rng.normal(0, sF, F)[:, None, None]
env = rng.normal(0, sE, (F, E))[:, :, None]
p = np.clip(0.5 + fam + env + rng.normal(0, 0.1, (F, E, T)), 0.01, 0.99)
return (rng.random((F, E, T)) < p).astype(float)
y = draw()
naive = y.std() / np.sqrt(y.size)
fam_means = y.mean(axis=(1, 2))
boot = [fam_means[rng.integers(0, F, F)].mean() for _ in range(5000)]
print(f"score {y.mean():.3f} naive SE (tasks iid) {naive:.3f} family-bootstrap SE {np.std(boot):.3f}")
true_sd = np.std([draw().mean() for _ in range(2000)])
print(f"true SD of the score across redraws of families: {true_sd:.3f}")
print(f"analytic sqrt(sF^2/F + sE^2/(F*E)) = {np.sqrt(sF**2 / F + sE**2 / (F * E)):.3f} (plus task noise)")
Prints a naive SE of 0.014 and a family-bootstrap SE of 0.034 against a true SD of 0.062 (analytic 0.061): with four families, task-level error bars are about four times too narrow.
In practice the split is assigned by hashing a grouping key, never by sampling tasks. The key is the most specific shared origin: environment generator and template for synthesized environments, repository for mined ones, source application for hand-built ones. Family definitions are written down before training, with the reasons, so they cannot be chosen after the results are known.
Agent World Model shows the strong form: training on synthetic SQL-backed environments and evaluating on external benchmarks the environments were not built to imitate, with a stated list of what the training environments omit. Operationally, teams keep several held-out families, rotate fresh time-cutoff tasks into evaluation, and track near-duplicate environments from the same generator, since a generator that emits two variants of one environment silently turns an environment-level split into a task-level one.
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. Fixing 28 defective Terminal-Bench tasks moved some scores by about 12 points (Terminal-Bench 2.1), and 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, a gap that closed with larger time budgets. The minimum report names the split level, environment and verifier versions, harness and budget, trials per task, and whether any training environment shares a generator, repository or template with the evaluation set.
With \(n\) tasks and \(k\) trials per task, the success rate \(\hat s=\frac{1}{nk}\sum_{i,j}y_{ij}\) has variance
\[ \operatorname{Var}(\hat s)=\frac{1}{n}\Big(\operatorname{Var}_i(p_i)+\frac{\mathbb E_i[p_i(1-p_i)]}{k}\Big), \]so extra trials shrink only the within-task term, and the standard error is computed over task means (Miller 2024). Two configurations evaluated on the same tasks are compared by the paired difference \(d_i=\bar y_i^A-\bar y_i^B\), whose variance removes the shared task difficulty. Defective tasks and harness choice are systematic errors, untouched by \(n\) or \(k\): fixing 28 Terminal-Bench tasks moved some scores by about 12 points, and harness swaps moved one model's accuracy by up to 29.9 points (Buchanan et al. 2026). A result is therefore a function \(s(\pi,\text{harness},v,\text{split},\text{budget})\), and every argument must be reported.
The script evaluates one policy under two harnesses on 100 tasks with five trials each. It reports each score with a 95% interval computed over task means, compares the harnesses with a paired difference, and emits a minimal evaluation card containing the fields a report must carry.
import numpy as np, json
rng = np.random.default_rng(6)
n, k = 100, 5 # tasks, trials per task
p_task = rng.beta(1.2, 1.0, n) # per-task success probability of the policy
def run(p): return (rng.random((n, k)) < p[:, None]).astype(float)
A = run(p_task) # harness A
B = run(np.clip(p_task - 0.08 * (p_task > 0.3), 0, 1)) # harness B is worse on mid/hard tasks
def summary(y):
m = y.mean(1); se = m.std(ddof=1) / np.sqrt(n) # cluster by task: trials are not independent
return round(float(y.mean()), 3), round(float(1.96 * se), 3)
d = A.mean(1) - B.mean(1) # paired difference per task
card = {"policy": "ckpt-step-1200", "split": "held-out environments", "env_version": "2.1",
"verifier_version": "v7", "harness": "A", "budget_s": 3600, "trials_per_task": k,
"tasks": n, "score": summary(A)[0], "ci95": summary(A)[1],
"shares_generator_with_train": False}
print(json.dumps(card))
print("harness B:", summary(B), "| paired A-B:", round(float(d.mean()), 3), "+/-", round(float(1.96 * d.std(ddof=1) / np.sqrt(n)), 3))
Prints the card (score 0.528, ±0.067) and harness B at 0.426 ± 0.065; the paired difference is 0.102 ± 0.057, a tighter interval than the two separate intervals suggest.
Reports are generated by the evaluation pipeline, not assembled by hand. Each run writes per-trial results with policy checkpoint, harness and its version, environment and verifier versions, budget (time, tokens, turns), split level and the registry check's outcome; the card is a view over those rows. Because harness and budget move scores by double-digit points, comparisons hold them fixed or report curves over the budget, and the harness is versioned like an environment.
The generator-sharing question is answered from lineage metadata: the pipeline checks whether any training environment shares a generator, repository or template with the evaluation set and writes the answer into the card. Benchmark changes such as Terminal-Bench 2.1 require re-running baselines rather than comparing across versions.
State of the Art in 2026
By late 2026, the labs that publish details of their agentic post-training describe a similar stack: thousands to tens of thousands of executable environments, synthesized or mined tasks with programmatic checks, and a sandbox 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 at prices that 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.
Concurrency from throughput. The concurrency figures in the reports follow from Little's law (Little's law). If a training step consumes \(B\) groups of \(G\) episodes and the step must take \(T_{\text{step}}\) seconds, episodes must finish at rate \(\lambda = BG/T_{\text{step}}\). With mean episode duration \(\bar W\), the mean number of episodes in flight is
Concurrency therefore scales with episode length as much as with batch size. Single-turn math answers last seconds; agentic coding and search episodes last minutes, which is what moves \(L\) from \(10^3\) to \(10^4\)–\(10^5\) at the same batch.
RL as a share of training cost. Writing the RL budget as \(C_{\text{RL}} = N_{\text{ep}}\,(c_{\text{tok}}\,\bar T + c_{\text{sbx}}\,\bar W) + C_{\text{upd}}\), with \(N_{\text{ep}}\) episodes, \(\bar T\) generated tokens per episode at cost \(c_{\text{tok}}\), sandbox time at cost \(c_{\text{sbx}}\) and trainer cost \(C_{\text{upd}}\), DeepSeek-V3.2's statement is \(C_{\text{RL}}/C_{\text{pre}} > 0.1\). Since the reported numbers are orders of magnitude, they compare on \(\log_{10}\): two counts within a factor of three are the same size for planning purposes.
Little's law turns a training-step budget into a sandbox count. The script draws long-tailed agentic episode durations (lognormal, median four minutes, capped at 30 minutes, an assumption rather than a measured distribution) for a step of 512 groups of 16 and reports the mean concurrency the fleet must sustain.
"""How many sandboxes a training step keeps busy: Little's law L = lambda * W."""
import numpy as np
rng = np.random.default_rng(0)
prompts, G = 512, 16 # groups per step and samples per group
step_s = 600.0 # target wall-clock time of one training step
# agentic episode durations are long-tailed: lognormal, median 4 min, capped at 30 min
dur = np.minimum(rng.lognormal(np.log(240), 0.9, prompts * G), 1800)
lam = prompts * G / step_s # episodes that must finish per second
L_mean = lam * dur.mean() # Little's law: mean concurrent episodes
print(f"episodes/step={prompts*G} arrival rate={lam:.1f}/s mean duration={dur.mean():.0f}s")
print(f"mean concurrent sandboxes L = {L_mean:,.0f}")
print(f"sandbox-hours per step = {dur.sum()/3600:,.0f}; p99 duration = {np.percentile(dur,99):.0f}s")
Output:
episodes/step=8192 arrival rate=13.7/s mean duration=352s
mean concurrent sandboxes L = 4,805
sandbox-hours per step = 801; p99 duration = 1800s
A modest batch with ten-minute steps already needs about 5,000 sandboxes in flight; doubling the step budget halves it, doubling the median duration doubles it. The 30-minute cap binds at the 99th percentile, so the cap, not the median, sets how long the last sandbox of a step stays busy. Scaling the batch or the episode length by ten reaches the \(10^4\)–\(10^5\) concurrency that Kimi K2.5 and DeepSeek-V4 report.
What the stack implies for a program. The reports agree on structure more than on numbers, and the structure is what a new program can copy: an inventory of executable environments with programmatic checks, a sandbox fleet sized for minutes-long episodes, and a gateway that records every model call. Capacity planning starts from the concurrency formula above, not from environment counts: a program with a few hundred environments and long episodes can need more sandboxes than one with thousands of short tasks.
Normalizing the numbers. Because "environment", "task" and "scaffold" mean different things across reports, internal dashboards should count units that are comparable: distinct images, distinct verifiers, tasks per family, and the share of tasks that are informative for the current policy. Purchased environments enter the same inventory under the same units. The budget line to watch is the RL share of total training compute; once it passes a tenth, sandbox and verifier efficiency become as important as GPU efficiency.
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.
| Report | Environments and tasks | Execution 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 trajectories | Kubernetes 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 SWE | Async-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 tasks | RL budget stated as above 10% of pre-training cost |
| Kimi K2.5 (Feb 2026) | Gym-like framework with pluggable toolsets and judges; synthetic prompts | Up 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 graph | slime 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.5 | Middleware (gateway plus data pool) between agents and trainer |
| DeepSeek-V4 (Apr 2026) | RL against real tool environments; counts not given in the summary | DSec: 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; 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).
Hard to solve, easy to verify, as a filter. A synthesized task with true solve rate \(p\) passes a pass@\(k\) admission rule (at least one success in \(k\) attempts) with probability
At \(k = 100\) a task solved once in a hundred attempts is kept with probability 0.63, and an impossible or broken task (\(p = 0\)) is never kept. The rule removes tasks whose verifier can never be satisfied; it cannot remove tasks whose verifier accepts wrong answers, because those have high \(p\). Kept tasks are useful for group-relative RL in proportion to the chance that a group of \(G\) samples has mixed rewards,
which is zero at \(p \in \{0, 1\}\) and largest at \(p = 0.5\).
Mined SWE instances. Let \(\mathcal{T}\) be the repository tests, \(b(t)\) and \(a(t)\) their pass indicators before and after the gold patch. Then \(\text{F2P} = \{t : \neg b(t) \wedge a(t)\}\) and \(\text{P2P} = \{t : b(t) \wedge a(t)\}\). DeepSeek-V3.2's validity condition is \(|\text{F2P}| \ge 1\) and \(\{t : b(t) \wedge \neg a(t)\} = \varnothing\); an agent's patch earns \(R = 1\) iff every test in \(\text{F2P} \cup \text{P2P}\) passes.
Simulation and startup. A simulator is a useful wind tunnel when it preserves the ordering of policies, \(J_{\text{sim}}(\pi_1) > J_{\text{sim}}(\pi_2) \Leftrightarrow J_{\text{real}}(\pi_1) > J_{\text{real}}(\pi_2)\); matching reward curves, as Tongyi DeepResearch reports, is a stronger version of that. For real sandboxes, a startup time \(s\) wastes a fraction \(s/(s + \bar W)\) of sandbox time: a ten-second start against a five-minute episode costs about 3%.
Two admission tests recur across the reports. The first keeps a synthesized task only if some attempt among \(k = 100\) passes its verification function, as DeepSeek-V3.2 does; the second accepts a mined SWE instance only if the gold patch turns at least one failing test into a passing one and breaks none. The script applies the first to 20,000 simulated tasks (35% impossible, the rest with Beta(0.5, 1.5) solve rates, both assumptions) and the second to two hand-written test reports.
"""Two admission tests from 2025-2026 reports: a pass@k filter for synthesized tasks,
and the fail-to-pass / pass-to-pass check for mined SWE instances."""
import numpy as np
def keep_task(successes):
"""DeepSeek-V3.2-style rule: keep a synthesized task only if some attempt passed."""
return successes > 0
def swe_instance_valid(before, after):
"""before/after: {test_name: passed} without and with the gold patch.
Valid iff at least one test flips fail->pass and no passing test breaks."""
f2p = [t for t in before if not before[t] and after.get(t, False)]
p2p_broken = [t for t in before if before[t] and not after.get(t, False)]
return len(f2p) > 0 and not p2p_broken, f2p, p2p_broken
rng = np.random.default_rng(1)
n, k, G = 20_000, 100, 8
# true solve rates of freshly synthesized tasks: many impossible or broken (p = 0)
p = np.where(rng.random(n) < 0.35, 0.0, rng.beta(0.5, 1.5, n))
succ = rng.binomial(k, p)
kept = keep_task(succ)
inf = lambda q: 1 - q**G - (1 - q)**G # P(group of G has mixed rewards)
print(f"kept {kept.mean():.1%} of tasks; impossible tasks kept: {np.mean(kept[p == 0]):.0%}")
print(f"informative groups (G={G}): all tasks {inf(p).mean():.2f}, kept tasks {inf(p[kept]).mean():.2f}")
before = {"test_parse": False, "test_roundtrip": True, "test_empty": True}
after = {"test_parse": True, "test_roundtrip": True, "test_empty": True}
print("valid instance:", swe_instance_valid(before, after))
after["test_empty"] = False
print("gold patch breaks a test:", swe_instance_valid(before, after))
Output:
kept 57.4% of tasks; impossible tasks kept: 0%
informative groups (G=8): all tasks 0.39, kept tasks 0.68
valid instance: (True, ['test_parse'], [])
gold patch breaks a test: (False, ['test_parse'], ['test_empty'])
The pass@100 rule drops every impossible task and almost doubles the share of groups that carry a gradient, from 0.39 to 0.68. The SWE check rejects the instance as soon as the gold patch breaks a previously passing test, because such an instance would reward agents for reproducing the regression.
Reading the reports as recipes. Each recurring pattern carries an operating cost that the reports mention briefly or not at all. Pass@100 admission costs a hundred rollouts per candidate task, usually from a cheaper model than the policy, so admission compute must be budgeted alongside training. Fail-to-pass harvesting needs the repository's tests to run reliably in a container; flaky tests become noisy rewards, so mined instances are run several times and dropped when the gold patch does not pass every time (see Mining Real Software).
What the reports omit. None of the rows gives a verifier error rate, a hack rate found during training, or the share of environments retired as the policy saturated them. These are the numbers that decide whether an environment inventory is worth its size. A program replicating the stack should measure them from the start: verifier false-positive rate on adversarial probes, infrastructure-failure rate per environment, and pass-rate drift per family.
Build order. Read across the reports, the components arrived in a consistent order: a gateway that captures tokens exactly (Kimi K2.5, GLM-5's token-in/token-out gateway, MiniMax Forge's middleware), then a sandbox service with fast startup (Prime Intellect, DSec), then synthesis to fill the task inventory. Simulation (Kimi K2's simulated tools, Tongyi's offline Wikipedia) is used where the real system is slow, rate-limited or unsafe to call at training scale, and is checked against the real system before the policy moves to it.
The Environment Market
Frontier and "neo" labs buy most of their environments and tasks from outside vendors, and 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, and 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, and their prices are analyzed in Hand-Built High-Fidelity Environments. Kourabi & Patel (SemiAnalysis, 2026) count more than 35 environment companies, almost all seed-stage with one to three customers, and estimate that Anthropic works with more than a dozen of them; coding environments are the most in demand. Denain & Barber (Epoch AI, 2026) put typical tasks at $200–$2,000 and contracts at six to seven figures per quarter, and Erdil et al. (Mechanize, 2025) argued that per-task spending should rise because 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, acquired Sepal AI, which builds training data, benchmarks and RL environments, in February, and 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, and its CEO estimated that environment complexity must double every six to eight months to keep challenging frontier models (both self-reported). Zeoli (Wing VC, 2026) expects coding and computer use to be the first large markets, long white-collar workflows the larger long-term one, and the winners to 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.
The cost of a useful rollout. The Mechanize argument can be written as a cost model. A task with authoring cost \(a\) receives \(n\) rollouts over its training life, each costing \(c\) in inference and sandbox time, and a share \(q\) of those rollouts carries a reward that is both informative and correct. Then
is the cost per useful rollout. A better task (\(a_2 > a_1\), \(q_2 > q_1\)) is worth buying while \(\kappa(a_2, q_2) \le \kappa(a_1, q_1)\), that is while
The break-even authoring cost grows linearly with lifetime compute per task: the longer and more expensive the episodes, the more a task's quality is worth. This is why long agentic tasks support prices of hundreds to thousands of dollars.
Contract arithmetic and moving targets. Epoch's figures bound the volume of a contract: six to seven figures per quarter at $200–$2,000 per task is between \(10^5/2{,}000 = 50\) and \(10^7/200 = 50{,}000\) tasks, a range too wide to plan on. Halluminate's self-reported doubling of environment complexity every \(\tau = 6\)–\(8\) months means complexity grows as \(H(t) = H_0\,2^{t/\tau}\), a factor of \(2^{12/\tau} \approx 2.8\)–\(4\) per year.
The cost model compares a cheap task ($20 to author, 20% useful rollouts) with a carefully built one ($1,000, 50% useful) at three lifetime compute levels, from short tool calls to long SWE episodes. The rollout count and quality shares are assumptions chosen to show the shape of the trade-off, not vendor data.
"""When is an expensive task worth buying? Cost per useful rollout = (authoring + lifetime compute) / useful rollouts."""
def cost_per_useful(author, compute, rollouts, quality):
"""quality: share of rollouts whose reward is both informative and correct."""
return (author + compute) / (rollouts * quality)
def break_even_author_cost(cheap_author, compute, q_cheap, q_good):
"""Highest authoring cost at which the better task still matches the cheap one."""
return q_good / q_cheap * (cheap_author + compute) - compute
rollouts = 2_000 # rollouts a task receives over its training life (assumption)
q_cheap, q_good = 0.20, 0.50 # useful share for a cheap vs a carefully built task (assumption)
for per_rollout in (0.05, 0.5, 5.0): # $ per agentic rollout: short tool call ... long SWE episode
C = rollouts * per_rollout
a = cost_per_useful(20, C, rollouts, q_cheap)
b = cost_per_useful(1_000, C, rollouts, q_good)
be = break_even_author_cost(20, C, q_cheap, q_good)
print(f"compute/task ${C:>7,.0f}: $/useful rollout cheap={a:6.2f} built={b:6.2f} break-even authoring ${be:,.0f}")
Output:
compute/task $ 100: $/useful rollout cheap= 0.30 built= 1.10 break-even authoring $200
compute/task $ 1,000: $/useful rollout cheap= 2.55 built= 2.00 break-even authoring $1,550
compute/task $ 10,000: $/useful rollout cheap= 25.05 built= 11.00 break-even authoring $15,050
When a task's lifetime compute is $100, the cheap task wins by a wide margin and a better task is worth at most $200. At $10,000 of compute per task the ordering reverses: the built task costs less than half as much per useful rollout, and any authoring cost up to about $15,000 would still pay. The crossover is set by lifetime compute, not by the authoring price.
Buying environments. A purchased environment is accepted only after the same checks an internal one passes: an oracle or gold solution reaches full reward, a null agent and a set of adversarial agents do not, a pass-rate sweep with the current policy shows the tasks are in band, the image builds reproducibly, and an overlap check finds no tasks shared with the evaluation suites (see Train/Eval Separation). Tasks that fail are returned under the contract rather than silently dropped, so the vendor's rejection rate is measured.
Contract terms that matter. The terms that protect a lab are delivery format (Harbor, OpenEnv or Verifiers, so the environment runs without vendor code in the trainer), replacement of tasks later found hackable or broken, exclusivity or at least disclosure of overlap with other customers, and a refresh schedule. Refresh matters because a frontier policy saturates a task family within months; a contract priced per task without refresh buys an asset that loses value as the model improves.
Vendor risk. SemiAnalysis's count of seed-stage vendors with one to three customers each implies continuity risk: a lab should hold the images, verifiers and task data, not only access to them. Consolidation such as Mercor's acquisitions reduces that risk but concentrates supply, and environments sold to several labs make benchmark contamination and shared reward hacks more likely. Per-vendor dashboards track acceptance rejection rate, hacks found during training, and months to saturation.
Open Ecosystems
An open layer grew alongside the closed market, so that environments can be shared and reused across trainers. Prime Intellect open-sources its environments on the Environments Hub, written with its Verifiers library; OpenEnv gained a coordinating committee in June 2026 (including Meta-PyTorch, Hugging Face, Prime Intellect, Nvidia, Mercor, Modal and Microsoft), with RFCs on external rewards, dataset-backed tasksets and automatic environment validation. The standards are compared in Environment Standards and Hubs.
The shared contract. An environment is shareable when a trainer needs nothing beyond a fixed interface: a task distribution \(\rho\), a reset \(s_0 = \text{reset}(x, \text{seed})\), a transition \(s_{t+1}, o_{t+1} = \text{step}(s_t, a_t)\), a reward \(R_x(\tau)\) computed from the final state and declared artifacts, and budgets. A trainer that mixes \(E\) hub environments with weights \(w_e\) optimizes
so the mixing weights are part of the objective, and a shared environment must report rewards on a common scale.
Automatic validation as testing. A validator runs an oracle, a null agent and adversarial agents. If \(n\) adversarial probes all fail to earn reward, the verifier's false-positive rate \(f\) satisfies \((1-f)^n \ge 0.05\) at 95% confidence, so \(f \le 3/n\) approximately (the rule of three): 300 clean probes bound \(f\) below 1%.
The sketch below is a minimal environment in the reset/step/score shape shared by Gymnasium, Verifiers and OpenEnv, with an automatic validator of the kind OpenEnv's RFCs propose. The validator checks that an oracle solves every seed, a null agent and a wrong-answer agent earn nothing, reset is deterministic, and two instances do not share state. A second environment has a deliberately lax verifier.
"""A shareable environment contract (reset / step / score) and an automatic validator
that a hub can run before accepting an environment."""
import random
class SumEnv:
"""Task: write the sum of a hidden list into the file 'answer' using a tool."""
def __init__(self): self.files = {}
def reset(self, seed):
rng = random.Random(seed)
self.nums, self.files, self.steps = [rng.randint(1, 99) for _ in range(5)], {}, 0
return f"Numbers: {self.nums}. Write their sum to 'answer'."
def step(self, action): # action = ("write", path, text) | ("stop",)
self.steps += 1
if action[0] == "write": self.files[action[1]] = action[2]
return "ok", action[0] == "stop" or self.steps >= 10
def score(self): # reads final state only, never the transcript
return float(self.files.get("answer", "").strip() == str(sum(self.nums)))
class LeakyEnv(SumEnv):
"""Bug: the verifier accepts any non-empty answer."""
def score(self): return float(bool(self.files.get("answer")))
def run(env, seed, policy):
obs, done = env.reset(seed), False
while not done: obs, done = env.step(policy(env, obs))
return env.score()
oracle = lambda env, obs: ("write", "answer", str(sum(env.nums))) if "answer" not in env.files else ("stop",)
null = lambda env, obs: ("stop",)
wrong = lambda env, obs: ("write", "answer", "0") if "answer" not in env.files else ("stop",)
def validate(make_env, seeds=range(50)):
checks = {
"oracle solves": all(run(make_env(), s, oracle) == 1 for s in seeds),
"null agent fails": all(run(make_env(), s, null) == 0 for s in seeds),
"wrong answer fails": all(run(make_env(), s, wrong) == 0 for s in seeds),
"reset deterministic": all(make_env().reset(s) == make_env().reset(s) for s in seeds),
}
a, b = make_env(), make_env(); a.reset(0); b.reset(0); a.step(("write", "answer", "1"))
checks["instances isolated"] = "answer" not in b.files
return checks
for cls in (SumEnv, LeakyEnv):
c = validate(cls)
print(f"{cls.__name__:8s}", "PASS" if all(c.values()) else "FAIL", [k for k, v in c.items() if not v])
Output:
SumEnv PASS []
LeakyEnv FAIL ['wrong answer fails']
Both environments pass the oracle and null-agent tests; only the wrong-answer probe exposes the lax verifier. A hub that ran only oracle and null checks would accept it.
Adopting hub environments. An environment taken from the Environments Hub or an OpenEnv registry is third-party code that will run millions of times inside the training system. It is pinned by version hash, its image mirrored internally, and it runs in the sandbox fleet rather than in the trainer process, because in-process environment code executes with the trainer's credentials. Licenses are checked per environment, since hub contents mix permissive and restrictive terms.
Validation and contamination. The hub's own checks are a floor; each environment also passes the internal validator and a pass-rate sweep with the target policy. Public environments carry a contamination risk in both directions: their tasks may already be in pretraining corpora, and training on them can leak into evaluations built from the same sources. OpenEnv's RFCs on external rewards, dataset-backed tasksets and automatic validation are aimed at exactly these problems, and environments fixed internally are worth contributing back so that the public version stays the one under test.
Reference Architecture
A production environment program needs eleven components in three layers: a definition layer that says what an environment is (registry, task store, image builder), a run layer that executes episodes (inference gateway, rollout orchestrator, sandbox fleet, verifier service), and a learning layer that turns episodes into updates and checks them (trajectory store, curation, trainer, eval harness). The diagram synthesizes the reports above and earlier parts of this book; its main choice is that model calls, environment execution and grading are separate services joined by versioned identifiers.
Throughput is set by the slowest layer. Treat the run and learning layers as stages in series, each able to sustain \(\mu_i\) episodes per second (gateway, sandbox fleet, verifier, trainer). The program's throughput is
where \(\rho_i\) is the utilization of stage \(i\). Only the bottleneck runs at \(\rho = 1\); adding capacity anywhere else raises cost without raising \(X\).
Sizing the sandbox pool. With episode arrivals at rate \(\lambda\) and mean sandbox holding time \(\bar W\), the offered load is \(a = \lambda \bar W\) busy sandboxes. Modelling the pool as an M/M/\(c\) queue, the probability that an episode waits for a sandbox is the Erlang C formula
For a fixed waiting target the required pool follows square-root staffing, \(c \approx a + \beta\sqrt{a}\), with \(\beta \approx 2.4\) for a 1% chance of waiting. Headroom therefore shrinks as a share of the fleet as the fleet grows.
The join key. Each episode is identified by \(k(\tau) = (e@v_e,\ x@v_x,\ d_{\text{img}},\ v_{\text{ver}},\ v_\pi)\): environment, task, image digest, verifier and policy versions. A trajectory is reproducible only if every element of \(k\) is pinned.
Two capacity calculations follow from the diagram. The first finds the bottleneck among four stages with illustrative capacities in episodes per second; the second sizes the sandbox pool with the Erlang C formula, computed through the numerically stable Erlang B recursion, for offered loads from 100 to 10,000 busy sandboxes and a 1% target chance that an episode waits.
"""Capacity of the run layer: the bottleneck stage sets throughput, and Erlang C sizes the sandbox pool."""
import math
def erlang_c(c, a):
"""P(an arriving episode waits) in an M/M/c queue with offered load a = lambda*W (needs c > a)."""
if c <= a: return 1.0
inv_b = 1.0 # Erlang B by the stable recursion, then convert to C
for k in range(1, c + 1): inv_b = 1 + inv_b * k / a
b = 1 / inv_b
return b / (1 - (a / c) * (1 - b))
def pool_size(a, p_wait=0.01):
c = math.ceil(a) + 1
while erlang_c(c, a) > p_wait: c += 1
return c
# episodes per second each stage can sustain (illustrative capacities)
stages = {"gateway (inference)": 16.0, "sandbox fleet": 14.0, "verifier": 40.0, "trainer": 22.0}
x = min(stages.values())
print("bottleneck:", min(stages, key=stages.get), f"-> {x:.1f} episodes/s")
print("utilization:", {k: f"{x / v:.0%}" for k, v in stages.items()})
for a in (100, 1_000, 10_000): # offered load = mean busy sandboxes
c = pool_size(a)
print(f"load a={a:>6,}: sandboxes for P(wait)<1% = {c:,} headroom={(c - a) / math.sqrt(a):.2f} sqrt(a)")
Output:
bottleneck: sandbox fleet -> 14.0 episodes/s
utilization: {'gateway (inference)': '88%', 'sandbox fleet': '100%', 'verifier': '35%', 'trainer': '64%'}
load a= 100: sandboxes for P(wait)<1% = 125 headroom=2.50 sqrt(a)
load a= 1,000: sandboxes for P(wait)<1% = 1,077 headroom=2.43 sqrt(a)
load a=10,000: sandboxes for P(wait)<1% = 10,239 headroom=2.39 sqrt(a)
The sandbox fleet is the bottleneck, so the verifier sits at 35% utilization and extra verifier capacity would be wasted. The pool needs 25% headroom at 100 busy sandboxes but only 2.4% at 10,000, because the headroom grows with \(\sqrt{a}\) (about 2.4 \(\sqrt{a}\) at every scale), which is why large shared fleets are cheaper per episode than many small ones.
Three layers, three engineering profiles. The definition layer is low-throughput and correctness-critical, and is run like a build system: changes go through review and the environment's own tests before a new version is registered. The run layer is the cost center, dominated by inference and sandbox time, and is run like a serving system with latency and availability targets. The learning layer is storage and GPU work, and is run like a data platform with lineage on every record.
Build or buy, layer by layer. In 2026 the run layer is the most often bought: sandbox services from Modal, Prime Intellect, GKE Agent Sandbox or in-house fleets such as DSec, and gateways built into frameworks such as slime and prime-rl. The definition and learning layers stay in house because they hold the task data, the verifiers and the evaluation sets.
Service-level objectives. Each layer gets one headline target: registry builds reproducible to the digest; sandbox startup at the 99th percentile and pool wait probability; gateway capture completeness of 100% of calls with token ids and log-probabilities; verifier latency well below episode duration; infrastructure-failure rate per environment version; and policy staleness at the trainer. A breach in any of them is visible as a change in reward curves only after damage is done, so each is alerted on directly.
Components
Each component has one job and one owner, and each emits identifiers that the trajectory store joins on.
- 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.
- Task store. Versioned prompts, seeds, hidden answers and split labels; held-out families are unreadable by curation and training.
- Image builder. Builds images, snapshots and warm pools (see Sandboxes).
- Inference gateway. OpenAI-compatible proxy recording token ids, log-probabilities and policy version for every call.
- Rollout orchestrator. Schedules groups, enforces budgets, handles stragglers, retries only infrastructure failures (see Rollout Systems).
- Sandbox fleet. Isolated containers or microVMs holding state and running tools, MCP servers, browsers or shells.
- Verifier service. Rewards from tests, state checks, rubrics or judges, computed in a fresh sandbox from declared artifacts (see Verifiers and Rewards).
- Trajectory store. Episode metadata and token arrays keyed by every version above (see The Trajectory Data Model).
- Curation. Pass-rate banding, dedup, decontamination, environment mixing (see Curating Rollouts).
- Trainer. Updates the policy, correcting for policy lag with stored log-probabilities.
- Eval harness. Runs checkpoints on held-out families under a pinned harness and gates promotion (see Train/Eval Separation).
Content-addressed versions. The registry assigns each environment the version \(v_e = H(\text{spec}_e)\), a hash of the canonical specification (image digest, tools, verifier version, task-set version, limits). Two episodes are comparable only if their keys agree, and a change to any field, including the verifier, creates a new version rather than mutating an old one.
Correcting for policy lag. The gateway stores, for every generated token \(y_t\) with context \(h_t\), the behavior log-probability \(\log \mu(y_t \mid h_t)\) under the weights the engine actually used. The trainer computes the ratio \(r_t = \pi_\theta(y_t \mid h_t) / \mu(y_t \mid h_t)\) and, following Yao et al. (2025), truncates it:
The ratio is defined only if the trainer scores exactly the stored token ids; re-encoding text breaks the correspondence.
Curation and gating. Curation keeps task \(x\) when its estimated pass rate \(\hat p_x = c_x/k\) lies in a band \([\ell, u]\), with standard error \(\sqrt{p(1-p)/k}\). The eval harness promotes a checkpoint when the lower confidence bound on its improvement over the incumbent on held-out families is positive, \(\hat\Delta - z\sqrt{\hat p_1(1-\hat p_1)/n_1 + \hat p_2(1-\hat p_2)/n_2} > 0\).
The identifiers in the component list can be shown in a few lines. An environment specification is hashed into its version, so changing only the verifier yields a new version; a trajectory carries that version, the task, the policy version and the gateway's per-token log-probabilities; the trainer computes truncated importance weights from those stored log-probabilities and rejects a sample whose token ids no longer match.
"""Versioned identifiers that join the components, and the trainer's use of stored log-probabilities."""
import hashlib, json
from dataclasses import dataclass, asdict
import numpy as np
def content_id(obj):
"""Version = hash of the canonical spec: any change to image, tools or verifier is a new version."""
return hashlib.sha256(json.dumps(obj, sort_keys=True).encode()).hexdigest()[:12]
@dataclass(frozen=True)
class EnvSpec:
name: str; image_digest: str; tools: tuple; verifier: str; taskset: str; timeout_s: int
@property
def version(self): return content_id(asdict(self))
@dataclass
class Trajectory:
env: str; env_version: str; task_id: str; policy_version: int
token_ids: list; behavior_logp: np.ndarray; reward: float | None; infra_error: str | None
spec = EnvSpec("repo-fix", "sha256:9f2c", ("bash", "edit"), "pytest@v3", "tasks@v7", 1800)
spec2 = EnvSpec("repo-fix", "sha256:9f2c", ("bash", "edit"), "pytest@v4", "tasks@v7", 1800)
print("env versions:", spec.version, spec2.version)
rng = np.random.default_rng(0)
T = 6
mu = rng.normal(-1.0, 0.3, T) # log-probs recorded by the gateway at sampling time
traj = Trajectory("repo-fix", spec.version, "t-0412", 41, list(range(T)), mu, 1.0, None)
registry = {(spec.name, spec.version): spec}
print("join ok:", (traj.env, traj.env_version) in registry)
logp_new = mu + rng.normal(0.0, 0.7, T) # trainer's log-probs under current weights
w = np.exp(logp_new - traj.behavior_logp) # token importance weights pi/mu
print("token weights:", np.round(w, 2), "truncated at 2:", np.round(np.minimum(w, 2.0), 2))
retok = traj.token_ids[:3] + [99] + traj.token_ids[4:] # text re-encoded by the trainer
mismatch = sum(a != b for a, b in zip(retok, traj.token_ids))
print("retokenization mismatches:", mismatch, "-> reject sample" if mismatch else "")
Output:
env versions: c257f1c5d4f3 a546273ab70e
join ok: True
token weights: [2.49 1.94 0.61 0.41 0.65 1.03] truncated at 2: [2. 1.94 0.61 0.41 0.65 1.03]
retokenization mismatches: 1 -> reject sample
Moving the verifier from pytest@v3 to pytest@v4 changes the version id, so rewards from the two verifiers can never be pooled by accident. The first token's weight of 2.49 is truncated to 2, and a single re-encoded token is enough to reject the sample.
In production each component has one owning team, one headline metric and a characteristic failure. The table is a checklist for operating the eleven components rather than a prescription of team structure.
| Component | Headline metric | Characteristic failure |
|---|---|---|
| Environment registry | share of versions with passing self-tests | a mutable tag lets a fleet run an unregistered image |
| Task store | read audit on held-out families | held-out tasks reach curation through a shared bucket |
| Image builder | build reproducibility, warm-pool hit rate | unpinned dependencies change behavior between builds |
| Inference gateway | calls captured with ids and log-probabilities | a scaffold bypasses the proxy and its tokens are lost |
| Rollout orchestrator | step time, staleness, retry rate | retrying agent failures as if they were infrastructure |
| Sandbox fleet | p99 startup, pool wait, failure rate | noisy neighbors make episode timeouts load-dependent |
| Verifier service | false-positive rate on probes, latency | grading in the agent's sandbox, where tests can be edited |
| Trajectory store | share of records with every key present | missing policy version makes importance weights impossible |
| Curation | informative-group share per step | a static band decays as the policy improves |
| Trainer | importance-weight clip rate, entropy | engine and trainer numerics diverge without correction |
| Eval harness | harness version pinned per result | a harness change is read as a model change |
Table. One metric and one failure per component of the reference architecture.
The trajectory store is where the components are audited together: a nightly job that counts records missing any key, or keys that do not resolve in the registry, catches most integration regressions before they reach a training run.
Trust and Failure Boundaries
The architecture draws three boundaries, each preventing a known failure. The agent sandbox never holds hidden tests or reference state, which blocks test tampering. The gateway sits outside the environment, so token capture is 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. And the orchestrator labels infrastructure failures instead of scoring them, because a crash scored as a failed episode silently corrupts advantages.
Why crashes must not be scored. Let a policy choose between strategies with true success rates \(s_A > s_B\), and let infrastructure fail during an episode with probabilities \(c_A, c_B\), independent of the outcome. If a crash is scored as reward 0, the expected observed reward is \(s(1-c)\), and the gradient favours \(B\) whenever
even though \(A\) is the better strategy. With \(s_A = 0.8\), \(c_A = 0.3\), \(s_B = 0.6\), \(c_B = 0.02\) the observed rewards are 0.56 and 0.59, so training moves away from \(A\). Long, thorough strategies crash more often, so this bias systematically rewards short episodes. If crashes are labeled and excluded, the expected reward conditional on no crash is \(s\), and the ordering is correct. Exclusion is unbiased only when crashes are independent of the outcome given the strategy; when they are not (for example, crashes concentrated on hard instances), the crashed episode is re-run rather than dropped.
The other two boundaries. If the agent can read the hidden tests with probability \(\eta\), a hacking strategy earns \(\eta\) reward with no work, and RL amplifies any \(\eta > 0\). If the gateway is inside the environment, the token ids the trainer scores can differ from those sampled, and the ratio \(r_t\) is computed for tokens the policy never produced.
The simulation trains a two-strategy softmax policy with group-normalized advantages (groups of 8, 64 groups per step, 300 steps). Strategy A succeeds 80% of the time but its long episodes hit infrastructure failures 30% of the time; strategy B succeeds 60% of the time and almost never crashes. The only difference between the two runs is whether a crash is scored as reward 0 or labeled and removed from its group.
"""Why the orchestrator labels infrastructure failures instead of scoring them.
Strategy A (thorough, long) succeeds more often but its long episodes are preempted more often."""
import numpy as np
SUCCESS = {"A": 0.80, "B": 0.60} # true task success rate of each strategy
CRASH = {"A": 0.30, "B": 0.02} # infrastructure failure rate (timeouts, preemptions)
def train(policy_for_crash, steps=300, groups=64, G=8, lr=0.5, seed=0):
rng = np.random.default_rng(seed)
theta = 0.0 # logit of choosing A
for _ in range(steps):
pA = 1 / (1 + np.exp(-theta)); grad = 0.0
for _ in range(groups):
pick_A = rng.random(G) < pA
ok = rng.random(G) < np.where(pick_A, SUCCESS["A"], SUCCESS["B"])
crash = rng.random(G) < np.where(pick_A, CRASH["A"], CRASH["B"])
r = ok.astype(float)
if policy_for_crash == "score as failure":
r[crash] = 0.0; keep = np.ones(G, bool)
else: # label and exclude from the group
keep = ~crash
if keep.sum() < 2 or r[keep].std() == 0: continue
adv = (r[keep] - r[keep].mean()) / r[keep].std()
grad += np.sum(adv * (pick_A[keep] - pA)) # d log pi / d theta for a Bernoulli choice
theta += lr * grad / (groups * G)
return 1 / (1 + np.exp(-theta))
for mode in ("score as failure", "label and exclude"):
print(f"{mode:18s}: P(choose thorough strategy A) after training = {train(mode):.2f}")
Output:
score as failure : P(choose thorough strategy A) after training = 0.16
label and exclude : P(choose thorough strategy A) after training = 0.98
Scoring crashes as failures drives the policy to the worse strategy, because A's observed reward is 0.56 against B's 0.59. Labeling and excluding them recovers the correct preference. Nothing in the reward curve of the first run reveals the problem: rewards rise as the policy learns to avoid crashes.
Holding the sandbox boundary. The agent sandbox has no network egress beyond an allow-list, no credentials, and no hidden tests or reference state. After the episode the orchestrator copies only the declared artifacts (a patch, a database file, an answer) into a fresh grading sandbox where the verifier and hidden tests live. Sandboxes for untrusted code run under microVM or gVisor isolation (see Sandboxes); reward-hacking reports such as METR (2025) show that frontier policies probe for exactly the shortcuts these rules remove.
Holding the capture boundary. The gateway is deployed as a highly available service in front of the inference engines; a scaffold that cannot reach it fails closed rather than calling a model directly. Capture completeness is checked per episode by comparing the number of model calls the scaffold made with the number the gateway recorded.
Holding the failure boundary. The orchestrator keeps a failure taxonomy that separates infrastructure causes (image pull, out-of-memory in the host, node preemption, verifier crash) from agent outcomes (the agent's own command timing out, a malformed tool call), which are scored. Dashboards plot infrastructure-failure rate per environment version and against episode length; a rising slope with length is the signature of the bias above, and a version whose rate exceeds its budget is quarantined from training until fixed.
Production Challenges and Solutions
Most problems in running an environment program are not algorithmic: they come from verifiers that can be fooled, tasks whose difficulty is wrong for the current policy, infrastructure that fails in ways that look like model failures, and environments that drift. The table maps the recurring problems to the fixes that the sources and earlier parts of this book describe, and to the component in the reference architecture where each fix lives.
| Challenge | Symptom | Solution | Where |
|---|---|---|---|
| Reward hacking | Reward rises, held-out eval flat; passes that edit tests or special-case checks | Isolated grading from declared artifacts; hidden tests; impossible-task canaries; read passes | Verifier, curation |
| Verifier false negatives | Correct solutions scored 0; tasks stuck at 0% pass rate | Gold must pass and null must fail before shipping; audit zero-pass tasks | Registry, verifier |
| Difficulty mismatch | Most groups all-pass or all-fail, so advantages are zero | Pass-rate sweep with the current policy; keep a band (at least one success in 64–128 rollouts, below a ceiling); refresh per checkpoint | Curation |
| Infra failures scored as failures | Reward drops that correlate with node, region or image | Separate infra outcome codes; retry or drop, never score; alert per environment | Orchestrator |
| Stragglers and long tails | GPU idle while a few long episodes finish | Asynchronous rollouts with bounded staleness; partial rollouts; per-episode time and turn budgets | Orchestrator, trainer |
| Cold starts and image cost | Minutes per episode spent pulling or building images | Layered and lazily loaded images, snapshots, warm pools; keep environments dependency-light | Image builder, sandbox fleet |
| Token mismatch | Training on re-tokenized text; KL or ratio spikes | Token-in/token-out gateway; store sampled log-probabilities and correct for inference/training mismatch | Gateway, trainer |
| Environment drift | Same 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 change | Registry, image builder |
| Contamination | Benchmark gains that do not transfer | Decontaminate tasks against eval suites; hold out whole environment families, not just tasks | Task store, eval harness |
| Low diversity | Gains concentrated in a few environment templates | Dedup by task embedding and environment template; cap per-family mixing weights | Curation |
| Simulator gap | Policies exploit LLM-simulated tools or users | Check simulated against real environments on a subset; finish training on real execution | Sandbox fleet, eval harness |
| Vendor quality | Buggy clones, LLM-written tasks, inconsistent rubrics | Acceptance tests per delivery; pay per accepted task | Registry |
| Sandbox escape and egress | Agents reaching the internet, the grader or other tenants | MicroVM or gVisor isolation for untrusted code; egress allowlists; no credentials in images | Sandbox 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. If an image crashes 5% of the time and crashes score zero, the policy is penalized for something it did not do, in a way correlated with that environment. And in group-based policy-gradient methods a group with identical rewards has zero advantage, so badly calibrated tasks burn compute for no gradient.
Most rows of the challenge table corrupt one of two quantities: the reward the policy gradient sees, or the distribution of tasks it is computed over. Writing them down separates the problems that only add noise from those that bias training in a fixed direction.
Verifier error. Let \(c\in\{0,1\}\) be whether an episode truly completes the task, with \(P(c=1)=p\), and let the verifier have false-positive rate \(\alpha=P(\tilde r=1\mid c=0)\) and false-negative rate \(\beta=P(\tilde r=0\mid c=1)\). Then
\[ \mathbb{E}[\tilde r] \;=\; p(1-\beta) + (1-p)\,\alpha . \]If \(\alpha\) and \(\beta\) do not depend on the policy, \(\nabla_\theta\mathbb{E}[\tilde r]=(1-\alpha-\beta)\nabla_\theta p\): the signal shrinks but keeps its direction. Reward hacking is the case where \(\alpha=\alpha(\theta)\) grows as the policy finds an exploit; the gradient then gains a term \((1-p)\nabla_\theta\alpha\), which is largest on the hard tasks where \(1-p\) is large. False negatives on correct solutions, by contrast, push \(p\) toward zero and appear as tasks stuck at a 0% pass rate.
Difficulty. With \(G\) rollouts per task, a group-relative advantage is non-zero only when the group mixes outcomes, which happens with probability \(1-p^G-(1-p)^G\).
Infrastructure failures. If an environment crashes with probability \(\kappa\) independently of behaviour and crashes are scored 0, the observed pass rate is \(p(1-\kappa)\) and every crashed episode that would have succeeded receives a negative advantage. When \(\kappa\) varies by environment, image or node, the error is no longer noise: the policy is pushed away from whatever correlates with crashes.
Token mismatch and staleness. The trainer's update assumes tokens were sampled from \(\pi_\theta\), but they came from a sampler \(\mu\) (another engine, older weights). The correction weight per token is \(\rho_t=\pi_\theta(a_t\mid h_t)/\mu(a_t\mid h_t)\), usually truncated at a constant \(C\); it requires the sampled ids and \(\log\mu\), which re-tokenized text does not have.
Contamination. If a fraction \(m\) of evaluation tasks is effectively memorized, the measured score is \(m+(1-m)s\) for true skill \(s\), and growth in \(m\) reads as progress that does not transfer.
Two rows of the table are cheap to simulate: an image that crashes 5% of the time with crashes scored as failures, and verifiers with growing false-positive and false-negative rates. The script below builds 2,000 groups of eight rollouts at a true pass rate of 0.5, computes group-normalized advantages as GRPO does, and reports the advantage that correct-but-crashed episodes receive. It then prints the expected observed reward and the slope \(1-\alpha-\beta\) that scales the learning signal for three verifier qualities.
import numpy as np
rng = np.random.default_rng(0)
def grpo_adv(r):
r = np.asarray(r, float)
return (r - r.mean()) / (r.std() + 1e-6)
p, G, crash = 0.5, 8, 0.05 # one image crashes 5% of the time
hurt, obs = [], []
for _ in range(2000):
ok = rng.random(G) < p
crashed = rng.random(G) < crash
scored = np.where(crashed, 0.0, ok) # crash scored as a failure
obs.append(scored.mean())
hurt += list(grpo_adv(scored)[crashed & ok]) # correct work that got penalized
print(f"observed pass rate {np.mean(obs):.3f} (true {p})")
print(f"mean advantage on crashed-but-correct episodes {np.mean(hurt):+.2f}")
for a, b in [(0.0, 0.0), (0.02, 0.10), (0.10, 0.30)]: # verifier FP and FN rates
print(f"FP={a:.2f} FN={b:.2f}: E[r|p=0.2]={a + (1-a-b)*0.2:.3f}, slope={1-a-b:.2f}")
It prints the deflated pass rate, the penalty assigned to correct work that crashed, and the shrinking slope:
observed pass rate 0.475 (true 0.5)
mean advantage on crashed-but-correct episodes -0.87
FP=0.00 FN=0.00: E[r|p=0.2]=0.200, slope=1.00
FP=0.02 FN=0.10: E[r|p=0.2]=0.196, slope=0.88
FP=0.10 FN=0.30: E[r|p=0.2]=0.220, slope=0.60
A crashed episode that would have passed receives an advantage of about \(-0.87\): the policy is told that correct behaviour was worse than average. Labelling the crash as an infrastructure outcome and dropping it from the group removes that term entirely, at the cost of a slightly smaller group. The verifier rows show the second effect: with 10% false positives and 30% false negatives, a task at 20% looks like 22% and the policy-dependent part of the reward keeps only 60% of its slope.
In practice the table is used backwards: an alert fires on a symptom and the on-call engineer needs the shortest path to a cause. Three symptoms cover most incidents, and each has one first check that separates its common causes.
The published incidents show why each check exists. METR (2025) saw o3 overwrite a scorer's timer and monkey-patch an evaluator, and Anthropic (2025) found that hacks learned on real coding environments generalized to broader misalignment, so a shipped exploit costs more than wasted compute. Monitors alone are not enough: ImpossibleBench found LLM monitors caught only 42–65% of cheating on SWE-scale tasks. Evaluation suites fail too: OpenAI (2026) stopped reporting SWE-bench Verified after finding material test or specification problems in 59 of 138 audited problems.
The infrastructure rows are where fleets differ most. Kondragunta (2026) reports that provisioning is dominated by image economics and that infrastructure failures must be labelled, not scored; GKE Agent Sandbox cut worst-case time to first command from about 7.5 minutes to under 10 seconds with warm pools and off-path hydration. Token mismatch is now handled in the frameworks, with rollout-correction options in verl. For sandbox escape, untrusted code runs in microVMs or gVisor with egress allowlists, as in Prime Sandboxes and DSec.
Playbook: Building an Environment Program Step by Step
An environment program should start from a held-out evaluation and one well-verified environment, prove that training on it moves the evaluation, and only then scale the number of environments and the infrastructure. The steps below are in dependency order; each produces an artifact that the next step needs.
The program's objective is a held-out improvement \(\Delta = S_{\text{eval}}(\theta_T) - S_{\text{eval}}(\theta_0)\) on evaluation families \(\mathcal{F}_{\text{eval}}\) disjoint from the training families. Each step \(k\) produces an artifact \(A_k\) that later steps consume, and has a cost \(c_k\) that grows by orders of magnitude from the first environment to full-scale training. A defect introduced at step \(i\) and found at step \(k\) wastes \(\sum_{j=i}^{k} c_j\), which is dominated by the last term. Ordering the steps by dependency and putting a check at the end of each one minimizes the expected waste, because each defect is caught at the cheapest step that can observe it.
The playbook is a dependency graph: each step produces an artifact, and a step may start only when the artifacts it needs exist. Encoding the graph lets an orchestration job refuse to launch a pilot without a baseline or a scale-up without a pilot report, instead of relying on memory. The script below declares the seven steps with their outputs and inputs, derives an order with the standard-library topological sorter, and checks two gates against a set of finished artifacts.
from graphlib import TopologicalSorter
# step -> (artifact it produces, artifacts it needs)
STEPS = {
"target": ("heldout_eval+baseline", []),
"env": ("env_v1+validate_hook", []),
"audit": ("audited_tasks", ["env_v1+validate_hook"]),
"calibrate": ("pass_rate_table", ["audited_tasks"]),
"pilot": ("pilot_report", ["heldout_eval+baseline", "pass_rate_table"]),
"scale": ("env_families+fleet", ["pilot_report"]),
"operate": ("dashboards+sweeps", ["env_families+fleet"]),
}
producer = {art: s for s, (art, _) in STEPS.items()}
graph = {s: {producer[a] for a in needs} for s, (_, needs) in STEPS.items()}
print("order:", " -> ".join(TopologicalSorter(graph).static_order()))
def may_start(step, done):
missing = [a for a in STEPS[step][1] if a not in done]
return not missing, missing
done = {"env_v1+validate_hook", "audited_tasks", "pass_rate_table"}
print("pilot:", may_start("pilot", done))
print("scale:", may_start("scale", done))
It prints a valid order and the artifacts each blocked step is missing:
order: target -> env -> audit -> calibrate -> pilot -> scale -> operate
pilot: (False, ['heldout_eval+baseline'])
scale: (False, ['pilot_report'])
The environment and the evaluation are independent roots, so they can be built in parallel; everything after the audit is a chain.
In an organization the dependency order becomes ownership. The evaluation is owned by people who never touch training environments, so that held-out families stay held out; environment authors own the verifier and its validation hook; a curation owner runs sweeps; and a platform team owns sandboxes, the orchestrator and the token gateway. The environment registry is the system of record that ties these together: every version carries its image digest, tools, verifier, task set, limits and owner, and each gate reads evidence from it rather than from a meeting.
Most programs in 2026 buy or reuse the lower layers instead of building them: environment libraries and hubs such as Verifiers, OpenEnv and Harbor, managed sandboxes, and open trainers. The parts that remain specific to the program are the target, the held-out families, the verifiers and the curation rules, which is where the playbook spends its first steps.
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), and record the baseline with error bars.
A baseline score \(\hat S\) on \(n\) evaluation tasks has binomial standard error \(\sqrt{\hat S(1-\hat S)/n}\) only if tasks are independent. Tasks in the same family share tools, data and failure modes, so with \(m\) tasks per family and intra-family correlation \(\rho\) the variance grows by the design effect
\[ \operatorname{Var}(\hat S) \approx \frac{S(1-S)}{n}\,\big[1+(m-1)\rho\big]. \]The effective sample size is \(n/[1+(m-1)\rho]\), close to the number of families when \(\rho\) is large. For a paired before/after comparison on the same tasks, the minimum detectable improvement is approximately \((z_{1-a/2}+z_{1-b})\,\mathrm{SE}(\hat\Delta)\) for test size \(a\) and power \(1-b\); a held-out set too small to detect the improvement the program aims for should be enlarged before any environment is built. Holding out whole families means \(\Delta\) estimates transfer to new environments rather than to new tasks in familiar ones.
Error bars on a held-out evaluation should resample whole families, because tasks inside a family succeed or fail together. The script builds an evaluation of eight families with 25 tasks each, gives each family its own difficulty, and compares the naive binomial interval, which treats all 200 tasks as independent, with a bootstrap that resamples families with replacement.
import numpy as np
rng = np.random.default_rng(1)
# held-out eval: 8 families x 25 tasks; families differ in difficulty
fam_p = rng.beta(2, 3, size=8)
fam = np.repeat(np.arange(8), 25)
y = (rng.random(fam.size) < fam_p[fam]).astype(float)
p, n = y.mean(), y.size
naive = 1.96 * np.sqrt(p * (1 - p) / n) # treats 200 tasks as independent
boots = []
for _ in range(5000): # resample whole families
pick = rng.integers(0, 8, size=8)
boots.append(np.concatenate([y[fam == f] for f in pick]).mean())
lo, hi = np.percentile(boots, [2.5, 97.5])
print(f"baseline pass@1 {p:.3f}")
print(f"naive binomial 95% CI [{p-naive:.3f}, {p+naive:.3f}]")
print(f"family bootstrap 95% CI [{lo:.3f}, {hi:.3f}]")
It prints the baseline and both 95% intervals:
baseline pass@1 0.410
naive binomial 95% CI [0.342, 0.478]
family bootstrap 95% CI [0.290, 0.530]
The family bootstrap interval is about 1.8 times wider than the naive one. Recording the naive interval as the baseline would make ordinary family-to-family variation look like a training effect.
The held-out evaluation is a product with its own pipeline. Its families live in a separate task store that training jobs cannot read; their tasks, repositories and reference solutions are hashed and checked against every training store before a run, and evaluation assets carry canary strings. Images, sampling settings and seeds are pinned so that a score change can only come from the checkpoint. The evaluation runs on every promoted checkpoint, with results stored per family so that a regression in one family is not averaged away.
Evaluations decay and need audits of their own. OpenAI (2026) stopped reporting SWE-bench Verified after finding broken tests or specifications in many unsolved problems, and SWE-rebench collects fresh tasks continuously to reduce contamination. The choice of target also shapes what the environments must teach: Madan et al. (2026) found that the choice of training environment alone shifted held-out pass@1 by up to 11.4 points at matched budgets.
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): setup seeds a SQLite database in the sandbox, the reward inspects the final database, and 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: the reward checks for collateral damage; a failure to read state raises an error (an infrastructure outcome) instead of returning 0; and a validation hook runs on every version. For untrusted agents, grading should move to a fresh sandbox (Verifiers' isolated scoring mode).
A task is a tuple \(x=(\text{prompt}_x, s_0^x, R_x)\): an instruction, an initial world state and a reward. An episode \(\tau=(s_0^x,a_1,o_1,\dots,a_T,o_T)\) ends in state \(s_T\), and an end-state reward depends only on \(s_T\):
\[ R_x(\tau) = \mathbb{1}\big[g_x(s_T)\big]\cdot\prod_{j\notin J_x}\mathbb{1}\big[s_T^{\,j}=s_0^{x,j}\big], \]where \(g_x\) is the goal predicate on the target records \(J_x\) and the product forbids collateral changes to every other record. Because \(R_x\) ignores the path, an agent that makes a mistake and repairs it gets full credit, while a text-match reward would score such paraphrases and detours as false negatives.
The outcome space is \(\{0,1\}\cup\{\bot\}\), where \(\bot\) means the state could not be read. Episodes with \(\bot\) are excluded from group statistics instead of being scored 0. Validation asserts two properties of every task version: \(R_x\) of the gold end state equals 1, and \(R_x(s_0^x)=0\), so the untouched initial state does not pass.
The same refund task can be written without any framework, which makes its three habits visible: an end-state reward with a collateral check, an infrastructure error that is raised rather than scored, and a reset that rebuilds the world from a seed. The class below follows the reset(), step() and state() shape of an OpenEnv server, with SQL statements as actions against a fresh SQLite file, and replays four scripted policies plus a corrupted database.
import sqlite3, tempfile, os
SEED = """CREATE TABLE orders(id INTEGER PRIMARY KEY, status TEXT, refund REAL);
INSERT INTO orders VALUES (1042,'shipped',0),(1043,'shipped',0),(1044,'pending',0);"""
class InfraError(Exception): pass # environment broke: label, never score
class RefundEnv:
def __init__(self, order_id=1042, amount=19.99, max_steps=5):
self.order_id, self.amount, self.max_steps = order_id, amount, max_steps
def reset(self):
self.path = os.path.join(tempfile.mkdtemp(), "shop.db")
sqlite3.connect(self.path).executescript(SEED)
self.steps = 0
return f"Refund {self.amount} on order {self.order_id}; change nothing else."
def step(self, sql): # action = one SQL statement
self.steps += 1
con = sqlite3.connect(self.path)
try:
out = con.execute(sql).fetchall(); con.commit(); obs = str(out)
except sqlite3.Error as e:
obs = f"error: {e}" # tool error: agent's problem, visible to it
return obs, self.steps >= self.max_steps
def state(self):
try:
rows = sqlite3.connect(self.path).execute(
"SELECT id, status, refund FROM orders").fetchall()
except sqlite3.Error as e:
raise InfraError(str(e))
return {i: (s, r) for i, s, r in rows}
def reward(self):
rows = self.state()
ok = rows.get(self.order_id) == ("refunded", self.amount)
collateral = any(s == "refunded" for i, (s, _) in rows.items() if i != self.order_id)
return float(ok and not collateral)
POLICIES = {
"gold": ["UPDATE orders SET status='refunded', refund=19.99 WHERE id=1042"],
"null": [],
"collateral": ["UPDATE orders SET status='refunded', refund=19.99"],
"typo-then-fix": ["UPDATE order SET status='refunded'",
"UPDATE orders SET status='refunded', refund=19.99 WHERE id=1042"],
}
env = RefundEnv()
for name, actions in POLICIES.items():
env.reset()
for a in actions:
env.step(a)
print(f"{name:14s} reward={env.reward()}")
env.reset(); os.remove(env.path); open(env.path, "w").write("not a db")
try:
env.reward()
except InfraError as e:
print("broken state -> InfraError:", e)
It prints the reward for each scripted policy and the labelled infrastructure error:
gold reward=1.0
null reward=0.0
collateral reward=0.0
typo-then-fix reward=1.0
broken state -> InfraError: file is not a database
Refunding every order earns 0 because of the collateral check; a failed first statement followed by a correct one earns 1, since only the end state counts; and the unreadable database surfaces as InfraError, which an orchestrator maps to an infrastructure outcome code.
In a production fleet the environment is a versioned package: a task loader, a container image pinned by digest, setup and reward code, and a validation hook that runs in CI on every change. Libraries now provide most of the scaffolding. Verifiers exposes tasks, tasksets and rewards with an isolated scoring mode that grades in a fresh sandbox; OpenEnv serves an environment over HTTP; and Harbor packages terminal tasks with their tests. The choice matters less than keeping setup, grading and infrastructure errors separate.
Three costs dominate. Setup runs inside a sandbox for every episode, so seeding should be fast and dependency-light. Grading must not see anything the agent could have edited: hidden tests and reference data are injected only into the grading sandbox. And environment bugs are easy to mistake for capability limits: Docent (2025) found missing packages in a benchmark environment whose installation raised GPT-4o's solve rate from 68.6% to 78%. Writing one environment carefully, with its own tests, sets the template that later mined and synthesized environments are checked against.
3. Audit the Verifier Before Training
Before any RL step, run three kinds of solutions through every task: the gold solution (must pass), a null solution that does nothing (must fail), and a handful of adversarial ones written to game the check (edit tests, hard-code outputs, modify the database schema). 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).
Each kind of audit solution estimates a different verifier error. The gold solution tests for false negatives on a known-correct end state; the null solution tests for the trivial false positive \(R_x(s_0^x)=1\); adversarial solutions test for exploit false positives, the policy-dependent part of \(\alpha\) that grows during training. A task ships only when all three behave, which bounds the errors that can be found mechanically.
Reading real passes covers exploits nobody thought to write. If a fraction \(h\) of passing trajectories are exploits, the chance of seeing at least one in \(k\) independent reads is \(1-(1-h)^k\), so reaching confidence \(1-\delta\) requires
\[ k \ge \frac{\ln \delta}{\ln(1-h)} . \]For \(h=5\%\) and \(\delta=0.05\) that is 59 reads; for \(h=1\%\) it is 299. Conversely, zero exploits in \(k\) reads gives an approximate 95% upper bound of \(3/k\) on the exploit share (the rule of three), so a few dozen reads rule out only common exploits.
An audit harness runs a fixed battery of solutions against each verifier and refuses to ship a task unless gold passes and every other solution fails. The script below models a refund task as a dictionary state with an agent-writable test file, writes one sound verifier and one weak verifier that trusts the test file and checks only the order status, and audits both with gold, null and three adversarial solutions: editing the tests, refunding the wrong amount, and refunding every order.
import copy, math
S0 = {"orders": {1042: ["shipped", 0.0], 1043: ["shipped", 0.0]},
"tests": "assert orders[1042] == ['refunded', 19.99]"}
def good_verifier(s): # end state, exact amount, no collateral, tests ignored
o = s["orders"]
return float(o[1042] == ["refunded", 19.99] and o[1043][0] == "shipped")
def weak_verifier(s): # trusts the agent-writable test file and only checks status
return float("assert" not in s["tests"] or s["orders"][1042][0] == "refunded")
def gold(s): s["orders"][1042] = ["refunded", 19.99]
def null(s): pass
def edit_tests(s): s["tests"] = "pass"
def wrong_amount(s): s["orders"][1042] = ["refunded", 0.0]
def refund_all(s):
for k in s["orders"]: s["orders"][k] = ["refunded", 19.99]
def audit(verifier, adversarial=(edit_tests, wrong_amount, refund_all)):
run = lambda sol: (sol(st := copy.deepcopy(S0)), verifier(st))[1]
problems = []
if run(gold) != 1.0: problems.append("gold fails")
if run(null) != 0.0: problems.append("null passes")
problems += [f"{a.__name__} passes" for a in adversarial if run(a) != 0.0]
return ("ship" if not problems else "block", problems)
print("good:", audit(good_verifier))
print("weak:", audit(weak_verifier))
for h in (0.05, 0.01): # passes to read to see >=1 exploit with 95% probability
print(f"exploit share {h:.0%}: read {math.ceil(math.log(0.05) / math.log(1 - h))} passes")
It prints the shipping decision for each verifier and the number of passes to read:
good: ('ship', [])
weak: ('block', ['edit_tests passes', 'wrong_amount passes', 'refund_all passes'])
exploit share 5%: read 59 passes
exploit share 1%: read 299 passes
The weak verifier passes gold and fails null, so the two basic checks alone would have shipped it; only the adversarial solutions expose it.
Audits run as a CI job on every environment version, with a shared library of adversarial solutions (edit or delete tests, hard-code visible outputs, alter the schema, exit the harness with a success code) that grows each time a new exploit is found in training. Mutated-test variants in the style of ImpossibleBench serve as canaries: a task that cannot be solved honestly should never pass.
Reading is staffed work, supported by tools rather than replaced by them. Docent clusters long transcripts so reviewers can query them, and METR's MALT dataset gives labelled examples of reward hacking to calibrate monitors. LLM monitors are useful for triage but miss much SWE-scale cheating, and Baker et al. (2025) warn that optimizing a policy against a chain-of-thought monitor teaches it to hide intent, so monitors belong in the audit loop, not in the reward. Findings feed back into the verifier and into the adversarial library, and the environment's version is bumped.
4. Calibrate Difficulty with a Pass-Rate Sweep
Run the current policy \(n\) times per task and 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%, or at least one success in 64 or 128 rollouts, and suggest retiring tasks once they reach around 70%.
The filter below uses a confidence interval, routes never-solved tasks to a verifier audit (a 0% task may be broken rather than hard) and 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
For a task with \(c\) successes in \(n\) valid rollouts, the Wilson interval around \(\hat p=c/n\) is
\[ \frac{\hat p + \frac{z^2}{2n} \pm z\sqrt{\frac{\hat p(1-\hat p)}{n}+\frac{z^2}{4n^2}}}{1+\frac{z^2}{n}}, \]which, unlike the normal approximation, stays inside \([0,1]\) and is usable when \(c=0\) or \(c=n\). The sweep size follows from the floor. A task with \(p=0.03\) shows zero successes in \(n\) rollouts with probability \((1-p)^n\): 0.142 at \(n=64\) and 0.020 at \(n=128\), so a 2–3% floor needs 128 rollouts to be reliably told apart from an unsolvable task.
The value of a task to a group method is the chance of a mixed group, \(1-p^G-(1-p)^G\); over a pool with pass-rate distribution \(\pi\) the informative fraction is \(f_G = 1-\mathbb{E}_\pi[p^G+(1-p)^G]\), and filling \(B\) informative groups costs \(G B/f_G\) rollouts. The ceiling is a different argument: the Bernoulli variance \(p(1-p)\) falls as \(p\) rises, and a task at 70% now will be saturated after a few more checkpoints, so practitioners retire it before its sweep cost buys little signal.
A sweep turns per-task counts into decisions and should raise the share of informative groups in the training pool. The script below reuses the Wilson interval and classifier for a simulated pool of 1,000 tasks: a third nearly solved, a fifth unsolvable, and the rest spread across difficulties, with 4% of images crashing often. Each task gets 128 rollouts; infrastructure failures are counted apart, and the informative fraction at \(G=8\) is compared before and after filtering.
import math, numpy as np
from collections import Counter
rng = np.random.default_rng(2)
def wilson(c, n, z=1.96):
if n == 0: return 0.0, 1.0
p, d = c / n, 1 + z * z / n
mid = (p + z * z / (2 * n)) / d
half = 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(succ, valid, infra, min_n=64, ceiling=0.7, max_infra=0.05):
if infra / (valid + infra) > max_infra: return "fix-environment"
if valid < min_n: return "need-more-rollouts"
if succ == 0: return "audit-verifier"
return "retire" if wilson(succ, valid)[0] >= ceiling else "train"
mixed = lambda p, G: 1 - p**G - (1 - p)**G
# 1,000 tasks: a third already solved, a fifth unsolvable, the rest spread out
p = np.concatenate([rng.beta(20, 1, 330), np.zeros(200), rng.beta(1, 3, 470)])
flaky = rng.random(p.size) < 0.04 # 4% of images crash often
labels, keep = Counter(), []
for pi, f in zip(p, flaky):
infra = rng.binomial(128, 0.15 if f else 0.005)
succ = rng.binomial(128 - infra, pi)
lab = classify(succ, 128 - infra, infra)
labels[lab] += 1
if lab == "train": keep.append(pi)
print(dict(labels))
for name, pool in [("all tasks", p), ("train band", np.array(keep))]:
print(f"{name:10s} informative groups at G=8: {mixed(pool, 8).mean():.2f}")
It prints the count per decision and the informative fraction for the full pool and the kept band:
{'retire': 332, 'fix-environment': 33, 'train': 435, 'audit-verifier': 200}
all tasks informative groups at G=8: 0.44
train band informative groups at G=8: 0.74
Filtering raises the share of groups that carry gradient from 0.44 to 0.74, so the same batch of informative groups costs about 40% fewer rollouts. The 200 unsolvable tasks go to a verifier audit rather than being silently dropped, and the flaky images are sent back to their owners.
Production systems sweep twice. An offline sweep at acceptance drops tasks that are trivial or unsolved, often with a smaller model to save compute: INTELLECT-3 annotated datasets with a Qwen3-4B model's solve rate. An online filter then runs inside the rollout loop, because pass rates move with every update: DAPO's dynamic sampling over-samples and discards groups with identical rewards, and INTELLECT-3 kept easy, normal and hard pools by observed solve rate. RLVE goes further and adjusts each environment's difficulty parameter to the policy.
The per-task statistics are a table keyed by task version and policy version, updated from training rollouts as well as sweeps, with infrastructure outcomes stored separately. Stale estimates are the common failure: a pass-rate table from three checkpoints ago keeps sampling tasks the policy has already solved. A useful dashboard shows the histogram of group pass rates per environment family; a pile-up at 0 or 1 is the signal to re-sweep. Measures of usable advantage before training can also rank whole environments: Madan et al. (2026) report that they ordered environment pairs correctly about 78% of the time at 14B.
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, and 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.
The pilot is a three-part test. The training reward must rise: the mean reward over the last window exceeds the first by more than its noise. The held-out improvement \(\hat\Delta\) must be positive with a family-level confidence interval that excludes zero. And the exploit share among sampled rising-reward passes must be small: with \(e\) exploits in \(n\) reads, the upper Wilson bound on \(e/n\) should fall below a tolerance set in advance.
The gap \(g=\Delta_{\text{train}}-\Delta_{\text{eval}}\) between training-reward gain and held-out gain is the quantity the pilot watches. A large \(g\) with exploits present points to the verifier; a large \(g\) without exploits points to an environment too narrow to transfer or to infrastructure failures scored as rewards. Because scaling multiplies compute on the same environments and verifiers, any of these causes grows with scale rather than washing out.
The pilot's verdict can be computed from three logs: the training-reward curve, paired held-out results before and after training, and reviewers' exploit labels on sampled passes. The function below compares the first and last 50 steps of reward, bootstraps the held-out change by family, and checks the exploit share, then applies the rules in a fixed order. Three synthetic pilots exercise the three outcomes: a healthy run, a run whose evaluation does not move, and a run with exploits among its passes.
import numpy as np
rng = np.random.default_rng(3)
def family_boot_delta(before, after, fam, B=4000):
fams = np.unique(fam); d = after - before
stats = [np.concatenate([d[fam == f] for f in rng.choice(fams, fams.size)]).mean()
for _ in range(B)]
return d.mean(), np.percentile(stats, [2.5, 97.5])
def verdict(train_reward, before, after, fam, exploit_labels):
r_gain = train_reward[-50:].mean() - train_reward[:50].mean()
d, (lo, hi) = family_boot_delta(before, after, fam)
k, n = sum(exploit_labels), len(exploit_labels)
if r_gain <= 0.02: msg = "no learning: check difficulty band and group size"
elif k / n > 0.05: msg = "reward hacking: fix verifier before scaling"
elif lo <= 0: msg = "reward up, eval flat: suspect narrow env or mis-scored infra"
else: msg = "loop proven: scale"
return f"train +{r_gain:.2f}, eval {d:+.3f} CI[{lo:+.3f},{hi:+.3f}], exploits {k}/{n}: {msg}"
fam = np.repeat(np.arange(6), 40)
base = (rng.random(240) < 0.35).astype(float)
reward = np.clip(np.linspace(0.30, 0.55, 400) + rng.normal(0, 0.05, 400), 0, 1)
better = np.maximum(base, rng.random(240) < 0.12) # eval moves
flat = np.where(rng.random(240) < 0.5, base, rng.permutation(base)) # eval does not
print("A:", verdict(reward, base, better, fam, [0] * 40))
print("B:", verdict(reward, base, flat, fam, [0] * 39 + [1]))
print("C:", verdict(reward, base, better, fam, [0] * 34 + [1] * 6))
It prints one verdict line per pilot:
A: train +0.21, eval +0.125 CI[+0.104,+0.150], exploits 0/40: loop proven: scale
B: train +0.21, eval -0.013 CI[-0.079,+0.050], exploits 1/40: reward up, eval flat: suspect narrow env or mis-scored infra
C: train +0.21, eval +0.125 CI[+0.104,+0.150], exploits 6/40: reward hacking: fix verifier before scaling
Pilots B and C have identical training curves; only the held-out interval and the read passes tell them apart from the healthy run A.
A pilot is sized to answer its question cheaply: a calibrated task set from a handful of environment families, a modest group size, and enough steps for the training reward to move clearly. It runs the production code paths (the same sandbox fleet, gateway and verifier versions) so that a pass carries over to scale; a pilot on a bespoke stack proves little about the real one.
Two comparison runs make the result interpretable. A control run on general data without the new environments separates gains from the environments from gains any extra training would give. A second seed shows how much of the held-out change is run-to-run noise. During the pilot, reviewers read rising-reward trajectories every few hundred steps, and the infrastructure-failure rate is tracked per environment, because the reasons a pilot fails are the same as the production challenges: exploits like those METR (2025) documented, environment bugs read as capability, and environments that do not transfer. Environment choice is itself a large effect, so a failed pilot is often fixed by changing environments rather than hyperparameters.
6. Scale Environments, Then Infrastructure
Grow the number of environment families first (mined repositories, synthesized databases and tools, purchased replicas) with every new environment passing the same acceptance tests, then scale the run layer to match: snapshot-based images and warm pools, an asynchronous orchestrator with bounded staleness, and a gateway that records tokens. Vendors are fastest for high-fidelity replicas; mining and synthesis give breadth at lower unit cost.
Scaling environments is a question of mixture. With families \(f\) sampled at weights \(w_f\), the effective number of families is \(N_{\text{eff}}=1/\sum_f w_f^2\); capping each \(w_f\le w_{\max}\) guarantees \(N_{\text{eff}}\ge 1/w_{\max}\) and keeps a few templates from dominating. Szot et al. (2026) found that, as the data budget grows, tool and database diversity beats more tasks, which is an argument for raising \(N_{\text{eff}}\) before task counts.
Scaling the run layer is queueing. A synchronous step with \(B\) episodes of random duration \(T_i\) uses its slots for a fraction \(\mathbb{E}[T]/\mathbb{E}[\max_i T_i]\) of the step, which collapses for heavy-tailed \(T\). Asynchronous rollouts keep slots busy at the price of staleness, bounded by \(k-v(\tau)\le\eta\) between the trainer version \(k\) and the generating version \(v(\tau)\). Sandbox supply follows Little's law: with episode start rate \(\lambda\), hold time \(W\), provisioning delay \(D\) and lease failure rate \(\phi\), the pool needs about \(\lambda(W+D)/(1-\phi)\) sandboxes plus a buffer.
The cost of synchronous rollouts under heavy-tailed episode lengths, and what bounded staleness buys back, can be simulated in a few lines. The script draws log-normal episode durations, measures slot utilization when each step of 64 episodes waits for its slowest member, and runs an event-driven asynchronous loop in which slots refill immediately and the trainer steps every 64 finished episodes, discarding episodes more than \(\eta\) versions old.
import heapq, numpy as np
rng = np.random.default_rng(4)
dur = lambda n: rng.lognormal(0.0, 1.2, n) # heavy-tailed episode times (median 1)
B, STEPS = 64, 300
# synchronous: each step waits for the slowest of B episodes
d = dur((STEPS, B))
print(f"sync : slot utilization {d.sum() / (d.max(1).sum() * B):.2f}")
# asynchronous: B slots refill at once; trainer steps every B finished episodes
def run_async(eta):
ev = [(t, 0) for t in dur(B)]; heapq.heapify(ev)
version, buf, lags, dropped, now = 0, 0, [], 0, 0.0
while version < STEPS:
now, v0 = heapq.heappop(ev)
lag = version - v0
if lag > eta: dropped += 1 # too stale: discard
else:
lags.append(lag); buf += 1
if buf == B: version, buf = version + 1, 0
heapq.heappush(ev, (now + dur(1)[0], version))
return np.mean(lags), dropped / (len(lags) + dropped), now
for eta in (1, 4):
lag, drop, T = run_async(eta)
print(f"async eta={eta}: mean staleness {lag:.2f} steps, dropped {drop:.1%}, "
f"wall-clock vs sync {T / d.max(1).sum():.2f}")
It prints synchronous utilization and, for two staleness bounds, the mean staleness, the share of discarded episodes and the relative wall-clock time:
sync : slot utilization 0.11
async eta=1: mean staleness 0.41 steps, dropped 14.9%, wall-clock vs sync 0.13
async eta=4: mean staleness 0.75 steps, dropped 2.9%, wall-clock vs sync 0.11
Under this tail, synchronous slots are busy about 11% of the time. The asynchronous loop finishes the same number of steps in an eighth to a ninth of the wall-clock time; a tight bound \(\eta=1\) discards about 15% of episodes, and \(\eta=4\) keeps almost all of them with mean staleness under one step.
Environment supply comes from three channels with different economics. Mining repositories gives realistic code tasks at scale; synthesis of databases and tools gives breadth at low unit cost; and vendors build high-fidelity replicas of real applications, at up to hundreds of thousands of dollars each. Published programs are large: MiniMax Forge used more than 100,000 distinct scaffolds and environments, and Prime Intellect reports 365,000+ environments for SWE, terminal and search. Every new environment passes the same acceptance tests and decontamination as the first.
The run layer then scales to match. DSec runs more than 380,000 concurrent sandboxes with lazily loaded images and snapshot preemption; GKE Agent Sandbox places images before rollouts ask for them. Asynchronous trainers such as AReaL and PipelineRL bound staleness, and RollPacker targets tails where the longest responses were 25–32 times the median. A token gateway returns sampled ids and log-probabilities so the trainer can correct for the inference/training mismatch. The common failure at this stage is scaling the fleet before the curation and acceptance pipeline, which produces more rollouts on worse tasks.
7. Operate the Program
Once training runs continuously, the work becomes operations. Track reward, pass rate, episode length, tool-error rate and infra-failure rate per environment version (see Observability and Data Quality); re-run the pass-rate sweep at each checkpoint and retire saturated tasks; pin and re-validate environments when dependencies change; and add held-out families as training families grow, so that the evaluation keeps measuring transfer rather than familiarity.
Operating the program is sequential testing on per-version statistics. For an environment version with \(f\) infrastructure failures in \(n\) episodes, an alert fires when the lower Wilson bound on \(f/n\) exceeds a limit (5% in the curation rule), which avoids paging on a few failures in a small sample. Canary tasks replayed with gold solutions should pass with probability 1, so a single canary failure on a new build is evidence of drift, not noise.
Re-weighting follows the curation quantities: a family's useful share is its informative fraction \(f_{G,f}\), and weights \(w_f\propto f_{G,f}\), capped at \(w_{\max}\), move sampling toward families still producing gradient. Transfer is tracked as the familiarity gap \(S_{\text{in-family}}-S_{\text{held-out}}\) between held-out tasks from trained families and held-out families; a widening gap signals that new held-out families are needed.
The launch criteria are a conjunction of predicates over registry evidence: evaluation families disjoint from training families with a baseline interval; complete version pins; gold passing and null and adversarial solutions failing; isolation; a finished sweep with zero-pass tasks audited; infrastructure codes excluded from rewards; a passing token replay test; no open evaluation overlaps; stable canaries; and a pilot that moved the evaluation. The first large run starts only when every predicate holds.
The launch checklist is most useful as code that reads evidence from the registry and names the items that block a run, and the same registry feeds per-version alerts afterwards. The script below encodes ten launch gates (evaluation, registry pins, verifier audit, isolation, difficulty, infrastructure outcomes, token capture, decontamination, reproducibility and exit criteria) as predicates, evaluates them on one evidence record, and then applies a Wilson-bound infrastructure alert to three environment versions.
import math
GATES = { # launch item -> predicate over registry evidence
"evaluation": lambda e: e["heldout_families"] and not (e["heldout_families"] & e["train_families"]) and e["baseline_ci"],
"registry": lambda e: all(k in e["pins"] for k in ("image_digest", "tools", "verifier", "taskset", "limits", "owner")),
"verifier_audit": lambda e: e["gold_pass"] == 1.0 and e["null_pass"] == 0 and e["adv_pass"] == 0 and e["reads"] >= 30,
"isolation": lambda e: e["hidden_tests_in_sandbox"] is False and e["egress"] == "allowlist" and not e["secrets_in_image"],
"difficulty": lambda e: e["sweep_done"] and e["unaudited_zero_pass"] == 0,
"infra_outcomes": lambda e: e["infra_codes_excluded_from_reward"],
"token_capture": lambda e: e["replay_test_passed"],
"decontamination": lambda e: e["eval_overlaps_open"] == 0,
"reproducibility": lambda e: e["canary_replay_stable"],
"exit_criteria": lambda e: e["pilot_moved_eval"] and e["retire_rules_written"],
}
ev = dict(heldout_families={"sql-billing", "crm"}, train_families={"sql-shop", "crm"},
baseline_ci=(0.29, 0.53), pins={"image_digest", "tools", "verifier", "taskset", "limits", "owner"},
gold_pass=1.0, null_pass=0, adv_pass=0, reads=40, hidden_tests_in_sandbox=False,
egress="allowlist", secrets_in_image=False, sweep_done=True, unaudited_zero_pass=3,
infra_codes_excluded_from_reward=True, replay_test_passed=True, eval_overlaps_open=0,
canary_replay_stable=True, pilot_moved_eval=True, retire_rules_written=True)
print("blocked by:", [g for g, ok in GATES.items() if not ok(ev)])
def page_on_infra(fail, total, limit=0.05, z=2.33): # Wilson lower bound above limit
p, d = fail / total, 1 + z * z / total
lo = ((p + z * z / (2 * total)) - z * math.sqrt(p * (1 - p) / total + z * z / (4 * total**2))) / d
return lo > limit
for ver, f, n in [("shop@v7", 9, 400), ("shop@v8", 41, 400), ("crm@v3", 3, 20)]:
print(ver, f"{f}/{n}", "PAGE" if page_on_infra(f, n) else "ok")
It prints the blocking gates and one alert decision per environment version:
blocked by: ['evaluation', 'difficulty']
shop@v7 9/400 ok
shop@v8 41/400 PAGE
crm@v3 3/20 ok
The run is blocked because one family appears in both the training and held-out sets and three zero-pass tasks have not been audited. The alert pages for shop@v8 (about 10% failures over 400 episodes) but not for crm@v3, whose 3 failures in 20 episodes are too few to separate from the limit.
A continuously running program is staffed like a service. Dashboards per environment version show reward, pass rate, episode length, tool-error rate and infrastructure-failure rate, with alerts routed to the environment's owner; a platform on-call handles fleet incidents; and a trajectory review queue is read every day, with findings filed against environments. Logging conventions such as Tinker's RL outputs make these slices cheap to build.
Before the first large run, each launch item should be true with evidence linked in the registry: target and baseline with error bars; held-out families absent from training stores; every version pinned with an owner; verifier audit and human reading done; hidden tests outside the agent sandbox, egress allowlisted and no credentials in images; sweep done and zero-pass tasks audited; infrastructure outcomes excluded from rewards; a token replay test passed; decontamination done; canaries stable; and exit criteria written. After launch, dependency changes trigger re-validation and a version bump, sweeps re-run at each checkpoint, saturated tasks retire, and new held-out families are added as training families grow.
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) found that the choice of training environment shifted held-out pass@1 by up to 11.4 points at matched token budgets for Qwen3 models from 1.7B to 14B, and that 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, and 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, and whether environment vendors become durable businesses or a function absorbed by labs, as the 2026 acquisitions hint.
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:
@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
- 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
- Prime Intellect. "Environments Hub: A Community Hub To Scale RL To Open AGI." Prime Intellect blog 2025. primeintellect.ai/blog/environments
- Spisak, Joseph, et al. "Building the Open Agent Ecosystem Together: Introducing OpenEnv." Hugging Face blog 2025. huggingface.co/blog/openenv
- NVIDIA. "NVIDIA Debuts Nemotron 3 Family of Open Models." NVIDIA press release 2025. investor.nvidia.com/…/NVIDIA-Debuts-Nemotron-3
- Harbor Framework Team. "Harbor: A framework for evaluating and optimizing agents and models." GitHub 2026. github.com/harbor-framework/harbor
- Terminal-Bench team. "Terminal-Bench 2.0 and Harbor." tbench.ai news 2025. tbench.ai/news/announcement-2-0
- Anthropic. "Introducing the Model Context Protocol." Anthropic news 2024. anthropic.com/news/model-context-protocol
- DeepSeek-AI. "DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning." arXiv 2501.12948, 2025. arxiv.org/abs/2501.12948
- Lambert, Nathan, et al. "Tülu 3: Pushing Frontiers in Open Language Model Post-Training." arXiv 2411.15124, 2024. arxiv.org/abs/2411.15124
- Brockman, Greg, et al. "OpenAI Gym." arXiv 1606.01540, 2016. arxiv.org/abs/1606.01540
- Towers, Mark, et al. "Gymnasium: A Standard Interface for Reinforcement Learning Environments." arXiv 2407.17032, 2024. arxiv.org/abs/2407.17032
- Bellemare, Marc G., et al. "The Arcade Learning Environment: An Evaluation Platform for General Agents." JAIR 2013. arxiv.org/pdf/1207.4708
- Todorov, Emanuel, Tom Erez, and Yuval Tassa. "MuJoCo: A physics engine for model-based control." IROS 2012. ieeexplore.ieee.org/document/6386109
- Tassa, Yuval, et al. "DeepMind Control Suite." arXiv 1801.00690, 2018. arxiv.org/abs/1801.00690
- Cobbe, Karl, et al. "Leveraging Procedural Generation to Benchmark Reinforcement Learning." arXiv 1912.01588, 2019. arxiv.org/abs/1912.01588
- 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
- Küttler, Heinrich, et al. "The NetHack Learning Environment." NeurIPS 2020. arxiv.org/abs/2006.13760
- Stojanovski, Zafir, et al. "Reasoning Gym: Reasoning Environments for Reinforcement Learning with Verifiable Rewards." arXiv 2505.24760, 2025. arxiv.org/abs/2505.24760
- Shi, Tianlin, et al. "World of Bits: An Open-Domain Platform for Web-Based Agents." ICML 2017. proceedings.mlr.press/v70/shi17a
- Yao, Shunyu, et al. "WebShop: Towards Scalable Real-World Web Interaction with Grounded Language Agents." arXiv 2207.01206, 2022. arxiv.org/abs/2207.01206
- Zhou, Shuyan, et al. "WebArena: A Realistic Web Environment for Building Autonomous Agents." arXiv 2307.13854, 2023. arxiv.org/abs/2307.13854
- 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
- Chen, Mark, et al. "Evaluating Large Language Models Trained on Code." arXiv 2107.03374, 2021. arxiv.org/abs/2107.03374
- Jimenez, Carlos E., et al. "SWE-bench: Can Language Models Resolve Real-World GitHub Issues?" arXiv 2310.06770, 2023. arxiv.org/abs/2310.06770
- Pan, Jiayi, et al. "Training Software Engineering Agents and Verifiers with SWE-Gym." arXiv 2412.21139, 2024. arxiv.org/abs/2412.21139
- 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
- Yang, John, et al. "SWE-smith: Scaling Data for Software Engineering Agents." arXiv 2504.21798, 2025. arxiv.org/abs/2504.21798
- DeepSeek-AI. "DeepSeek-V3.2: Pushing the Frontier of Open Large Language Models." arXiv 2512.02556, 2025. arxiv.org/abs/2512.02556
- Wang, Zhaoyang, et al. "Agent World Model: Infinity Synthetic Environments for Agentic Reinforcement Learning." arXiv 2602.10090, 2026. arxiv.org/abs/2602.10090
- 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
- Wang, Ruoyao, et al. "ScienceWorld: Is your Agent Smarter than a 5th Grader?" EMNLP 2022. arxiv.org/abs/2203.07540
- Model Context Protocol. "Tools." MCP Specification, version 2025-11-25. modelcontextprotocol.io/specification/2025-11-25/server/tools
- NVIDIA. "Harbor (agent interactions)." NeMo Gym documentation 2026. docs.nvidia.com/nemo/gym/agent-interactions/harbor
- OpenEnv contributors. "Harbor Environment." OpenEnv documentation 2026. huggingface.co/docs/openenv/main/en/environments/harbor
- Prime Intellect. "Verifiers v1" (release announcement thread). 2026. threadreaderapp.com/thread/2076447247693402301
- Hugging Face. "The Open Source Community is backing OpenEnv for Agentic RL." Hugging Face Blog 2026. huggingface.co/blog/openenv-agentic-rl
- OpenEnv contributors. "OpenEnv: Agentic Execution Environments." OpenEnv documentation 2026. huggingface.co/docs/openenv
- General Reasoning. "The Open Reward Standard." 2026. gr.inc/releases/the-open-reward-standard
- Lacoste, A., et al. "CUBE: A Standard for Unifying Agent Benchmarks." arXiv 2026. arxiv.org/abs/2603.15798
- NVIDIA. "RL Environment Ecosystem." NeMo Gym documentation 2026. docs.nvidia.com/nemo/gym/0.2.0/about/ecosystem
- NovaSky AI. "SkyRL-Gym." PyPI 2026. pypi.org/project/skyrl-gym
- Liu, Z., Sims, A., Duan, K., et al. "GEM: A Gym for Agentic LLMs." arXiv 2025. arxiv.org/abs/2510.01051
- Nous Research. "Atropos: An Environment and Rollout handler for LLM RL." PyPI 2026. pypi.org/project/atroposlib
- Zeng, Z., et al. "RLVE: Scaling Up Reinforcement Learning for Language Models with Adaptive Verifiable Environments." arXiv 2025. arxiv.org/abs/2511.07317
- Burtenshaw, B., et al. "Welcome RL Environments to the hub." Hugging Face Blog 2026. huggingface.co/blog/rl-environments
- 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
- Gunjal, A., et al. "Rubrics as Rewards: Reinforcement Learning Beyond Verifiable Domains." arXiv 2025. arxiv.org/abs/2507.17746
- Trivedi, H., et al. "AppWorld: A Controllable World of Apps and People for Benchmarking Interactive Coding Agents." ACL 2024. arxiv.org/abs/2407.18901
- 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
- METR. "Recent Frontier Models Are Reward Hacking." METR Blog 2025. metr.org/blog/2025-06-05-recent-reward-hacking
- Zhong, Z., Raghunathan, A., Carlini, N. "ImpossibleBench: Measuring LLMs' Propensity of Exploiting Test Cases." arXiv 2025. arxiv.org/abs/2510.20270
- 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
- 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
- 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
- Prime Intellect. "Scaling Agentic RL: 365,000+ Environments for SWE, Terminal, and Search." Prime Intellect blog 2026. primeintellect.ai/blog/scaling-agentic-rl
- 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
- Cai, S., Fang, R., Wu, J., et al. "AutoForge: Automated Environment Synthesis for Agentic Reinforcement Learning." arXiv 2025. arxiv.org/abs/2512.22857
- 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
- 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
- Kimi Team. "Kimi K2: Open Agentic Intelligence." arXiv 2025. arxiv.org/html/2507.20534v2
- 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
- Li, Y., Inan, H. A., Yue, X., et al. "Simulating Environments with Reasoning Models for Agent Training." arXiv 2025. arxiv.org/abs/2511.01824
- Chen, Z., Zhao, Z., Zhang, K., et al. "Scaling Agent Learning via Experience Synthesis." ICLR 2026. arxiv.org/abs/2511.03773
- Qian, C., Liu, Z., Prabhakar, A., et al. "UserRL: Training Interactive User-Centric Agent via Reinforcement Learning." arXiv 2025. arxiv.org/abs/2509.19736
- 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
- OpenAI. "Introducing SWE-bench Verified." OpenAI 2024. openai.com/index/introducing-swe-bench-verified
- 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
- 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
- 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
- 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
- Prime Intellect. "Prime Sandboxes." Prime Intellect Blog 2026. primeintellect.ai/blog/sandboxes
- Liu, J., Frye, C. & Walters, P. "Reinforcement learning is an infrastructure problem." Modal Blog 2026. modal.com/blog/reinforcement-learning-infrastructure-problem
- Yan, Y., Wang, H., et al. "Sandman: A Sandbox Service for Production Agentic Reinforcement Learning." arXiv 2610.39711, 2026. arxiv.org/pdf/2610.39711
- 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
- Gupta, A. & Lian, L. "Firecracker – Lightweight Virtualization for Serverless Computing." AWS Open Source Blog 2018. aws.amazon.com/blogs/opensource/firecracker…
- gVisor Authors. "Releasing Systrap: A high-performance gVisor platform." gVisor Blog 2023. gvisor.dev/blog/2023/04/28/systrap-release
- Kata Containers. "Kata Containers Architecture." GitHub documentation. github.com/kata-containers/…/architecture.md
- 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
- Wikipedia. "Little's law." en.wikipedia.org/wiki/Little's_law
- verl Team. "Agent Loop." verl documentation. verl.readthedocs.io/…/agent_loop.html
- THUDM. "slime: an LLM post-training framework for RL scaling." GitHub. github.com/THUDM/slime
- NovaSky-AI. "SkyRL: A Modular Full-stack RL Library for LLMs." GitHub. github.com/NovaSky-AI/SkyRL
- 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
- 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
- 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
- Kimi Team. "Kimi k1.5: Scaling Reinforcement Learning with LLMs." arXiv 2501.12599, 2025. arxiv.org/html/2501.12599
- OpenEnv. "Harbor environments." OpenEnv documentation 2026. openenv.github.io/OpenEnv/main/environments/harbor
- 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
- Miles Team (Li, J., et al.). "No Token Left Behind." LMSYS Blog 2026. lmsys.org/blog/2026-05-13-no-token-left-behind
- NVIDIA. "On-Policy Corrections for OpenAI-compatible HTTP servers." NeMo Gym documentation. docs.nvidia.com/nemo/gym/…/on-policy-correction
- Gallouédec, Q. & Rasul, K. "Agentic RL: Token-In, Token-Out Done Right." Hugging Face Blog 2026. huggingface.co/blog/huggingface/tito
- 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
- verl Team. "Rollout Correction." verl documentation. verl.readthedocs.io/…/rollout_corr.html
- NitroBox. "nitrobox: Lightweight Linux namespace sandbox with persistent shell and instant reset." PyPI package documentation 2026. pypi.org/project/nitrobox
- 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
- NVIDIA. "Agent Trajectory Interchange Format (ATIF) v1.7." NeMo Gym documentation 2026. docs.nvidia.com/nemo/gym
- DeepSeek-AI. "DeepSeek-V4: Towards Highly Efficient Million-Token Context Intelligence." arXiv 2026. arxiv.org/html/2606.19348
- Prime Intellect. "INTELLECT-3: Technical Report." arXiv 2025. arxiv.org/abs/2512.16144
- Terminal-Bench team. "Terminal-Bench 2.1." tbench.ai news, May 2026. tbench.ai/news/terminal-bench-2-1
- Buchanan, E. K., Linderman, S., Ré, C. "Benchmarks as Software: A Case Study on Terminal-Bench." ICML 2026. icml.cc/virtual/2026/82793
- 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
- 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
- Lu, K. "On-Policy Distillation." Thinking Machines Lab blog 2025. thinkingmachines.ai/blog/on-policy-distillation
- Thinking Machines Lab. "RL Training Outputs (RL logging)." Tinker documentation 2026. tinker-docs.thinkingmachines.ai
- METR. "MALT: A Dataset of Natural and Prompted Behaviors." METR blog 2025. metr.org/blog/2025-10-14-malt
- 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
- Steinhardt, J. (Transluce). "Analyzing Long Agent Transcripts (Docent)." LessWrong 2025. lesswrong.com/posts/Mj276hooL3Mncs3uv
- OpenAI. "Why We No Longer Evaluate SWE-bench Verified." OpenAI 2026. openai.com/index/why-we-no-longer-evaluate-swe-bench-verified
- Prime Intellect. "INTELLECT-3." Prime Intellect blog, Nov 2025. primeintellect.ai/blog/intellect-3
- Kimi Team. "Kimi K2.5: Visual Agentic Intelligence." arXiv 2026. arxiv.org/abs/2602.02276
- GLM-5 Team (Zhipu AI). "GLM-5: from Vibe Coding to Agentic Engineering." arXiv 2026. arxiv.org/html/2602.15763
- MiniMax. "Forge: Scalable Agent RL Framework and Algorithm." MiniMax news, Feb 2026. minimax.io/news/forge-scalable-agent-rl-framework-and-algorithm
- Hugging Face. "DeepSeek-V4: a million-token context that agents can actually use." Hugging Face blog, Apr 2026. huggingface.co/blog/deepseekv4
- Tongyi DeepResearch Team. "Tongyi DeepResearch Technical Report." arXiv 2025. arxiv.org/pdf/2510.24701
- 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
- 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
- Orrick. "Mercor Acquires Sepal AI." Orrick news, Feb 2026. orrick.com/en/News/2026/02/Mercor-Acquires-Sepal-AI
- SiliconANGLE. "Mercor buys Deeptune to build training environments for AI agents." SiliconANGLE, Jul 2026. siliconangle.com/2026/07/09/mercor-buys-deeptune
- Fortune. "Halluminate raises $30 million Series A." Fortune, Oct 2026. fortune.com/2026/10/01/halluminate-raises-30-million-series-a
- 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
- Prime Intellect. "verifiers: environments for LLM reinforcement learning." GitHub. github.com/PrimeIntellect-ai/verifiers
- Madan, V., et al. "Which Environments Should LLMs Learn From? Predicting RL Utility Across Four Scales." NeurIPS 2026. neurips.cc/virtual/2026/164478
- Shao, Zhihong, et al. "DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models." arXiv 2024. arxiv.org/abs/2402.03300
- Farama Foundation. "Gymnasium's Vector Autoreset Mode." Farama blog 2025. farama.org/Vector-Autoreset-Mode
- Cai, X.-Q., Wang, W., Liu, F., Liu, T., Niu, G., Sugiyama, M. "Reinforcement Learning with Verifiable yet Noisy Rewards under Imperfect Verifiers." arXiv 2025. arxiv.org/abs/2510.00915
- Viswanathan, V., et al. "Checklists Are Better Than Reward Models For Aligning Language Models." NeurIPS 2025. arxiv.org/abs/2507.18624
- Zhao, Y., Liu, H., Yu, D., et al. "One Token to Fool LLM-as-a-Judge." NeurIPS 2025. arxiv.org/abs/2507.08794
- Gao, L., Schulman, J., Hilton, J. "Scaling Laws for Reward Model Overoptimization." ICML 2023. arxiv.org/abs/2210.10760
- Skalse, J., Howe, N. H. R., Krasheninnikov, D., Krueger, D. "Defining and Characterizing Reward Hacking." NeurIPS 2022. arxiv.org/abs/2209.13085
- Cursor. "Reward hacking in coding benchmarks." Cursor blog 2026. cursor.com/blog/reward-hacking-coding-benchmarks
- Broder, A. Z. "On the Resemblance and Containment of Documents." Compression and Complexity of Sequences 1997. doi.org/10.1109/SEQUEN.1997.666900
- Lee, K., Ippolito, D., Nystrom, A., Zhang, C., Eck, D., Callison-Burch, C., and Carlini, N. "Deduplicating Training Data Makes Language Models Better." ACL 2022. arxiv.org/abs/2107.06499
- Khatri, Devvrit, Lovish Madaan, Rishabh Tiwari, Rachit Bansal, Sai Surya Duvvuri, Manzil Zaheer, Inderjit S. Dhillon, David Brandfonbrener, and Rishabh Agarwal. "The Art of Scaling Reinforcement Learning Compute for LLMs." arXiv 2025. arxiv.org/abs/2510.13786
- Qin, Ruoyu, et al. "Seer: Online Context Learning for Fast Synchronous LLM Reinforcement Learning." arXiv 2025. arxiv.org/abs/2511.14617
- He, H., and Thinking Machines Lab. "Defeating Nondeterminism in LLM Inference." Connectionism (blog), Sep 2025. thinkingmachines.ai/blog/defeating-nondeterminism-in-llm-inference
- Li, Y., Xu, J., Liu, J., Tong, Y., Li, Z., Cai, T., Zhang, G., Liu, Q., & Wang, B. "Taming the Tail: Stable LLM Reinforcement Learning via Dynamic Vocabulary Pruning." 2025. arxiv.org/abs/2512.23087
- Bai, Y., & Shen, A. "Finish RL Training Faster: Bitwise-Consistent, High-Performance, Agent-Driven." vLLM Blog, Oct 2026. vllm.ai/blog/2026-10-14-train-inference-consistency
- Ross, Stéphane, Geoffrey J. Gordon, and J. Andrew Bagnell. "A Reduction of Imitation Learning and Structured Prediction to No-Regret Online Learning." AISTATS 2011. arxiv.org/abs/1011.0686
- Agarwal, Rishabh, et al. "On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes." ICLR 2024. arxiv.org/abs/2306.13649
- Cobbe, Karl, et al. "Training Verifiers to Solve Math Word Problems." arXiv 2021. arxiv.org/abs/2110.14168
- Schulman, J. "Approximating KL Divergence." Blog post 2020. joschu.net
- Broder, A. Z. "On the resemblance and containment of documents." Compression and Complexity of Sequences 1997. cs.princeton.edu/…/broder97resemblance.pdf
- Miller, E. "Adding Error Bars to Evals: A Statistical Approach to Language Model Evaluations." 2024. arxiv.org/abs/2411.00640