Agentic Coding with Reinforcement Learning: Reward Design and Evaluation Pitfalls in Long-Horizon Tasks

    Agentic coding has shifted code-model evaluation from single-turn completion to long-horizon repository tasks that require bug localization, context understanding, multi-file edits, and iterative test-driven repair. This article examines two constraints that shape model quality: unstable rollout lengths during reinforcement learning and benchmark bias caused by tight coupling between models and evaluation harnesses. It covers reward design patterns such as cost-penalized completion rewards and length-weighted baselines, along with data-engineering requirements for reliable signals. It also reviews evaluation risks and practical checks, including cross-harness validation, prompt sensitivity analysis, strict-score ablation, and independent reproduction, and offers recommendations for training, data, evaluation, and team processes.

    1. Background: Why Agentic Coding Has Become a Major Battleground for Reinforcement Learning

    In recent years, competition in large-model code generation has gradually shifted from the accuracy of single-turn completion to the success rate of multi-turn agentic tasks. An agentic coding task requires a model to work autonomously in a real code repository through a complete loop: locating defects, understanding context, modifying multiple files, running tests, and iterating on fixes based on feedback. These tasks have three typical characteristics:

    1. Very long trajectories: A single task often involves dozens of tool calls, and any deviation at an intermediate step can cause the final task to fail.
    2. Sparse feedback: A terminal signal such as whether tests pass is often available only at the end of the task, while intermediate steps lack direct supervision.
    3. High cost: Every training trajectory involves substantial real tool execution and environment interaction, making large-scale low-cost sampling difficult.

    Because feedback is sparse and outcome-oriented, reinforcement learning (RL) is a natural fit for these tasks. A widely observed phenomenon is that models with similar performance on general conversation can differ by several times in agentic coding scores. This is explained partly by training methods and partly by evaluation systems. The following sections examine both.

    2. A Core Training Challenge: Rollout Length Oscillation

    In RL training for agentic tasks, one easily underestimated problem is severe oscillation in the length of rollouts (sampled trajectories). In the early stage of training, the model tends to answer quickly and terminate tasks early, producing shorter trajectories. As the policy learns to iterate through trial and error, trajectories can then grow without bound, resulting in many invalid loops. This pattern of “sometimes too short, sometimes too long” directly affects training stability.

    The damage appears in three main areas:

    • Unstable advantage estimation: Policy-gradient methods rely on relative advantages within a group. When trajectory lengths within a group have very high variance, return differences between long and short trajectories contaminate advantage estimates and cause jitter in the update direction.
    • Memory and compute fluctuation: Trajectory length directly determines KV cache usage and environment-interaction cost. Length oscillation makes resource scheduling difficult and creates severe load imbalance within a batch.
    • Reward signals distorted by length: If reward depends only on whether the task is completed, the model may “learn” to accumulate probability through excessively long trajectories, mistaking exploration noise for capability improvement.

    Common engineering remedies fall into two categories, described below with illustrative code.

    3. Reward Design: Cost Penalties and Length-Weighted Baselines

    The first approach explicitly introduces a cost term into the reward function so that both task completion and efficient completion enter the optimization objective. A typical composite reward has the following form:

    1. def compute_reward(passed: bool, steps: int, budget: int) -> float:
    2. if not passed:
    3. return 0.0 # No reward for a failed task; suppress do-nothing strategies
    4. base = 1.0
    5. # Cost penalty: steps beyond the budget are deducted proportionally
    6. overuse = max(0, steps - budget) / budget
    7. return base * (1.0 - lambda_cost * overuse)

    The budget can be set in tiers according to task difficulty to avoid a one-size-fits-all penalty on repair processes that are long but necessary.

    The second approach is a length-weighted reward baseline. Conventional GRPO-like methods compute a group mean baseline and treat all trajectories equally. A length-weighted baseline assigns different weights according to trajectory length, so that long trajectories—which usually have more noise and sparser information—contribute less to the baseline, while short successful trajectories receive higher relative advantage. An illustrative implementation is:

    1. weights = 1.0 / (1.0 + alpha * trajectory_lengths)
    2. baseline = (weights * rewards).sum() / weights.sum()
    3. advantages = rewards - baseline

    When these two designs are combined, training usually shows two observable improvements. First, the trajectory-length distribution converges to a reasonable range. Second, success rates on the same tasks improve, because the model no longer relies on brute-force trial and error to get lucky; instead, it learns to plan more direct repair paths. In addition, strengthening long-horizon task ability often requires supporting data engineering: select task samples that involve multi-file coordination and hidden dependencies, and use deterministic environment snapshots to ensure the reliability of RL signals.

    4. Evaluation Pitfalls: Deep Coupling Between Harnesses and Benchmarks

    Does good training guarantee trustworthy scores? Not necessarily. Evaluation bias is another issue that must be confronted in agentic coding.

    First, consider the effect of the harness. The same model running the same benchmark under different execution frameworks can differ by several percentage points or more. The harness determines many engineering details, including prompt templates, tool-call parsing, error-retry strategies, and context-truncation rules. A harness that has been trained together with a model naturally fits that model best; a third-party model running in that harness is effectively competing in ill-fitting shoes. Third-party evaluations may therefore use general-purpose execution environments to correct for this bias. For the same model, score differences across environments can often reach double-digit percentages.

    Second, consider changes in the benchmark’s scoring criteria. When a benchmark is upgraded, it may introduce stricter scoring standards—for example, requiring that a fix for one path defect must not break other paths of the same kind, must remain compatible with all existing input types in the repository, or must satisfy one-vote veto items set according to open-source maintainers’ standards for reviewing pull requests. As a result, many models that only satisfy “unit tests pass” will see their scores drop overall. This direction—scoring against real engineering standards—is good in itself, but caution is needed: if the scoring criteria and the training team come from the same organization, and the detailed rules are not fully public, there is room for hidden, targeted optimization in favor of that organization’s own methods. Practical ways to identify such bias include:

    1. Cross-validation: Run the same model in at least two independent harnesses and examine the correlation between scores.
    2. Sensitivity analysis: Make small perturbations to prompts, such as removing some guidance text, and observe the magnitude of score fluctuations.
    3. Ablation comparison: Compare scores under “unit tests pass only” and “strict criteria” to determine whether the model truly generalizes or has overfit to scoring details.
    4. Third-party reproduction: Rely on independent evaluation organizations that publish cross-model data using a unified environment, rather than relying only on official results.

    5. Recommendations for Engineering Teams

    Combining training and evaluation considerations, several practical recommendations emerge:

    • Training: Build trajectory-length monitoring dashboards for agentic RL tasks, and include the mean and variance of the length distribution in training health metrics. In reward design, keep the objective “outcome first, cost second,” and determine penalty coefficients through small-scale ablations.
    • Data: Prioritize environment quality over data quantity. Ensure tests are reproducible and failures can be attributed. For long-horizon tasks, sample in strata according to dependency depth.
    • Evaluation: Establish an internal multi-environment evaluation matrix. Base any model-upgrade decision on median scores across environments, so that score bias from a single harness does not mislead technology choices.
    • Team: Treat evaluation credibility as infrastructure. Document scoring criteria and open-source the scripts to reduce internal disagreement and external skepticism.

    6. Conclusion

    Improving agentic coding capability is the result of coordination among training algorithms, reward engineering, and evaluation systems. Controlling rollout-length oscillation and designing composite rewards determine the model’s upper bound, while decoupling evaluation environments determines the credibility of scores. Understanding “why the same model has vastly different scores on different leaderboards” is as important as understanding “how to train a stronger model.” For teams building code-agent capabilities, investing in both training and evaluation as first-class citizens is essential to delivering stable, verifiable automated coding capability in real engineering scenarios.