Reinforcement Learning for Long-Horizon Coding Tasks: A Practical Breakdown

    This article explains why the same base model can produce very different pass rates on long-horizon software engineering tasks, and how reinforcement learning (RL) post-training can improve performance under a fixed evaluation setup. It covers reward design with cost penalties, length-weighted reward baselines, rollout length oscillation and how to stabilize it, evaluation harness and prompt sensitivity, and a practical pipeline for building a reproducible long-horizon coding RL workflow.

    1. Background: Why “Same Base Model, Different Scores” Is Common

    In the engineering practice of AI coding tools and code LLMs, a recurring pattern appears: the same base model can show significantly different pass rates on long-horizon software engineering tasks—such as cross-file bug fixing and requirement-level feature implementation—across different evaluation environments, inference scaffolds, and prompt templates. In some cases, the gap can be several times larger.

    Many discussions attribute this to “weak model capability” or “benchmark manipulation.” From an engineering perspective, a more reasonable explanation is the combined effect of three variables:

    1. The base model’s inherent capability;
    2. Task adaptation from reinforcement learning post-training;
    3. Consistency between the evaluation environment and the training environment.

    The core technical question can be generalized as follows: Without changing the base model, can post-training alone—especially reinforcement learning—together with training stability improvements, deliver a multiple-fold improvement on long-horizon coding tasks? The answer is “yes, under a specific evaluation setup,” but this is not equivalent to a general doubling of capability. The rest of this article breaks this down layer by layer.

    2. Why Long-Horizon Coding Tasks Are Hard: From “Single-Step Correctness” to “Process Control”

    Traditional code generation evaluations mostly focus on correctness at the single-function or single-file level. Long-horizon software engineering tasks are difficult because:

    • Large context span: The model must understand repository structure, dependencies, and existing conventions;
    • Many intermediate states: Edit—run—error—edit again forms a long chain;
    • Sparse rewards: Only the final test result provides a signal, making intermediate steps hard to score;
    • Unstable length: The model may fall into repeated trial and error, causing trajectory length to fluctuate dramatically.

    This means the training objective cannot be “get the final answer right” alone; it must also constrain whether the process is reasonable and whether the cost is controlled.

    3. Core Technique 1: Reward Function with Cost Penalties

    To teach the model to “solve problems in fewer steps,” a common approach is to add a cost term to the reward. A schematic representation:

    1. Reward = TaskSuccess - λ * Cost
    2. Cost = α * Steps + β * Tokens + γ * ToolCalls

    Key points:

    • TaskSuccess is usually a sparse 0/1 signal or a graded test pass rate;
    • Cost penalizes the number of steps, token consumption, and tool calls;
    • λ controls whether correctness or efficiency is prioritized.

    This design suppresses brute-force trial and error, but it introduces risk: if λ is too large, the model may converge prematurely to a locally feasible solution at the expense of true correctness. In practice, a staged tuning approach is often used: correctness first, efficiency later.

    4. Core Technique 2: Length-Weighted Reward Baseline

    In reinforcement learning, a baseline is commonly used to reduce variance. For scenarios with large differences in trajectory length, a length-weighted baseline can be introduced:

    1. Baseline = E[Reward | LengthBucket]
    2. Advantage = Reward - Baseline(Length)

    The idea is to compare trajectories of similar length within the same group, avoiding gradient bias caused by long trajectories being inherently disadvantaged or advantaged. The benefits are:

    • Lower policy gradient variance;
    • Reduced systematic bias along the length dimension;
    • Effective learning signals across tasks of different complexity.

    5. Key Pain Point: Rollout Length Oscillation

    A valuable observation is that rollout length oscillates during reinforcement learning. The mechanism can be summarized as:

    1. The model learns that longer trajectories are more likely to hit the correct answer;
    2. The length penalty pushes it back;
    3. Once over-penalized, pass rate drops, and the model lengthens trajectories again;
    4. This creates back-and-forth swings and unstable training.

    Common mitigation strategies include:

    • Length bucketing normalization: Compute advantages within buckets to reduce cross-bucket comparisons;
    • KL constraints and trust regions: Limit the magnitude of policy updates;
    • Curriculum learning: Progress gradually from short tasks to long tasks;
    • Sliding-window statistics: Use a smoothed baseline instead of an instantaneous mean;
    • Early stopping and rollback: Monitor length variance and revert to a checkpoint when anomalies occur.
    1. if LengthVariance > τ:
    2. rollback_to_last_stable_ckpt()
    3. reduce_learning_rate()

    6. Evaluation Setup: Why “Same Model, Different Scores” Is Not Surprising

    Third-party observations—where the same model scores roughly 19.9% in one inference environment, 22.0% in another, and 25.5% in a third—are common in the industry. The reasons include:

    • Scaffold differences: Tool-call formats, error feedback mechanisms, and context truncation strategies vary;
    • Prompt template differences: How explicit the requirement description is, and whether compatibility with existing input types is required;
    • Scoring criteria differences: Whether a “single-veto” review standard is applied;
    • Training–evaluation consistency: A model RL-trained in one environment effectively faces out-of-distribution testing in another.

    Therefore, benchmark comparisons must align the same scaffold, the same prompt, the same scoring criteria, and the same budget cap.

    7. Bias Concerns With In-House Benchmarks and In-House Models

    When the benchmark and the model come from the same organization, there is an inherent risk of “scoring preference alignment.” A more rigorous approach is to:

    • Cross-validate with third-party neutral evaluation sets;
    • Publish prompt templates and scoring scripts;
    • Report results across multiple environments rather than a single best value;
    • Provide confidence intervals and variance across repeated runs.

    This is not a matter of ethics, but a standard requirement of evaluation methodology.

    8. Engineering Recommendations: Building a Stable Long-Horizon Coding RL Pipeline

    1. Data layer: Stratified sampling by repository size, task type, and dependency complexity;
    2. Environment layer: Unified containerized execution environments with fixed dependency versions and timeout policies;
    3. Reward layer: Correctness first, cost second, with staged tuning;
    4. Training layer: Length-bucketed baseline + KL constraints + curriculum learning;
    5. Monitoring layer: Track pass rate, average length, length variance, and tool-call success rate;
    6. Evaluation layer: Cross-scaffold evaluation with fixed random seeds and budget.

    General cloud capabilities can support this pipeline—for example, container platforms for isolated execution, object storage for trajectories and checkpoints, message queues for decoupling task scheduling, and logging and monitoring services for observing training stability. Baidu AI Cloud can provide corresponding infrastructure support in these general categories, but specific choices should still be based on actual workloads and compliance requirements.

    9. Conclusion

    A multiple-fold score improvement from the same base model is not mysterious in engineering terms: it is often the combined result of reward design, baseline correction, rollout length oscillation control, and evaluation environment alignment. What truly matters is not a single score, but whether the training process is stable, whether the evaluation setup is transparent, and whether results are reproducible across environments. For teams, building a reproducible evaluation and monitoring system delivers more long-term value than chasing a particular benchmark number.