How Reinforcement Learning Breaks the Long-Horizon Coding Bottleneck

    This article explains why reinforcement learning (RL) post-training can dramatically improve coding models on long-horizon software engineering tasks, and why benchmark scores often look inconsistent across environments and versions. It covers three core techniques: reward functions with cost penalties, length-weighted reward baselines, and controls for rollout length oscillation. It also highlights the often-overlooked role of harness and training-environment consistency, the pitfalls of changing evaluation criteria, and a reproducible engineering checklist for building training and evaluation pipelines. Readers will learn how to interpret score jumps critically by asking whether the evaluation criteria changed, whether the environment is consistent, and whether the model was optimized against the same setup.

    1. Where the Problem Starts: The Engineering Truth Behind Score Gaps

    A curious pattern has recently emerged in the industry: a coding model built on an open-source base model and post-trained with reinforcement learning can score far above its base version on some software engineering benchmarks, occasionally reaching roughly twice the base score on individual leaderboards. At first glance, such results look “unscientific.” But once you unpack them, they are not magic. They are the product of three overlapping factors: tight alignment between the post-training objective and the evaluation objective, training and inference running inside the same harness (agent execution framework), and a structural change in how the benchmark itself scores.

    It is worth stressing that a benchmark score is only a projection of capability, not capability itself. The conclusion with real engineering value is this: the bottleneck in long-horizon coding has shifted from “can the model write code” to “can the model maintain a stable, controllable, and convergent behavior distribution across dozens or hundreds of interaction steps.” Reinforcement learning is precisely the tool for solving the latter problem.

    2. Why a Strong Base Model Can Still Double After Post-Training

    A base model’s capability comes from large-scale pretraining and instruction alignment. It is good at turning a single requirement into a piece of code in one turn. But real software engineering is long-horizon: read the repository, locate the call chain, modify multiple files, run tests, inspect errors, and fix them. In this chain, failure often does not come from an inability to write code, but from:

    • Inability to self-correct after heading in the wrong direction early;
    • Context being flooded by irrelevant information and losing the original constraints;
    • Output length getting out of control, either ending too early or falling into unproductive repetition;
    • Lacking a stable criterion for “what counts as done.”

    The gains from post-training come from making these implicit failures explicit in the optimization objective. When the reward signal is refined from “is the final answer correct” to “did it locate the right file, did it preserve existing interface compatibility, did it pass the newly added tests,” the model’s behavior distribution is significantly reshaped. This is why the base score and the post-trained score can differ by a multiple: what is being optimized is not the amount of knowledge, but the behavioral policy.

    3. Core Technique One: Reward Function with Cost Penalties

    For long-horizon tasks, the most naive reward is binary: give 1 if tests pass, otherwise 0. Its problem is that it is sparse and incomparable. One model can brute-force its way to a pass in 200 steps, while another solves it elegantly in 30 steps, and both receive the same reward. Training will end up encouraging a “verbose, many-step” policy.

    After introducing cost penalties, the objective can be abstracted as:

    1. # Illustrative pseudocode: reward = task utility - cost penalty
    2. def reward(trajectory, task):
    3. utility = 0.0
    4. utility += 1.0 * task.tests_passed_ratio() # functional correctness
    5. utility += 0.5 * task.hidden_checks_passed() # hidden cases / edge compatibility
    6. utility -= 0.2 * task.regression_count() # breaking existing behavior
    7. cost = (alpha * trajectory.token_count()
    8. + beta * trajectory.step_count()
    9. + gamma * trajectory.tool_call_count())
    10. return utility - cost

    There are three engineering points. First, penalty terms must be normalized; otherwise, differences in scale across tasks will let gradients be dominated by long tasks. Second, weights should be annealed in stages: early in training, prioritize utility so the model first learns to “get things done”; later, gradually increase the cost weight to compress redundancy. Third, penalties must apply only to controllable quantities. Do not count environmental jitter (such as time consumed due to test-machine load), or you will introduce noisy gradients.

    4. Core Technique Two: Length-Weighted Reward Baseline

    Policy-gradient methods rely on a baseline to reduce variance. The common approach is to use a scalar mean as the baseline. But in coding tasks, trajectory length varies enormously (from a dozen steps to over a hundred), and the reward variance of long and short trajectories is completely different. A unified baseline will systematically bias the gradients of long trajectories.

    The idea of a length-weighted baseline is to bucket by length, estimate the baseline within each bucket, and then extrapolate with smoothing:

    1. # Illustrative pseudocode: estimate baseline by length buckets with smoothing
    2. def baseline(reward, length, buckets, smooth=0.1):
    3. b = buckets[length] # historical mean for this length bucket
    4. b = (1 - smooth) * b + smooth * global_mean
    5. return b
    6. advantage = reward - baseline(reward, length, buckets)

    The direct effect is that long and short trajectories are compared on the same scale. The model will not gain a natural advantage just because it “writes long,” nor be over-penalized for “writing short.” Combined with cost penalties, the length distribution will converge toward “stop once it is good enough.”

    5. Core Technique Three: Governing Rollout Length Oscillation

    This is the most easily overlooked yet most fatal problem in long-horizon reinforcement learning. During training, the average rollout length swings back and forth dramatically: one batch gets longer, the next shrinks sharply, and the reward curve jitters in sync, leading to unstable training or even collapse.

    The cause is usually positive feedback: the model accidentally discovers that “writing a bit more makes it easier to guess right,” length rises, the proportion of high-length samples rises, and the sampling distribution shifts further toward long outputs. The reverse also holds.

    Actionable governance measures include:

    1. Confidence-interval monitoring of length constraints: do not look at the mean, look at P50/P90 percentiles; the mean hides long-tail explosions.
    2. Soft constraints on length rather than hard truncation: hard truncation misinterprets “being truncated” as a failure signal and pollutes the reward.
    3. KL constraint against a reference policy: limit how fast the new policy drifts from the reference policy to suppress abrupt changes.
    4. Length-stratified sampling within groups: ensure each batch has representatives of both long and short samples, avoiding batch bias.
    5. Anomalous batch dropping and resampling: when a batch’s average length deviates from the sliding median beyond a threshold, downweight or resample.
    1. # Illustrative pseudocode: batch-level length anomaly detection
    2. def is_anomalous(lengths, window, z=3.0):
    3. med = median(window)
    4. mad = median([abs(x - med) for x in window]) + 1e-6
    5. return abs(mean(lengths) - med) / mad > z

    6. The Underestimated Key: Harness and Training-Environment Consistency

    With the same model, switching the execution framework can change the score by several percentage points. The reason is not hard to understand: the harness determines what the model sees (system prompts, repository retrieval results, error-feedback format), what it can do (available tools and permissions), and how it is scored (how tests are triggered, how timeouts are judged). Doing reinforcement learning in a particular harness is equivalent to internalizing that harness’s “prompt distribution + tool interfaces + scoring criteria”; switching environments is like switching to a different language.

    Practical recommendations:

    • Keep training and evaluation harnesses as close to the same source as possible; if you must cross environments, do a small amount of adaptation fine-tuning on the target environment;
    • Treat the harness as a versionable configuration asset, recording prompt templates, tool sets, and timeout and retry policies;
    • Build a multi-environment evaluation matrix, covering at least three forms: “vendor-provided CLI form,” “general agent form,” and “pure completion form,” and observe the magnitude of score drift;
    • Report environment information alongside scores, otherwise the numbers are not comparable.

    7. The Trap of Evaluation Criteria: Why Leaderboards Drop Together

    The second type of contrast comes from the evaluation itself. When a leaderboard is upgraded from 1.x to 2.0, common changes include deliberately leaving blanks in prompts, no longer hard-coding requirements, and introducing many “single-veto” items following the standard of open-source maintainers reviewing PRs. For example, if only a defect on path A is required to be fixed, but a similar problem exists on path B and is not addressed, or new changes are not compatible with other input types already present in the repository, ordinary unit tests may all pass, yet the leaderboard may still score it zero.

    The essence of such criteria is writing “senior maintainer expectations” into the scoring function. It is more realistic, but extremely unfriendly to models not optimized for that criteria. This yields two general conclusions:

    • Leaderboard scores must be interpreted together with the version number and scoring criteria; cross-version comparison is meaningless;
    • If a leaderboard and a training method come from the same system, its score naturally carries an alignment advantage and should be regarded as internal consistency validation rather than a neutral third-party conclusion.

    8. A Reproducible Engineering Checklist

    1. Data side: construct tasks from real repository PR history, preserving original tests and hidden cases; stratify tasks by difficulty and length.
    2. Reward side: utility term + cost term + regression penalty, weight annealing, all normalized.
    3. Optimization side: length-bucketed baseline, KL constraint, gradient clipping, anomalous batch filtering.
    4. Sampling side: stratified sampling to ensure length diversity, control concurrency and timeouts, avoid environmental noise entering the reward.
    5. Evaluation side: multi-harness matrix + fixed version criteria + percentile metrics (P50/P90) rather than mean only.
    6. Infrastructure side: containerized isolated execution environments, object storage for archiving trajectories, message queues for peak-shaving scheduling, logging services and monitoring alerts to track length and reward curves; on Baidu AI Cloud, you can assemble training and evaluation pipelines by combining these general categories.

    9. Conclusion

    “Using reinforcement learning to double a coding model’s benchmark score” is not mysterious: it relies on writing the failure modes of long-horizon tasks into the reward, using a length-weighted baseline to stabilize variance, using percentile monitoring and soft constraints to suppress rollout oscillation, and keeping training and evaluation in the same execution environment. Conversely, when you see score contrasts across environments and versions, you should first ask three questions: did the criteria change? Is the environment consistent? Was it optimized against the same source? Once these three questions are answered clearly, the score truly has reference value.