How Reinforcement Learning Solves Long-Horizon Coding Tasks
This article explains why reinforcement learning is preferred over supervised fine-tuning for long-horizon software engineering tasks, and how to stabilize training and interpret benchmark results. It covers reward design that balances correctness, cost, and hard constraints; length-weighted baselines and rollout length oscillation; the real sources of benchmark score gaps; and a reusable checklist for reproducible evaluation.
1. The Starting Point: Why RL for Coding Is Harder Than It Looks
In software engineering settings, asking a model to autonomously complete the full chain of “read the repository, locate the defect, modify the code, pass verification” is a classic long-horizon task. Unlike single-turn question answering, failure in long-horizon tasks usually does not come from one wrong reasoning step. Errors accumulate across multiple turns of interaction: one incorrect file localization can send every subsequent patch off course, and one incompatible assumption about an existing input type can cause a whole set of previously passing test cases to fail together.
This is why the industry generally relies on reinforcement learning rather than pure supervised fine-tuning when training these capabilities. The core reason is that correct intermediate steps are hard to enumerate and label exhaustively, while the outcome signal — “did it ultimately pass verification” — is naturally available. The problem is that this outcome signal is sparse and delayed, and optimizing it directly leads to unstable training.
2. Reward Design: From “It Runs” to “It Ships”
An early approach reduced the reward to a binary pass/fail signal. This introduces two side effects: the model tends to look for the shortest opportunistic path, and it over-modifies unrelated code just to make tests pass. A common industry improvement is to add cost penalty terms that fold change size, number of turns, and execution time into negative signals, upgrading the reward from “did it pass” to “how cheaply did it pass.”
An illustrative reward structure can be expressed as:
reward = correctness_score \- alpha * normalized_edit_size \- beta * normalized_step_cost \- gamma * violation_penalty
Here, violation_penalty corresponds to “instant fail” constraints, such as breaking compatibility with the repository’s existing input types or modifying modules outside the requested scope. These constraints already exist in real code review. Writing them explicitly into the reward significantly suppresses opportunistic behavior.
3. Length-Weighted Baselines and Rollout Length Oscillation
The most typical instability in long-horizon training is rollout length oscillation: one batch of samples happens to explore a longer successful path, pushing the policy toward longer outputs; then memory and sampling budget tighten, length is forced down, success rate drops sharply, and it rebounds again. The result is a sawtooth curve that makes convergence difficult.
The idea behind a length-weighted reward baseline is to let the baseline adapt to the sample length distribution instead of using a global fixed mean. Long and short samples are then compared against their own kind, which lowers the variance of advantage estimation. In practice, this can be combined with the following strategies:
- Set a soft cap on sampling length rather than a hard truncation, avoiding a reward discontinuity at the cutoff;
- Bucket baselines by length, normalize within each bucket, then compute advantages;
- Monitor length quantiles rather than the mean, since the mean hides bimodal distributions;
- Keep a certain proportion of historical successful trajectories as stability anchors.
4. The Real Sources of Benchmark Gaps: Don’t Rush to Blame Model Capability
A high-leverage insight: when a model leads by a large margin on a single leaderboard, suspect the evaluation setup before assuming a capability gap. There are three common causes.
First, the leaderboard and the training team share the same origin. When the evaluation criteria and the training method come from the same team, the details of the criteria are fully understood, and scores naturally run high. Some newer leaderboards deliberately leave a lot of room in the prompt and no longer pin down requirements, while layering multiple veto conditions on top of open-source maintainer review standards: fixing a defect on path A while leaving the same class of issue on path B unaddressed, or passing ordinary unit tests without remaining compatible with existing input types, results in a zero. Without targeted adaptation, any model will lose points on such leaderboards.
Second, harness inconsistency. Official results are often obtained in a self-built command-line environment, and that environment is itself the sampling sandbox for reinforcement learning, with tool-call formats, context organization, and failure fallback logic tightly coupled. The same model scores lower when moved to another coding tool’s command-line entry point, and may recover when moved to the evaluator’s general-purpose sandbox. This shows that a substantial share of the gap comes from environment adaptation rather than the weights themselves.
Third, differences in capability structure. When resources tilt toward directions such as graphics and 3D generation, marginal investment in general coding capability is diluted, which shows up on general coding leaderboards as expected.
5. A Reusable Practice Checklist
- Fix the evaluation setup first: unify the sandbox, prompt templates, timeout and retry policies, then compare models.
- Layer the reward: outcome reward + process compliance reward + cost penalty, avoiding a single binary signal.
- Prioritize stability: length-bucketed baselines, soft truncation, and a joint dashboard of success rate and length quantiles.
- Hold out a validation set from the real distribution: include multiple input types and cross-module interaction cases to avoid optimizing only for unit test pass rate.
- Attribution order: environment → prompt → data → training hyperparameters → model capability, checking the easiest to verify first.
6. Conclusion
Improving long-horizon coding capability is fundamentally a dual engineering problem of training stability and evaluation credibility. Only by making reward design, baseline estimation, length governance, and evaluation consistency solid can you build reproducible, explainable capability gains on general-purpose compute and container platforms, log services, and monitoring and alerting infrastructure such as Baidu AI Cloud — rather than a one-off high score that is hard to reproduce.
