Pure Reinforcement Learning for Coding Agents: Key Practices for Improving Long-Horizon Tasks
This article examines how pure reinforcement learning (RL) is applied to post-training coding agents, with a focus on long-horizon engineering tasks. It first qualifies the widely cited "2x benchmark improvement" claim by showing that the gain holds only on long-horizon, engineering-oriented evaluations, reverses on terminal-interaction benchmarks, and is negligible on code comprehension. It then explains why verifiability makes pure RL the mainstream post-training route, outlines the training loop, and identifies environment and task scaling as the primary lever for capability gains. The article details rollout length control and training stability techniques, proposes an evaluation system based on pass rate percentiles, efficiency, regression and safety, and failure-mode clustering, and closes with practical adoption steps for enterprise teams building their own training and evaluation pipelines.
1. First, Cool Down the “2x Improvement” Claim
When you see a statement like “a coding tool scores twice as high as the previous generation on a coding leaderboard,” the first reaction should be to ask three questions: which benchmark, compared against what, and is the base model the same? The original information already answers this: the multiple only holds on a category of evaluations that lean toward long-horizon, engineering-oriented work, with scores of roughly 41.3 vs. 19.9. Switch to an evaluation focused on terminal interaction and command execution, and the conclusion reverses outright: 50.0 vs. 59.7. Switch again to an evaluation focused on code understanding and Q&A, and it lands at 71.0 vs. 70.2, essentially within noise.
From this, three more rigorous judgment principles can be drawn:
- Benchmark heterogeneity: Different evaluations measure different capability dimensions. Long-horizon benchmarks weight planning, state retention, and self-correction more heavily; terminal-oriented benchmarks weight environment interaction efficiency and short feedback loops. Neither can be extrapolated to the other.
- Base model mismatch: A before/after comparison must use the same base model, the same decoding configuration, and the same tool permissions; otherwise the improvement cannot be attributed to the training method itself. The comparison in the original information happens to be “newly trained version” vs. “previous-generation base model,” which is not an ablation study in the strict sense.
- Averages hide distributions: A close total score does not mean equivalent capability. You need to look at percentiles and the distribution of failure modes, especially the completion rate on long-tail tasks.
So the more accurate statement is: a significant advantage was achieved in long-horizon, strongly engineering-oriented scenarios, not an across-the-board lead.
2. The Method Mainline: Why Still Choose Pure RL
The core reason pure reinforcement learning (which does not rely on human-annotated solution trajectories) has become the mainstream post-training route for coding agents is verifiability. Reward signals for code tasks are naturally clear-cut: whether unit tests pass, whether compilation succeeds, whether static checks report errors, whether performance meets a threshold. These signals require no human preference annotation and can be generated at scale automatically, which sidesteps the way imitation learning is constrained by the quality and coverage of labeled data.
A typical training loop can be abstracted as:
for step in range(total_steps):tasks = sampler.sample(batch_size) # stratified sampling by difficulty/domainrollouts = [agent.run(t, env=env_pool[t]) # multi-turn tool callsfor t in tasks]rewards = [verifier.score(t, r) # tests, compilation, performance thresholdsfor t, r in zip(tasks, rollouts)]advantages = normalize(rewards) # group-relative advantage estimationpolicy.update(rollouts, advantages) # policy update + KL constraint
There are three key design points here: diversity of the environment pool, reliability of the verifier, and variance control in advantage estimation. Degradation in any one of them shows up as “training loss looks normal but real capability stalls.”
3. The First Lever for Opening Up a Gap: Scaling Tasks and Environments
The original information notes that the method follows a pure RL route but significantly expands the coverage of tasks and environments, with short and long tasks coexisting and extending into directions such as scientific computing, performance optimization, and security analysis. This matters more in engineering terms than tuning the algorithm, for the following reasons:
- The environment is the curriculum. An agent’s capability ceiling is largely determined by the state space the environment exposes. Training only in environments where the task is “modify one function to make the tests pass” teaches the model local patching; adding environments that require cross-file refactoring, dependency installation, and build configuration repair is what forces out planning and tool-selection ability.
- Domain transfer brings generality. Scientific computing emphasizes numerical correctness and boundary conditions, performance optimization emphasizes measurable metrics and regression risk, and security analysis emphasizes vulnerability localization and minimal reproduction. The differences among these objective functions force the policy to learn “diagnose first, then act” rather than applying formulaic patches.
- Difficulty stratification and sampling strategy. It is advisable to maintain task metadata (domain, estimated step count, historical pass rate), use stratified sampling to control the difficulty distribution, and adjust dynamically: down-weight tasks whose pass rate stays near 1 for a long time, and give tasks stuck at 0 for a long time stronger environment scaffolding first, to avoid uninformative gradients.
A simplified illustration of stratified sampling:
def sample_tasks(pool, k):# Goal: balance the effective learning signal across difficulty bucketsbuckets = group_by(pool, key=lambda t: t.difficulty)weights = {b: 1.0 / max(1e-3, pass_rate(b)) for b in buckets}return weighted_sample(pool, weights, k)
4. The Real Technical Difficulty: Rollout Length Control and Training Stability
The most valuable piece of experience in the original information is this: in early versions, generation length oscillated back and forth and could easily derail training; after constraining rollout length, training could run stably for days on end, and held-out evaluation scores kept rising. This is a typical pain point of long-horizon RL and worth expanding on.
Why the oscillation happens. A single trajectory for a long-horizon agent may contain dozens of tool-call turns, and trajectory length is itself a high-variance random variable. Sudden length shifts break training along three paths: first, advantage estimation gets contaminated by length bias, and the model learns “longer means more effort”; second, memory usage and the in-batch sample length distribution change drastically, causing drift in the effective batch composition; third, the policy update step size becomes mismatched with the current policy distribution, triggering collapse-style degradation.
Viable control measures (all common industry practices):
- Length penalties or length-normalized advantage estimation, to avoid “verbose equals high score”;
- A soft cap and truncation policy per trajectory, treating an over-limit trajectory as incomplete rather than assigning zero reward directly, to reduce the variance introduced by sparse rewards;
- Length-bucketed batching, to keep the sample length distribution stable within the same optimization step;
- Monitoring four curves: KL divergence, entropy, average length, and truncation rate; if any metric shifts abruptly, lower the learning rate or roll back to a checkpoint;
- Keeping a fixed evaluation set for periodic regression, and using “keeps rising” rather than “single best point” as the selection criterion.
Illustrative length-constraint logic:
def score(task, rollout, max_steps):if rollout.truncated:# Don't judge incomplete as zero; give partial progress signal to reduce variancereturn 0.3 * rollout.progress_ratiopassed = verifier.run(task, rollout)length_penalty = alpha * (rollout.steps / max_steps)return float(passed) - length_penalty
5. Evaluation System: How to Avoid Fooling Yourself
For the training above to be credible, evaluation design must come first. At minimum, four categories of metrics are recommended:
- Pass rate and percentiles: Look beyond the mean at p50/p90 to identify long-tail collapse;
- Efficiency metrics: Average number of interaction turns, token consumption, wall-clock time. In long-horizon tasks, efficiency often affects usability more than pass rate;
- Regression and safety metrics: Whether new failures are introduced, whether high-risk operations are performed, whether resources outside the environment are accessed without authorization;
- Failure-mode clustering: Classify failures into categories such as wrong localization, environment misconfiguration, insufficient verification, and premature termination, and use them to guide environment building in reverse.
Also hold to three disciplines: keep the evaluation set isolated from the training environments, rotate it regularly to prevent overfitting, and keep the same base model and decoding parameters across all comparisons.
6. Adoption Advice: How Enterprises Can Reuse This Approach
To build a similar training and evaluation system for coding agents on your own codebase, proceed in the following order:
- Build the verifier first, then talk about training. Turn unit tests, builds, static checks, and performance baselines into an orchestrable pipeline. Reward signal quality determines everything.
- Containerize environments and unify the entry point. Use a container platform to host isolated environments, object storage to hold task packages and artifacts, a message queue to decouple task scheduling, and logging and monitoring with alerting to observe the training and inference paths. These are all general capability categories and do not require binding to a specific vendor implementation.
- Validate the loop at small scale first. Get the minimal loop of “sample-execute-verify-update-evaluate” working end to end, then gradually expand task coverage.
- Treat stability engineering as a first-class concern. Length control, checkpoint rollback, and metrics dashboards should be in place on day one of training, not added after a collapse.
- Keep external claims restrained. Explain advantages with per-scenario data, state the base model and evaluation conditions clearly, and avoid absolute multiple-based conclusions.
7. Summary
The reusable value of this phenomenon lies not in a multiple on some leaderboard but in three methodological points: a pure RL route centered on verifiable rewards, curriculum design driven by scaling tasks and environments, and stability engineering that takes rollout length control as its handle. Make these three solid, and pair them with an isolated, rotatable evaluation system, and capability gains for coding agents on long-horizon engineering tasks can be reproduced reliably and iterated on continuously.
