Reinforcement Learning for Coding Agents: Training Stability and Evaluation Bias
Reliable improvements in coding agents depend on more than model size. This article explains how trajectory-length oscillation, cost-aware rewards, and length-conditioned baselines affect reinforcement learning stability, and how review criteria and execution harnesses can distort benchmark comparisons. It also outlines practical controls for separating genuine gains in repository repair from evaluation-specific advantages.
Long-horizon coding tasks differ fundamentally from single-turn question answering. An agent must inspect a repository, locate defects, edit multiple parts of the codebase, run tests, and revise its work in response to review feedback. Reinforcement learning turns final acceptance into an optimization signal, potentially improving task completion rates substantially.
In practice, a doubling of benchmark scores rarely comes from switching to a larger base model alone. More often, three factors work together: rewards account for costs and unnecessarily long trajectories, training keeps trajectory lengths stable, and evaluation uses an execution environment consistent with the one encountered during training.
The following sections explain these mechanisms rather than repeat any particular vendor’s marketing claims.
Why Long-Horizon Tasks Are Difficult to Train Reliably
Software engineering trajectories vary widely in length. A simple bug fix may take a dozen or so steps, while a cross-module refactor may require more than a hundred.
When every step is sampled from the same policy, an initially conservative policy can produce short trajectories with few successful examples. If the agent happens to complete a long trajectory and receive a high reward, the policy may shift toward more exploration and broader file changes. Trajectories then grow rapidly, timeouts and unproductive edits increase, and returns fall again.
This repeated swing between short and long rollouts is trajectory-length oscillation.
Its immediate consequence is distorted advantage estimation. Within a batch, short and long trajectories can have different return scales and variances. If the baseline simply subtracts the batch mean, noise from long trajectories can dominate the gradient and repeatedly reverse the direction of policy updates. Validation curves become jagged, and occasional high scores prove difficult to reproduce.
Trajectory-length distributions should therefore be monitored alongside accuracy. Track whether the distribution is unimodal and whether it drifts consistently during training. For each training round, record:
- Trajectory-length quantiles.
- Timeout rates.
- Tool-call counts.
- Length differences between successful and unsuccessful trajectories.
Why Rewards Need an Explicit Cost Penalty
Rewarding only test success can encourage excessive searches, repeated edits, and prolonged reasoning in pursuit of an occasional passing result. A cost-aware reward combines the final outcome and execution overhead into a single scalar:
effective_return = task_success_score - λ × normalized_cost
Cost may represent token consumption, tool round trips, the number of modified files, or wall-clock time. Choose λ using a validation range in which costs fall substantially while success rates remain nearly unchanged, rather than assigning an arbitrary fixed value.
If the penalty is too strong, the model may abandon difficult tasks prematurely. Success rates on short trajectories can look impressive while harder tasks fail entirely. If the penalty is too weak, length oscillation persists.
A more cautious approach is to clip costs at selected quantiles so that a few extremely long failed trajectories do not distort the entire batch gradient. Report both pass rate and passes per unit cost to avoid optimizing one metric at the expense of the other.
The cost term must also reflect operational constraints. If production quotas are based on request counts, penalize requests. If the main risk is overly broad modification, penalize changed lines and writes outside the target paths. Constraints omitted from the reward are likely to become opportunities for the policy to exploit.
What a Length-Weighted Return Baseline Addresses
The standard advantage calculation subtracts a baseline from the return. When trajectory lengths vary substantially, a single baseline across all samples can systematically overestimate or underestimate advantages for particular length ranges.
A length-weighted baseline estimates expected returns separately for length buckets, or through a continuous kernel over trajectory lengths. The advantage then subtracts the baseline corresponding to that trajectory’s length. This makes the comparison more meaningful: how much better did the trajectory perform than others of similar length?
The intuition is straightforward. A successful 80-step trajectory should not be judged solely by comparing its absolute return with that of a failed 15-step trajectory. Its relevant comparison is with trajectories of roughly 80 steps.
Weighting can use inverse sample counts or a smooth function of length, with care to prevent baseline variance from becoming excessive in sparsely populated buckets. Practical implementation guidelines include:
- Fix length-bucket boundaries before training. Do not silently change them as the distribution shifts, because doing so makes gradients across training stages less comparable.
- Maintain an exponential moving average for each bucket rather than relying only on the current minibatch.
- For empty buckets, fall back to neighboring buckets and reduce the affected sample’s loss weight.
- Decouple baseline statistics or the baseline network from policy updates so that both do not drift together.
Length weighting does not replace exploration strategies or high-quality data. It removes spurious advantages associated with length, making genuine task signals easier to detect.
If successful trajectories remain scarce, curriculum learning, replay of failed trajectories, and high-quality demonstrations filtered by humans or rules are still needed. Even an accurate baseline cannot turn noise into a useful learning signal.
Data Quality and Training Stability Matter More Than Extra Updates
Reinforcement learning is highly sensitive to software repository data. Repository licenses, test reproducibility, answer leakage in defect descriptions, and exposure to hidden tests all affect whether the policy learns to repair software or memorize solutions.
Stable training typically involves:
- Fixing random seeds and dependency versions.
- Truncating excessively long trajectories and reporting them separately rather than silently discarding them.
- Labeling tool failures, such as network errors, permission issues, or broken test fixtures, separately from model errors.
- Using smaller learning rates and larger batches to smooth advantage noise.
- Interleaving behavior cloning or applying KL constraints between policy updates to prevent abrupt shifts away from behavior that can still use tools reliably.
Improving long-horizon performance means making multistep credit assignment more reliable. Intermediate rewards should be sparse and verifiable—for example, a key test changing from failing to passing, or a static check succeeding. Vague process scores that encourage verbose logs are less useful.
Once process rewards can be gamed, trajectory-length oscillation can return in another form.
How Evaluation Protocols Can Create Several-Fold Score Gaps
Even when training works, comparisons across leaderboards can be misleading. The explanation often lies in evaluation protocols rather than hidden technical breakthroughs.
Underspecified Requirements and Automatic Rejection
Some newer benchmarks no longer specify the exact scope of the required changes. Instead, they apply maintainer-style review criteria with conditions that automatically invalidate a submission.
A solution may receive zero credit if it:
- Fixes only the path named in the task while leaving equivalent defects elsewhere.
- Fails to support input types already accepted by the repository.
- Passes tests but breaks an implicit contract.
This approach is closer to real code review, but it also increases evaluation variance. Models not adapted to these scoring rules should be expected to score lower. That decline alone does not establish that the base model’s capabilities have deteriorated.
Execution Harness Coupling
The system prompt, available tools, working-directory permissions, test commands, and timeouts together form the agent’s execution harness.
A policy trained through reinforcement learning in one harness can perform differently when moved to another command-line wrapper, retry policy, or context-truncation scheme.
When third parties rerun models under a shared harness, performance gaps often narrow. This suggests that some of the original advantage came from harness coupling rather than transferable coding ability.
Overlap Between Benchmark and Training Teams
If the same team develops both the benchmark and the training system, the policy may unintentionally fit scoring rules, common failure patterns, and timeout boundaries.
This is not necessarily cheating. However, claims of broad superiority should disclose:
- Whether evaluation used a proprietary harness.
- Whether the scoring scripts were available during development.
- Whether failures reflected functional errors or rejection on formatting grounds.
A single aggregate score cannot distinguish better repair ability from familiarity with rejection rules.
How to Judge Whether Improvements Are Credible
Before arguing that one agent is stronger than another, run at least four controlled comparisons:
- Change only the execution environment. Keep the checkpoint, temperature, and number of sampled attempts fixed, then measure the score range across environments.
- Break down rejection reasons. Report the shares attributable to functional failures, out-of-scope changes, compatibility omissions, and timeouts.
- Evaluate both requirement styles. Report results on older, explicitly scoped tasks and newer, underspecified review-based tasks rather than showing only the favorable version.
- Plot length and cost throughout training. Track trajectory-length quantiles and cost curves to verify that higher scores are not being purchased through operationally unacceptable rollouts.
If the advantage disappears after changing environments, or if pass rate rises while passes per unit cost fall, the appropriate conclusion is that the agent is more effective under a particular harness and reward definition—not that its general coding ability has doubled.
A base model that allocates capacity to games, 3D tasks, or other specializations may become weaker at general repository repair. Establishing that explanation, however, requires ablations across task subsets. A single leaderboard cannot support it.
A Minimal Implementation Checklist
Teams building coding agents should iterate in the following order rather than start by stacking reward techniques:
- Make tests reproducible and failure causes classifiable.
- Record trajectory lengths and execution costs.
- Introduce clipped cost penalties and length-bucketed baselines.
- Add internal review rules to the validation set, while retaining an external regression set decoupled from the training harness.
The advantage calculation can remain simple:
advantage = reward - cost_penalty - baseline[length_bucket]
Here, reward is assigned only at an automatically verifiable terminal outcome, and baseline comes from historical mean returns within the corresponding length bucket. Any additional dense reward should first demonstrate, through small-scale ablations, that it does not increase unproductive edits.
Large changes in coding benchmark scores can reflect more stable reinforcement learning: suppressing trajectory-length oscillation, constraining redundant work with cost penalties, and correcting advantages through length-weighted baselines. They can also reflect underspecified evaluation requirements, automatic rejection rules, and overlap between training and evaluation environments.
Reporting these factors separately provides a better foundation for the next round of data and training improvements than pursuing a single aggregate score.
