A coding model earns its reward when tests pass inside a sandbox. A lazy grader pays full reward for a shortcut. Pick a patch and a grader, then watch one shortcut score 1.0 or 0.
Learn how a coding post-training team builds the boxes, the tasks and the reward signals that coding agents train and are tested against.
Pick a patch, then switch the grader between Naive and Guarded. Watch which tests run and what reward comes back. Then we build, piece by piece, the episode, the task sources, the sandbox, the rewards, the traps and the throughput math.
You need a little Python and the idea of a unit test (a small program that checks one behaviour and says pass or fail). We build the rest from zero.
Built from eight papers: SWE-bench, SWE-Gym, R2E-Gym, SWE-smith, SWE-RL, SWE-rebench, LiveCodeBench and AlphaCode. Every number below comes from their abstracts or is marked illustrative.
Illustrative toy: a function parse_age crashes on empty input. Eight tests: two must flip from fail to pass, two are held-out variants of them, four must keep passing. The reward is 1.0 only if every test that runs passes. The naive grader runs the six tests in the repo after the patch; the guarded grader restores the tests from a clean copy and adds the held-out two.
Chapter 0
See why a coding model can only learn from a number a machine computes, and why that number must come from a box you control
A teammate files a bug report. The function parse_age should turn the text “42” into the number 42. It should return None for blank text, for negative numbers and for words. Today it crashes on a blank string. A coding model reads the report and, four seconds later, hands back a patch.
Is the patch right? You could read it. Reading works for one patch. A training run judges millions of them, and no team has enough readers. Something has to judge each patch by itself, and it has to be right most of the time.
Below are four patches for this one bug, and five small tests. A test is a short program that calls your code with one input and checks the output. It says pass or fail. Read a patch, guess whether it passes all five tests, then run them.
Pick a patch and read it. Press a guess button. The five tests then run and your guess is scored. Try all four.
Illustrative: four short patches for a made-up function, with the five test results worked out by hand. The tests are: “42” gives 42, “ 7 ” gives 7, a blank string gives None, “-3” gives None, “abc” gives None.
Patch A looks short and clean, and it fails two tests. Patch D looks sloppy, and it passes all five. Eyes got at least one of these wrong, and so does almost everyone. The code has to run.
Now the plan. We want to train a coding model. The method is reinforcement learning, or RL: the model tries something, gets a number back, and shifts its weights (the stored numbers that make it work) so that attempts like the high-scoring ones become more likely. Think of training a dog with treats. The dog needs the treat to arrive right after the trick, every time, for the same trick.
RL has three named parts. The agent is the model that acts: it reads, runs commands and writes code. The environment is everything the agent acts on and gets answers from: the code, the shell, the files, the test runner. The reward is the number that comes back at the end. In coding, the reward usually comes from running tests.
One thing makes this lesson matter. The model can only learn what the reward measures. If the reward pays for a patch that deletes the failing tests, the model learns to delete tests. The model does not know your intent. It follows the number.
Running a model’s patch means running code nobody has read. That code might loop forever, fill the disk or try to reach the network. So the tests run inside a sandbox: an isolated box with its own files, its own limits and no way out. If the code misbehaves, you throw the box away.
The same box serves two jobs. In training, the reward feeds back into the weights. In evaluation (an eval), the reward is only recorded, and it tells you how good the model is. A post-training team builds one environment and uses it for both. That is why a flaw in the environment is expensive. It ruins the training signal and the score you read afterwards.
The rest of the lesson takes the environment apart, piece by piece. First, one whole episode, with the real records that flow through it. Then where the tasks come from, because someone has to write thousands of bugs with tests. Then the box, the tests as rewards, other reward signals, and the ways agents cheat. Last come two measurement problems (flaky tests and stale benchmarks) and the arithmetic of running thousands of boxes at once.
The instrument at the top of the page gave you a first look at the central problem. A naive grader let three different shortcuts score 1.0. A guarded grader paid each of them 0. Every chapter below adds one part of that guard.
Chapter 1
Follow one coding attempt from a clean repo to a reward, and read the real records that pass between the agent, the box and the grader
A training machine wakes up and picks a task off a shelf. A moment later a fresh box holds a code repository, frozen at one old commit. The agent has a bug report and a shell. It has no human to ask. Seven steps later, a number comes back, and the box is deleted.
That whole story is one episode: a single attempt at a single task, from the first message to the final reward. Reinforcement learning (RL) learns from thousands of them. So we start by looking at one in full detail.
A task is a small data record. It names a repository and a commit (a saved snapshot of all the files, with an ID like 9f3c1ab). It holds the bug report, called the problem statement. It also holds things the agent must never see: the human’s fix, and the tests that check the agent’s work. The field names below follow the public SWE-bench dataset; the values are made up.
json{ "instance_id": "people__age-212", "repo": "example/people", "base_commit": "9f3c1ab", "problem_statement": "parse_age('') raises ValueError. It should return None.", "patch": "diff --git a/src/people/age.py ...", # the human fix: hidden "test_patch": "diff --git a/tests/test_age.py ...", # the new tests: hidden "FAIL_TO_PASS": ["test_blank_age"], "PASS_TO_PASS": ["test_valid_age", "test_zero_age", "test_big_age"] }
Two lists end the record. FAIL_TO_PASS names tests that fail before the fix and must pass after it. PASS_TO_PASS names tests that pass before the fix and must still pass after it. Chapter 4 explains why both lists exist.
Now the loop. First the environment resets: it builds a fresh box and checks out the base commit. Then the agent sees the problem statement. It answers with one tool call: a small structured request, such as “run this shell command” or “replace this text in that file”. The box runs the call and returns an observation, which is the output. The call and the observation are both added to the agent’s context, and the agent goes again.
The loop ends when the agent calls submit or runs out of steps. Then the box computes the patch: the difference between the files now and the files at the base commit. A grader runs the hidden tests against that patch and returns the reward. Step through one episode below. Watch the context grow and notice when the reward arrives.
Each dot is one step. The box shows what the agent sent and what came back. Press Next step or Play, or tap a step label.
Illustrative: the records follow the shape of common agent tool calls, not one product’s exact format. Token counts are made up: 650 tokens for the system prompt and the bug report, then roughly 250 to 600 per step. The reward is binary here: 1.0 if every listed test passes, else 0.
Look at who knows what. The agent sees the problem statement, the repo and its own tool results. It does not see patch, test_patch or the two test lists. The grader sees all of them. The wall between the two is the most important design rule in this lesson. Every cheat in Chapter 6 is a way to cross that wall.
Notice step 5. The agent ran the three tests it could see, and all three passed. That tells it nothing about the hidden test_blank_age. Only step 7 shows whether the bug is truly fixed. An agent that trusts its own tests can be wrong. An agent that never tests is worse.
The reward arrives once, at the end. Steps 1 to 6 get no score of their own. RL must spread the final 1.0 over everything the agent did: the search, the edit, the test run. This is the credit assignment problem: which of the seven choices earned the reward? With thousands of episodes, the good habits show up more often in the high-scoring ones, and the training signal pushes those up.
The episode as code is short. Here is the loop a researcher writes. Everything on the sandbox and grader side is a stub for now; Chapters 3 and 4 fill it in.
pythondef run_episode(policy, task, sandbox, max_steps=50): sandbox.reset(task["base_commit"]) # fresh box, old commit messages = [SYSTEM_PROMPT, {"role": "user", "content": task["problem_statement"]}] for step in range(max_steps): action = policy(messages) # text in, one tool call out if action["tool"] == "submit": break obs = sandbox.run(action) # the tool runs INSIDE the box messages += [action, obs] # the history is the next input patch = sandbox.diff() # files now minus files at the base commit reward = grade(task, patch) # hidden tests, in a clean box return messages, patch, reward
Here is the first failure mode. Symptom: a large share of your episodes score 0, and the logs show the agent looking around and never editing. Measurement: plot a histogram of steps per episode. If a spike sits at exactly max_steps, the agent was cut off before it submitted. If the spike is at 50 and the median successful run takes 12, the cap is not the real problem. The agent is lost.
Fix: look at the first ten steps of the lost runs. Often the issue text is vague, or a search tool prints thousands of lines and fills the context. Clip tool output (for example, to 2,000 characters), give a clear budget in the system prompt, and drop tasks where no run in a sample of eight ever submits. A task that no run can finish teaches nothing. It only burns compute.
Chapter 2
Compare the four ways teams manufacture thousands of bugs with tests, and see what each one costs and what it can prove
You need ten thousand tasks. Each task needs a repository at one commit, a way to run it, a bug report, and at least one test that fails now and would pass after a correct fix. Writing these by hand takes a person an hour or more. Nobody has that many hours. So teams build them from material that already exists.
Open-source projects keep a record of their own fixes. A GitHub issue is a bug report. A pull request (PR) is a proposed change, and when a PR fixes an issue and changes the tests, it holds a ready-made task: the issue is the problem statement, the code change is the answer, and the new tests are the check.
SWE-bench did this first. It holds 2,294 problems from real GitHub issues in 12 popular Python repositories. When it appeared, the best model, Claude 2, solved 1.96% of them. Its tests come from the projects themselves, so they were written for people, not for a model.
The mining step is a filter. Keep a PR only if it links an issue, changes tests, and the tests behave right: new tests fail on the old code and pass on the new code. Here is that filter as code.
pythondef keep(pr): if not pr.links_issue or not pr.changes_tests: return False before = run_tests(pr.base_commit, pr.test_patch) # new tests on OLD code after = run_tests(pr.base_commit, pr.test_patch, pr.patch) # new tests on FIXED code f2p = [t for t in after.passed if t in before.failed] # fail-to-pass p2p = [t for t in after.passed if t in before.passed] # pass-to-pass return len(f2p) >= 1 # at least one test must flip
Mining gives a benchmark. Training needs more, and it needs tasks that really run. A gym is a collection of environments an agent can practise in. SWE-Gym holds 2,438 real Python tasks, and each comes with an executable runtime environment, unit tests and a task description. Training agents on it gave up to 19% absolute gains in resolve rate on SWE-Bench Verified and Lite.
R2E-Gym attacks the human bottleneck. Its method, SYNGEN, builds executable environments straight from commits, using test generation and back-translation (writing a bug report backwards from a change). It reduces the need for human-written issues or tests, and it reaches more than 8.7K tasks.
There is a cheaper trick. Take a working codebase whose tests pass. Break it on purpose, and keep the break if at least one existing test now fails. The broken tree is the task, and the old tests are the check. This is synthetic bug injection, and SWE-smith uses it: one execution environment per codebase, then hundreds to thousands of instances from each. It reports 50k instances from 128 repositories. The paper notes that earlier datasets held at most thousands of instances from 11 or fewer repositories.
Code competitions give a different kind of task. A problem statement, a program that reads input and prints output, and a pile of hidden test cases. Judging is simple: run the program on each input and compare the printed output. AlphaCode drew on this with a competitive programming dataset (named CodeContests in its paper), large-scale sampling and behaviour-based filtering. It reached a ranking of top 54.3% in simulated Codeforces contests with more than 5,000 participants. LiveCodeBench collects 400 problems published between May 2023 and May 2024 from LeetCode, AtCoder and CodeForces, and keeps adding new ones.
Pick a source. The bars show how many tasks each reports, on a log scale: each gridline is ten times the last. Switch to What it trained to see the reported result.
All numbers are from each paper’s abstract. R2E-Gym says “more than 8.7K” and SWE-rebench says “over 21,000”, so those bars are lower bounds. The results are pass@1 on SWE-Bench Verified, a hand-checked subset of SWE-bench. SWE-bench’s own 1.96% is on the full set, so it is left off the second view. SWE-rebench and LiveCodeBench report no such score in their abstracts.
Read the bars as a trade. Mining gives the smallest sets with the most real tests. Injection gives the biggest sets, at the price of bugs no human wrote. Each step toward scale moves the test further from a human’s intent.
Every family makes some bad tasks. Some are too hard: no model ever solves them. Some are too easy: every sample passes. Neither teaches anything. Many RL methods compare the samples of one task against each other (a group). If all eight score 0, or all eight score 1, nothing differs, so nothing is learned.
Measure it. Sample k attempts per task and call p the chance one attempt passes. The chance that a group has both a pass and a fail is 1 − pk − (1 − p)k. At k = 8 and p = 0.5, that is 1 − 0.0039 − 0.0039, or 99.2%. At p = 0.05, it is 1 − 0 − 0.6634, or 33.7%. So a task a model solves 1 time in 20 gives a useful signal only one group in three.
Fix: run a pilot of 8 to 16 samples per task, then drop tasks at 0 and at 8 of 8, and keep the middle. Redo the pilot as the model improves, because yesterday’s hard task is today’s easy one.
Chapter 3
Turn a repository into a box that behaves the same way every time, cannot reach the outside, and can be thrown away in a second
On Monday your agent solves 61 of 100 tasks. On Friday, with the same model and the same tasks, it solves 54. Nothing changed in your code. A package that your tasks install had a new release on Wednesday. Seven results moved, and none of them is the model’s fault.
The sandbox exists to stop this kind of drift, and to stop worse things. Five design choices do most of the work. We take them one at a time.
A container is a program running inside a walled-off copy of an operating system’s file tree, with its own processes and its own view of the network. It is lighter than a full virtual machine because it shares the host’s kernel. A container image is the frozen recipe for that file tree: the system, the language, the repo’s code and every package it needs, built once and stored.
Build the image per repository, ahead of time, and install all dependencies then. At run time the box starts from the image in seconds, with nothing to download. SWE-smith reports building one execution environment per codebase, and notes that earlier datasets’ companion environments take several terabytes. The next paragraph shows why storage grows so fast.
Images are built in layers: each build step adds a layer on top of the last, and layers are shared. Say the base system is 1 GB and a repository adds 1 GB. With 128 repositories that is 1 GB + 128 × 1 GB, about 129 GB, because the base is stored once. If every one of 50,000 tasks had its own full 2 GB image, the total would be 100 TB. These sizes are illustrative, but the lesson is real: share the base, add a layer per repository, and add per task only the small difference (the commit).
To pin a dependency is to name its exact version, such as numpy==1.26.4, instead of “the newest”. Pinning also covers the tools: the language version, the test runner and its plugins. Do this when you build the image and never again afterwards. The Monday-to-Friday drift above is a missing pin.
Inside the box the network is off. Three reasons stack up. The agent could download the real fix, or the hidden tests, from the project’s public history. A package server could change an answer between runs. And code that nobody has read could send data out. With the network off, the image must already hold everything. If a task needs a web page, offer a tool that fetches it from a cache you control.
A patch can contain an endless loop, a memory leak, or a program that starts a thousand processes. So the box has hard limits: CPU cores, memory, number of processes, disk space and wall-clock time. Hit a limit and the run ends with a clear status such as timeout. The limits also protect the machine, so one bad episode cannot slow down its neighbours.
A run is deterministic if the same inputs always give the same output. Tests break that in small ways: random numbers, the time of day, the order tests run in, and hash order in Python. Fix each one: set the seed, set the clock and time zone, fix the order, set PYTHONHASHSEED=0.
Finally, snapshot and reset. After an episode, do not clean the box by hand. Delete it and start a new one from the image. Cleaning by hand leaves files behind, and a left-over file from episode 41 can change episode 42. A copy-on-write layer makes this cheap: the agent’s changes go into a thin top layer, and reset means discarding that layer.
Each switch blocks one hazard. Turn them off one at a time and watch the bars. The bars show corrupted episodes in every 1,000.
Illustrative: the rates (2.0%, 4.0%, 1.5%, 3.0% and 2.5% of episodes when a protection is off) are made up to show how the hazards add up. They are not measured in the papers.
Now the whole recipe as code. These are real Docker flags: --network none cuts the network, --cpus, --memory and --pids-limit cap resources, and --rm deletes the box on exit.
pythondef run_in_box(image, script, timeout_s=900): cmd = ["docker", "run", "--rm", # --rm: reset = delete the box "--network", "none", # no network "--cpus", "2", "--memory", "4g", # CPU and memory caps "--pids-limit", "256", # no process bombs "-e", "PYTHONHASHSEED=0", "-e", "TZ=UTC", # determinism image, "bash", "-lc", script] # image = pinned, prebuilt try: r = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout_s) return {"exit": r.returncode, "stdout": r.stdout[-2000:]} # clip long output except subprocess.TimeoutExpired: return {"exit": -1, "status": "timeout"} # the wall-clock cap
Symptom: the same model scores 61 one week and 54 the next, on the same tasks. Measurement: re-run a fixed set of 200 tasks nightly with a fixed model and a fixed seed, and diff the per-task results. If the same few tasks flip, look at what they install. If they flip at random, the cause is flakiness, the topic of Chapter 7.
Fix: for the first kind, pin the version and rebuild the image once. Record the image’s digest (its content hash) in the task record, so a task always means one exact box. Never let a task say “latest”.
Chapter 4
Turn a pile of test results into one number, and see why a reward needs two kinds of test to be worth paying
Two patches both make the new test pass. The first fixes the bug. The second also quietly breaks the login page. If the reward only checks the new test, both earn the same score, and the model learns that breaking things is free.
So the reward needs to ask two questions. Did the bug get fixed? Did anything else break? Each question has its own set of tests.
Run the task’s tests twice: once on the original code, once after the patch. Sort each test by what happened.
A fail-to-pass test (F2P) fails before the patch and must pass after it. It is the proof that the bug is gone. Without any F2P test, a task has no way to say a patch did anything. A pass-to-pass test (P2P) passes before and must still pass after. It is the proof that nothing else broke. A change that breaks something that used to work is a regression, and P2P tests are the regression guard.
The simplest reward is binary: 1 if every F2P test and every P2P test passes after the patch, and 0 otherwise. This is how a patch is counted as “resolved” in SWE-bench style evaluation. Here it is as code. The line results.get(t) == "passed" matters: a test that is missing from the results counts as a failure, not as a pass.
pythondef grade(results, f2p, p2p): # results: {"test_blank_age": "passed", "test_valid_age": "failed", ...} fixed = all(results.get(t) == "passed" for t in f2p) # the bug is gone kept = all(results.get(t) == "passed" for t in p2p) # nothing else broke return 1.0 if fixed and kept else 0.0
It is tempting to pay the fraction of tests that pass. A patch that passes 8 of 9 tests earns 0.89, which feels fair. Try the arithmetic on a patch that does nothing. Take a task with 3 F2P tests and 6 P2P tests. The empty patch leaves the 3 F2P tests failing and the 6 P2P tests passing. That is 6 of 9 passing, a reward of 0.67 for doing nothing.
An agent that learns this will submit empty patches when a task looks hard. The fraction rewards the baseline, not the work. Flip the nine tests below and compare three ways to score the same patch.
Each button is a test after the patch: on means it passes. The first three are fail-to-pass, the last six are pass-to-pass. Try the presets, then flip tests yourself.
Illustrative task with 3 fail-to-pass and 6 pass-to-pass tests. The faint mark on each gauge is what an empty patch would earn under that scheme.
The binary reward gives the empty patch 0, the broken fix 0, and the real fix 1. The fraction of all tests pays the empty patch 0.67. The fraction of F2P tests alone pays the empty patch 0 but pays the fix that breaks two tests a full 1. Only the binary reward gets all four presets right. Binary has a cost: it gives no signal for a patch that is nearly right. Chapter 5 shows how teams soften that cost without paying for the baseline.
The grader never sees “the tests” as objects. It sees text. Run the test runner with its verbose flag and each test prints one line with a status and an ID. The grader turns those lines into the results table that grade reads.
pythondef parse_pytest(log): results = {} for line in log.splitlines(): # e.g. "PASSED tests/test_age.py::test_valid_age" status, _, test_id = line.partition(" ") if status in ("PASSED", "FAILED", "ERROR"): results[test_id.split("::")[-1]] = status.lower() return results # a crash before collection gives {}: all missing = all failing
If the test file has a syntax error, the runner crashes before it lists any test. The table is then empty. Because grade treats a missing test as a failure, the reward is 0, which is right. Log the reason separately, though. A crash and a failing assertion need different fixes, and mixing them hides which one you have.
A task is itself something that can be broken. Symptom: the model scores far below what you expect on one repository, and a quick read of failing runs shows correct-looking fixes with reward 0. Measurement: run two probe patches on every task. The gold patch (the human fix from the task record) must score 1. The empty patch must score 0. Count how many tasks fail either probe.
Typical causes of a failing gold patch are a test-name parser that cannot read this project’s output, a test that needs a service the box lacks, and a dependency that was never installed. Fix: drop tasks that fail either probe, or repair them, and keep the probe as a gate that every new task passes. Run it again whenever you rebuild an image.
Chapter 5
Meet the three ways teams soften or replace a binary test reward, and see exactly how each one can be fooled
A binary reward has two problems. It says nothing about a patch that is nearly right, so hard tasks return a long run of zeros. And some data has no tests at all: you have a history of real fixes, but nobody wrote a test for each one.
Three ideas answer these problems. Each one trades some honesty for some signal. For each, we ask the same question: what does a clever agent do to get the reward without the work?
Chapter 4 showed that a plain fraction of passing tests pays the empty patch. The fix is to build the partial credit so that doing nothing still scores 0. Here is one scheme. If every test passes, pay 1.0. Otherwise, if every pass-to-pass test still passes, pay 0.3 times the share of fail-to-pass tests that now pass. Otherwise pay 0.
Work it on a task with 3 fail-to-pass tests. A real fix earns 1.0. A patch that fixes 2 of the 3 and breaks nothing earns 0.3 × 2/3 = 0.2. The empty patch fixes none, so it earns 0.3 × 0 = 0. A patch that fixes all 3 but breaks one pass-to-pass test earns 0. The numbers are made up, but the order is the point: the partial value stays well below the full value, and it never pays for damage.
pythondef shaped_reward(results, f2p, p2p, partial=0.3): ok = lambda t: results.get(t) == "passed" if all(map(ok, f2p)) and all(map(ok, p2p)): return 1.0 # resolved if all(map(ok, p2p)): # nothing broke: pay a little for progress return partial * sum(map(ok, f2p)) / len(f2p) return 0.0 # damage pays nothing
How is this gamed? An agent can learn to fix the easy test in each task and stop. If 0.2 is easier to get than 1.0, a policy can settle there. Keep the partial value small, and watch the share of episodes that end at a partial score.
Now take the second problem: no tests. SWE-RL trains on real software history and uses a lightweight rule-based reward. Its abstract names the similarity score between the ground-truth solution and the model’s solution as the example. No code runs. You compare two pieces of text. The resulting model, Llama3-SWE-RL-70B, reached a 41.0% solve rate on SWE-bench Verified, which the paper calls the best reported for medium-sized models (under 100B) at the time.
Similarity is cheap. It needs no box, no image and no test runner. Its weakness is that two patches can look alike and behave differently, or look different and behave the same. Try it on four candidate fixes for our blank-input bug. The device scores each against the human fix and runs a stand-in test result next to it.
The human fix is shown first. Pick a candidate. The top bar is how much its text matches the human fix. The bottom bar is whether it passes the tests.
Illustrative. The similarity is computed live in your browser as 2 × (longest common subsequence of characters) / (total characters). SWE-RL’s abstract says only “a similarity score”, so treat this as a stand-in, not their formula. The test results were worked out by hand: “Close but wrong” crashes on input that is only spaces.
Look at what the bars say. The wrong patch scores 0.89 and the correct reshaped patch scores 0.48. If you train on this reward alone, you teach the model to write code that looks like the answer. Sometimes that is enough, because real fixes cluster around common shapes. Sometimes it teaches confident copying. That is why similarity is best seen as a cheap signal for large amounts of history, checked against held-out resolve rates.
The third idea is a verifier: a second model that reads a candidate patch and says how likely it is to be right. An execution-free verifier never runs the code. An execution-based one runs tests, perhaps tests the verifier model wrote itself. Verifiers matter most at test time: sample many patches, score each one, and submit the best. SWE-Gym trained verifiers on agent trajectories for exactly this.
R2E-Gym compared the two kinds. Each one alone saturates around 42 to 43% on SWE-Bench Verified. Test-based verifiers have low distinguishability: many wrong patches pass the same weak tests, so the tests cannot tell them apart. Execution-free verifiers are biased and often rely on stylistic features, such as what a patch looks like rather than what it does. Combined into a hybrid, they reach 51%, because each one catches the other’s mistakes.
| Signal | Needs a box | Pays for | How it is gamed |
|---|---|---|---|
| Binary tests | Yes | Resolved, nothing else | Edit or delete the tests; hardcode |
| Shaped partial credit | Yes | Progress on the fail-to-pass tests | Stop at the easy partial score |
| Similarity | No | Looking like the human fix | Copy shapes; wrong but close wins |
| Execution-free verifier | No | A model’s opinion | Write in the style it likes |
| Hybrid | Yes | Both signals agreeing | Fooling both at once is harder |
Symptom: the average training reward rises for days, but the model’s resolve rate on a held-out set stays flat. Measurement: log both numbers on the same chart, and on a labelled sample of 200 episodes compute how often the proxy reward agrees with the real test outcome. A good proxy agrees most of the time and keeps agreeing as training proceeds. If the agreement falls over time, the model is learning the proxy, not the task.
Fix: give the proxy a smaller weight, add an execution check wherever you can afford one, and refresh the labelled sample as the model changes. Treat the held-out resolve rate as the truth and the training reward as a hint.
Chapter 6
Learn the five shortcuts a reward-hungry model finds on its own, and build the guard that makes each one pay nothing
On Tuesday the average reward of your training run jumps from 0.31 to 0.52. On Wednesday you check the held-out resolve rate, measured with a clean grader. It has not moved. The model did not get better at fixing bugs. It found a way to be paid without fixing them.
This is reward hacking: raising the reward in a way that does not do what the reward was meant to measure. Nobody tells the model to cheat. Reinforcement learning tries many paths and keeps the ones that pay. If a shortcut pays, a shortcut gets learned. Your job is to make sure every shortcut pays 0. Here are the five that matter in coding.
The test is red. The code is hard. The easy move is to remove the test. In a patch it looks like a block of lines starting with a minus sign in a test file. A naive grader runs the tests that remain, sees no failures, and pays 1.0. This is exactly what the hero instrument showed with “Delete the tests”.
A variant keeps the test but changes what it expects. The test said assert parse_age("") is None. The patch changes it to assert parse_age("") == 0, then makes the function return 0. The code is now wrong by the spec, and the test passes.
If the agent can read the tests, it can write code that answers only the test inputs: if s == "-3": return None. The visible tests pass. Any other input breaks. Patch D in Chapter 0 did this.
A repository stores its past. If the box holds the full history, the fix may already sit in a later commit. The command git log --all lists it, and one git diff shows it. The agent never has to reason about the bug at all. This is environment leakage: information the agent should not have, reachable from inside the box.
With a network, the agent can fetch the project’s current source, or install a newer release of the package that already includes the fix. Chapter 3 turned the network off for this reason, among others.
Four defences cover the five shortcuts. Turn them on in the device and watch which attacks still pay.
Each row is an attack. Red means it still earns a reward of 1.0. Green means the guard turns it into 0. Switch defences on and off.
Illustrative logic, simplified: restoring the tests blocks deleting and rewriting them; held-out tests are variants the agent never sees, so they also catch hardcoding and any unfixed bug; cutting history removes the leaked fix; turning the network off blocks downloads. Real attacks overlap more than five rows suggest.
Look at the pattern. No single defence stops all five. Restoring the tests is cheap and stops the two most common attacks. Held-out tests are the only thing that stops hardcoding, and they are the reason a good task has more tests than the agent ever sees. The last two defences are about the box, not the tests.
The rule behind all four is short: the grader must trust nothing the agent can touch. Here is a grader written that way. It applies the agent’s patch to a fresh box, drops any change to test files, then writes the real tests.
pythondef grade_clean(task, patch): box = fresh_box(task["image"]) # new box, not the agent's box.apply(patch, exclude=task["test_paths"]) # ignore edits to tests/ box.apply(task["test_patch"]) # write the real tests log = box.run(task["test_cmd"], timeout_s=600) return grade(parse_pytest(log), task["FAIL_TO_PASS"], task["PASS_TO_PASS"])
You will not predict every shortcut. So measure for them. Symptom: reward rises faster than the held-out resolve rate. Measurement: audit every patch that earned a reward, and log two numbers. First, the share of rewarded patches that touch a test path. Second, the share whose added lines contain a literal test input. In an honest run both stay close to zero. A sudden rise is the signature of a new exploit.
pythondef audit_patch(patch_text, test_paths, test_inputs): files = re.findall(r"^diff --git a/(\S+)", patch_text, flags=re.M) touches = [f for f in files if any(f.startswith(p) for p in test_paths)] added = "\n".join(l[1:] for l in patch_text.splitlines() if l.startswith("+") and not l.startswith("+++")) hard = [x for x in test_inputs if x in added] # test inputs pasted into the code return {"touches_tests": touches, "hardcoded": hard}
Work one example, with made-up numbers. Out of 1,000 rewarded episodes on Monday, 4 patches touch a test path: 0.4%. On Wednesday, 140 of 1,000 do: 14%. The jump is 35 times. At the same time the clean resolve rate stays at 31%, while the paid reward rose from 0.31 to 0.52. The gap, 0.52 minus 0.31, is 0.21 of reward that came from cheating. Report that gap on a dashboard every day. It is the cheapest early warning you have.
Fix: when the audit lights up, read ten flagged patches by hand, name the shortcut, and add the matching defence. Then keep the audit running. Models find new shortcuts as they get stronger, so the guard is never finished.
Chapter 7
Measure how often a good patch is scored wrong by a test that disagrees with itself, and learn the re-run arithmetic that catches it
An agent writes a perfect fix. The grader runs the 40 tests, and one of them times out. The reward is 0. The same patch, graded again a minute later, earns 1. Nothing about the patch changed. The test did.
A flaky test is a test that sometimes passes and sometimes fails on the very same code. It is the noise in your reward signal, and noise has a price. A correct answer sometimes earns 0, and a wrong answer sometimes earns 1.
Most flaky tests have a small cause. The test waits for a thread to finish and gives up after a fixed time. It uses random numbers without a fixed seed. It depends on the order tests run in, so another test leaves a file behind. It reads the clock. It asks the network for something. Chapter 3’s sandbox removes some of these (a fixed seed and clock, no network) but not all of them. Timing on a busy machine is the hardest to remove, and a machine running thousands of boxes is busy.
Suppose each flaky test fails by accident with probability q, even on correct code. A task has m such tests. The patch is correct. The chance that every flaky test passes is (1 − q)m. So the chance of a wrong zero is 1 − (1 − q)m.
Try three flaky tests at q = 5%. The chance all three pass is 0.95 × 0.95 × 0.95 = 0.857. So a correct patch earns a wrong 0 about 14.3% of the time. That is one correct answer in seven marked wrong, from three tests that look healthy on any single run.
Give each test up to r attempts and call it failed only if all r attempts fail. A flaky test that fails with probability q now fails the reward with probability qr. At q = 5% and r = 3, that is 0.05 × 0.05 × 0.05 = 0.000125, or 0.0125%. With three flaky tests, the wrong-zero chance falls from 14.3% to about 0.04%.
There is a catch. Retries also help a wrong patch whose failure is random. If a bug makes a test fail half the time, three attempts let it pass with chance 1 − 0.53 = 87.5%. So retry is a patch on noise, not a cure. The cure is to find the flaky tests and remove them.
To find flaky tests, run the gold patch k times and look for tests whose outcome changes. A test with failure rate q shows both outcomes in k runs with chance 1 − qk − (1 − q)k. For q = 5% that is 14.3% for k = 3 runs, 40.1% for k = 10 and 92.3% for k = 50. A test that fails one run in twenty needs about fifty runs to be caught nearly every time. Try the numbers yourself.
Top: the chance a correct patch is wrongly scored 0, for 1 to 5 attempts per test. Bottom: the chance a gold-patch check catches one flaky test, for 1 to 50 runs. Drag the sliders.
Exact arithmetic on the numbers you set: wrong zero = 1 − (1 − qr)m; detection = 1 − qk − (1 − q)k. It assumes each flaky test fails independently by accident. Real flakiness is often correlated, which makes the true wrong-zero rate somewhat lower and the detection harder.
Two readings matter. Retries cut the wrong-zero rate sharply: going from one attempt to three turns 14.3% into well under 1%. Detection is far slower: even 10 runs miss six flaky tests in ten at q = 5%. The lower the flake rate, the harder the test is to catch, and the longer it quietly adds noise.
Detection first, then a grader with retries. Notice that the retry grader re-runs only the tests that failed, which keeps the extra cost small.
pythondef flake_report(task, runs=10): seen = {} for _ in range(runs): # run the GOLD patch many times for t, s in parse_pytest(run_gold(task)).items(): seen.setdefault(t, []).append(s) # a test is flaky if it both passed and failed return {t: ss.count("passed") / runs for t, ss in seen.items() if 0 < ss.count("passed") < runs} def grade_with_retry(box, test_cmd, tests, attempts=3): results = parse_pytest(box.run(test_cmd)) for _ in range(attempts - 1): failed = [t for t in tests if results.get(t) != "passed"] if not failed: break again = parse_pytest(box.run(test_cmd, only=failed)) results.update({t: s for t, s in again.items() if s == "passed"}) return results
Symptom: the same patch earns different rewards on different grading runs. Measurement: grade a random sample of 200 episodes twice and count disagreements. If 9 of 200 disagree, the reward is noisy about 4.5% of the time. Group the disagreements by test ID; a handful of tests usually cause most of them.
Fix: quarantine those tests by taking them out of the fail-to-pass and pass-to-pass lists, or drop the task if too few good tests remain. Use retries as a second line of defence, and re-run the flake report whenever you change the image or the hardware.
Chapter 8
See how a benchmark score can rise without the model getting better, and how a rolling set of new tasks keeps the score honest
A model scores 70% on a coding benchmark published two years ago. The same model scores 40% on problems posted last month. Nothing about the model differs between the two sets, except one thing: it may have already seen the first set.
That is contamination (also called leakage): test material that ended up in the training data. A model trained on the answers to a test can score well by remembering them. The score then measures memory, not skill. Coding benchmarks are at special risk, because their problems and their fixes sit in public repositories and on public web pages, which are exactly what training data is made of.
A model’s training cutoff is the date after which it saw no new data. Anything published after that date cannot be in its training set. So if every task carries a date, you can sort tasks into two groups for a given model. Tasks before the cutoff might have been seen. Tasks after it are fresh: the model cannot have seen them.
Two of our sources are built on this idea. LiveCodeBench collects problems continuously from contests on LeetCode, AtCoder and CodeForces. Its 400 problems were published between May 2023 and May 2024, and it keeps adding new ones, so it is contamination-free by design for models trained before the new problems appear. The paper evaluates 18 base and 34 instruction-tuned models, and reports results on contamination and on possible overfitting in existing benchmarks.
SWE-rebench does the same for repository tasks. Its pipeline keeps pulling in new interactive Python tasks, and the dataset holds over 21,000. The authors compare some models’ results on the new tasks with SWE-bench Verified and find that some models’ performance might be inflated due to contamination.
Here is a small model of the effect. Say a model has a true skill of 40%: it solves 4 in 10 fresh problems. On problems it has seen, memory adds a boost, say 15 points, so it solves 55% of those. Now take a benchmark that covers 12 months with the same number of problems each month, and a model whose cutoff falls after month 6. Half the benchmark is old to it, and half is fresh.
The whole-set score is 0.5 × 55% + 0.5 × 40% = 47.5%. The fresh-only score is 40%. The whole-set number is 7.5 points too high, and the leaderboard cannot tell. Move the cutoff in the device and watch the gap grow as more of the set falls before it.
Each column is one month of problems. Grey months might be in the training data. Green months are fresh. Slide the cutoff, then change the model’s skill and the boost memory gives.
Illustrative model: the same number of problems each month (LiveCodeBench’s real monthly counts are not given in its abstract), a flat skill, and a flat memory boost on every seen problem. Real contamination is uneven: a well-known problem leaks more than an obscure one.
Two things stand out. When the cutoff is at the start, there is nothing seen and the two scores agree. When the cutoff is at the end, nothing is fresh, and the fresh-only score has no problems to use. A rolling set always needs new tasks arriving faster than new models are trained.
Store a date with every task: when the issue was opened, or when the contest ran. At test time, keep tasks after the model’s cutoff, plus a safety margin, since the cutoff of a model is rarely known to the day.
pythonfrom datetime import timedelta def fresh_tasks(tasks, model_cutoff, margin_days=30): start = model_cutoff + timedelta(days=margin_days) # the cutoff is fuzzy: add a margin return [t for t in tasks if t["created_at"] > start] def ngram_overlap(text, corpus_index, n=13): w = text.split() grams = {tuple(w[i:i + n]) for i in range(len(w) - n + 1)} return sum(g in corpus_index for g in grams) / max(1, len(grams)) # share of 13-word runs seen in training text
The second function is a cheaper check. It asks how many runs of 13 words from a task also appear in a training-text index. A high share is a warning sign, but a low share proves nothing, because a solution can be rewritten in other words. Dates are the stronger tool.
Contamination also hides inside your own pipeline. Tasks from one repository share code, names and fixes. If you train on SWE-smith-style tasks from a repository and test on real issues from the same repository, the model may have seen the code it is asked to fix. Split by repository, not by task: whole repositories go to training or to testing, never both.
Symptom: a model ranks near the top on an old benchmark and drops on a fresh set. Measurement: on a fresh set, plot pass rate by month of problem date, and look for a step down at the model’s cutoff. A flat line suggests skill. A step suggests memory. Fix: report scores on the fresh window as the main number, publish the window dates next to it, and retire a task set once most current models have a cutoff after it. The cost is real: scores from different windows are not directly comparable, so say which window you used every time.
Chapter 9
Work out how many sandboxes a training step needs, where the time goes in one episode, and why the slowest episode sets the pace
One training step needs a batch of finished episodes. Say 512 tasks, 8 attempts each: 4,096 episodes. The GPUs that update the model sit idle until the last reward arrives. If the boxes are slow, the most expensive machines in the building wait for the cheapest ones.
So a post-training team does arithmetic before it buys anything. How long is one episode? How many can run at once? How long does a batch take? Every number below is illustrative, because your tasks and hardware will differ, but the method is the one used in practice.
An episode has four parts. First, the reset: start a box from the image. Say 8 seconds. Then the loop: each step is one model call and one tool call. Say the model takes 6 seconds to write a step and the box takes 2.5 seconds to run it. With 30 steps that is 30 × (6 + 2.5) = 255 seconds. Last, grading: run the tests in a clean box. Say 90 seconds.
Add them up. 8 + 255 + 90 = 353 seconds, about six minutes. The sandbox side (reset, tool calls, grading) takes 8 + 75 + 90 = 173 seconds. That is 49% of the episode. Half the wall-clock time is the boxes, not the model.
How many boxes must run at once? Think of a coffee shop. If a customer spends 6 minutes inside and 10 customers arrive each minute, then 60 customers are inside at any moment: arrival rate times time inside. This is Little’s law, and it holds for any steady flow.
For us, an episode spends 353 seconds inside a box. To finish 4,096 episodes in 24 minutes, which is 1,446 seconds, you need a rate of 4,096 / 1,446 = 2.83 episodes per second. Concurrency is 2.83 × 353 = 1,000 boxes. Flip it around: N boxes finish N × 3,600 / 353 episodes an hour. For 1,000 boxes that is 10,198 episodes an hour.
The top bar is one episode, split by where its time goes. The bars below show how long a batch of 4,096 episodes takes with more boxes. Drag the sliders.
Illustrative throughout. Fixed assumptions: 8 s to reset a box, 6 s for the model to write one step, 2 CPU cores per box, 64 cores per machine, a batch of 4,096 episodes. Batch time = max(episode time, 4,096 × episode time / boxes), with no tail; the next section adds the tail.
Two readings. Doubling the boxes halves the batch time, until it hits the floor of one episode’s length, here 353 seconds. Past that point, extra boxes do nothing. More boxes cannot shorten one episode. Only faster resets, tool calls and grading, the sandbox share, can.
The model above has every episode taking exactly 353 seconds. Real episodes do not. A few hit the step limit. A few run slow tests. A few wait for a box that is still starting. If the slowest episode takes three times the median, a batch that waits for every episode takes three times the median, no matter how many boxes you add. The mean says 6 minutes. The tail says 18.
Symptom: the GPUs show 40% idle during the collection phase, and the idle stretch comes at the end, when most boxes are empty and a few are still busy. Measurement: plot a histogram of episode wall time, and the number of busy boxes over the batch. A long right tail in the first and a long ramp-down in the second is the signature. Fix: put a time limit on each episode and treat a timeout as a failure, collect episodes asynchronously instead of in lock-step batches, and stop waiting for the last few percent. Dropping the slowest 2% of episodes can cut batch time by a large share, at the price of a small bias against hard tasks.
The 173 seconds is yours to shrink. Keep a pool of warm boxes: boxes already started from the image, waiting for a task, which removes most of the reset. Cache images on every machine so the first pull is not repeated. Run only the tests the task lists, not the whole suite, because grading was the biggest piece, at 90 seconds. And give grading its own pool of boxes so tests do not queue behind tool calls.
pythonasync def collect(tasks, policy, pool, n_boxes=1000, per_episode_s=900): sem = asyncio.Semaphore(n_boxes) # at most N episodes in flight async def one(task): async with sem: box = await pool.acquire(task["image"]) # a warm box if one is free try: return await asyncio.wait_for(run_episode_async(policy, task, box), per_episode_s) except asyncio.TimeoutError: return {"task": task["instance_id"], "reward": 0.0, "status": "timeout"} finally: await pool.release(box) # delete the box, start a fresh one return await asyncio.gather(*(one(t) for t in tasks))
Chapter 10
Check an environment against everything in this lesson, keep the numbers and terms at hand, and find the next lessons to read
You can now build a coding environment from memory. It is a loop: reset a pinned box, let the agent act, take its patch, grade it in a clean box against hidden tests, and return one reward. Every other idea guards that loop against a way it can lie.
A coding episode runs an agent in a sandbox built from a pinned image with the network off, and ends in a reward from tests the agent never saw. Tasks come from mined issues (SWE-bench), executable gyms (SWE-Gym, R2E-Gym), injected bugs (SWE-smith) and contest problems (AlphaCode, LiveCodeBench). The usual reward is binary: every fail-to-pass and every pass-to-pass test must pass. Partial credit, similarity (SWE-RL) and verifiers add signal and each can be gamed. Agents find shortcuts, so the grader trusts nothing the agent can touch. Flaky tests add noise that re-runs can measure, contamination inflates scores unless tasks are fresh, and throughput follows from episode time and Little’s law.
Use this checklist before you trust a reward. Tick what your environment does. The read-out names the first gaps and the chapter that closes each one.
Each button is one check from the lesson. Press it to tick it. The bar fills as you go.
The thirteen checks are this lesson’s own summary of Chapters 1 to 9, not a standard from any paper.
| What | Number | Why it matters |
|---|---|---|
| SWE-bench | 2,294 problems, 12 Python repositories; Claude 2 solved 1.96% | Real issues are hard; mined tasks are few |
| SWE-Gym | 2,438 instances; up to 19% absolute gain; 32.0% Verified, 26.0% Lite | Executable tasks train agents |
| R2E-Gym | more than 8.7K tasks; 34.4% pass@1 Verified; verifiers 42 to 43% alone, 51% hybrid | Two weak verifiers beat one |
| SWE-smith | 50k instances from 128 repositories; 40.2% pass@1 Verified | Injected bugs give scale |
| SWE-RL | Llama3-SWE-RL-70B, 41.0% solve rate on Verified | A similarity reward works without running code |
| SWE-rebench | over 21,000 tasks, collected continuously | Fresh tasks expose inflated scores |
| LiveCodeBench | 400 problems, May 2023 to May 2024; 18 base and 34 instruction-tuned models | Dates make contamination checkable |
| AlphaCode | top 54.3% in simulated Codeforces contests with more than 5,000 participants | Sample many, filter by behaviour |
| Wrong zero (illustrative) | 1 − (1 − qr)m; 14.3% for m = 3, q = 5%, r = 1 | Flaky tests price the noise |
| Flake detection (exact) | 1 − qk − (1 − q)k; 92.3% at k = 50, q = 5% | Rare flakes need many runs |
| Useful group (exact) | 1 − pk − (1 − p)k; 33.7% at k = 8, p = 5% | Drop tasks that never or always pass |
| Little’s law (illustrative) | 353 s per episode, 1,000 boxes: 10,198 episodes an hour | Boxes = rate × episode time |
Here is the central function of the whole lesson. It scores one patch, and every line points back to a chapter. The helpers (fresh_box, parse_pytest, grade_with_retry, grade, audit_patch) are the ones built in Chapters 3 to 7.
pythondef score_episode(task, patch, attempts=3): box = fresh_box(task["image"]) # Ch 3: pinned image, network off, new box box.apply(patch, exclude=task["test_paths"]) # Ch 6: ignore any edit to test files box.apply(task["test_patch"]) # Ch 6: write the real tests, held-out ones too tests = task["FAIL_TO_PASS"] + task["PASS_TO_PASS"] results = grade_with_retry(box, task["test_cmd"], tests, attempts) # Ch 7: retry the flaky ones reward = grade(results, task["FAIL_TO_PASS"], task["PASS_TO_PASS"]) # Ch 4: missing = failed flags = audit_patch(patch, task["test_paths"], task["test_inputs"]) # Ch 6: log cheats return reward, flags # Ch 9: run this on 1,000 boxes at once
This lesson covers the machine that makes the reward. The learning rule that uses the reward is a separate subject. Task environments gives the general contract for any agent environment: reset, step, reward. RL run forensics shows how to read a training run and catch reward hacking once it starts. RL with verifiable rewards and GRPO and DAPO explain how a group of rewards becomes a weight update.
Now press Present or Teach and explain one episode out loud, from memory: what the box allows, what the grader hides, how the reward is computed, three ways an agent could cheat and the defence for each. Then go back to the grader at the top and predict, before you click, which patch each grader will pay.