Reinforcement Learning Optimization for Long-Horizon Coding Tasks

    This article explains why a coding agent can score far higher than its base model on public benchmarks, and breaks down the three layers involved: the base model, reinforcement learning post-training, and the agent execution harness. It covers the main challenges of long-horizon repository tasks—error accumulation, context drift, and sparse rewards—along with practical techniques such as cost-penalized reward functions, length-weighted reward baselines, and controlling rollout length oscillation. It also stresses keeping the evaluation environment identical to the training environment, offers a framework for assessing benchmark credibility, and closes with an actionable engineering checklist.

    1. Background: Why “Same Base Model, Double the Score” Is Not Counterintuitive

    In a highly competitive stage of AI coding tools, a common phenomenon appears: a coding agent scores significantly higher on public code benchmarks than the base model it relies on does on the same leaderboard, sometimes by a multiple. Many discussions instinctively suspect fabricated data, but from an engineering perspective this is the inevitable result of the division of labor between the “agent layer” and the “model layer.”

    Three layers need to be distinguished:

    • Base model layer: provides general capabilities for code understanding, generation, and reasoning;
    • Reinforcement learning post-training layer: performs preference optimization on interaction trajectories in real repositories with real toolchains;
    • Agent execution layer (harness): handles context organization, tool invocation, command execution, failure rollback, and result verification.

    Benchmark scores are the result of coupling all three layers. The base model only sets the capability ceiling, post-training determines whether that capability can be reliably triggered, and the execution layer determines whether the capability can be correctly applied. So “same base model, different scores” is the norm rather than an anomaly.

    2. Why Long-Horizon Coding Tasks Are Hard: Error Accumulation and Context Drift

    Short question-and-answer style code generation needs only one high-quality output, whereas repository-level tasks require the model to execute dozens or even hundreds of steps in sequence: locating files, understanding call chains, modifying code in multiple places, running tests, reading errors, and fixing them again. The difficulty concentrates in three areas:

    1. Error accumulation. A 95% per-step accuracy rate yields a theoretical success rate below 8% after 50 consecutive steps.
    2. Context drift. As the trajectory grows longer, early constraints get diluted, and the model tends to forget boundary requirements such as “only modify path A.”
    3. Sparse rewards. Only whether the final test passes serves as a signal, and intermediate steps lack gradient guidance.

    3. Core Method One: Reward Function with Cost Penalties

    If only “task completion” is rewarded, the model tends to search and trial-and-error without restraint. After introducing a cost term, the objective function can be abstracted as:

    1. # Illustrative pseudocode: expresses the design idea only
    2. reward = success_bonus \
    3. - alpha * token_cost \
    4. - beta * step_count \
    5. - gamma * tool_call_penalty

    Here alpha, beta, and gamma control cost sensitivity. Practical points:

    • Penalties should not be too large, otherwise the model will “exit early” and abandon necessary exploration;
    • Normalize costs to avoid inconsistent scales across tasks of different sizes;
    • Including timeouts, invalid commands, and repeated failures in the penalty terms can significantly reduce idle spinning.

    4. Core Method Two: Length-Weighted Reward Baseline

    Policy gradient methods rely on a baseline to reduce variance. In long-horizon tasks, trajectory lengths vary enormously, and a uniform baseline puts “long trajectories” at a natural disadvantage, with the gradient signal drowned out by noise. The basic idea of a length-weighted baseline is to compute expected return by bucketing trajectories by length:

    1. baseline = {bucket: mean_return_of_bucket
    2. for bucket, group in group_by_length(trajectories)}
    3. advantage = reward - baseline[length_bucket_of(trajectory)]

    The benefit is that “long but correct” trajectories of equal quality are no longer systematically undervalued, and the training signal is closer to true capability.

    5. The Real Difficulty: Rollout Length Oscillation

    One of the trickiest problems in reinforcement learning training is rollout length oscillating repeatedly during training: it first grows longer (more exploration), then drops sharply (the model learns to be lazy and exit early), and then rebounds. Without control, both training stability and final results suffer. Combinable measures include:

    • Confidence-interval monitoring of length constraints, filtering out anomalous batches;
    • Applying a moving average to the length distribution as a difficulty-adjustment signal for curriculum learning;
    • Stratified sampling to ensure each length bucket has enough samples;
    • Early stopping and checkpoint rollback to avoid being led astray by anomalous gradients from a single round.

    6. The Overlooked Key: The Evaluation Environment Must Match the Training Environment

    The same model scoring noticeably differently under different execution frameworks is a common industry phenomenon. The reason is that the execution layer determines how context is trimmed, how tools are exposed, how failures are fed back, and how the scoring script judges. If a model completes reinforcement learning within one execution framework and is then evaluated in another, it is equivalent to changing the rules of the competition for the contestant.

    Practical recommendations:

    1. Use the same tool interfaces and prompt conventions for training and evaluation;
    2. Pin the scoring script version and record the complete evaluation configuration;
    3. When reporting scores, also provide the execution environment, sampling temperature, maximum step count, and budget cap;
    4. Run cross-environment comparisons with the same model to quantify the gains contributed by the execution layer.

    7. A Framework for Assessing Leaderboard Credibility

    When facing a conclusion that “a model far exceeds its base model,” review it along the following dimensions:

    • Whether the leaderboard and the model come from the same source. If the benchmark authors and the training side are the same, there is implicit alignment of prompts and scoring standards.
    • Whether the scoring standard introduces a “single veto.” For example, only fixing defects in a specified path is required, yet compatibility with other input types in the repository is additionally demanded, so a solution that passes the standard unit tests may still be scored zero.
    • Whether prompts are deliberately left open-ended. Instead of hard-coding requirements, evaluation follows open-source maintainer review standards, and models without targeted adaptation generally lose points.
    • Whether sample size and confidence intervals are disclosed, and whether there is selective reporting.

    8. An Actionable Engineering Checklist

    • Build an internal repository-level evaluation set covering multiple languages and multiple build tools;
    • Version-control the reward function and penalty terms, changing only one variable at a time;
    • Monitor three curves—length distribution, success rate, and cost—and judge training health jointly;
    • Keep cross-execution-environment comparison experiments as a basis for capability attribution;
    • Isolate execution environments in a container platform, and track long-horizon trajectories with logging services and monitoring and alerting systems.

    9. Conclusion

    “Unchanged base model, doubled score” is usually not a data problem but the combined result of post-training and the execution layer. What truly deserves attention is not a single score but whether these four things are done solidly: reward design, baseline variance control, length oscillation control, and evaluation consistency. For a team, fixing the evaluation criteria and designing the training signal clearly brings more long-term value than chasing any single leaderboard ranking; if elastic compute and complete observability are needed, a stable training and evaluation pipeline can be built on general capabilities such as the container platform, logging service, and monitoring and alerting offered by Baidu AI Cloud.