Reinforcement Learning for Coding Agents: Key Solutions for Long-Horizon Task Optimization

    This article explains why benchmark score jumps in coding agents do not always reflect real capability gains, and breaks down what reinforcement learning actually optimizes in long-horizon coding tasks. It covers cost-penalized reward design, length-weighted reward baselines, and techniques for controlling rollout length oscillation, followed by the three main sources of evaluation discrepancies: shared origin between training and evaluation, harness differences, and benchmark version changes. The article closes with practical recommendations for fixing the evaluation coordinate system, designing rewards, unifying training and inference frameworks, building internal regression sets, and improving observability.

    1. Breaking Down the Phenomenon: Doubling a Benchmark Score Does Not Double Model Capability

    In the coding agent space, we often see claims that a general-purpose base model, after reinforcement learning, substantially outperforms later versions of that base on coding benchmarks. The controversy is rarely about the numbers themselves; it is about whether the comparison happens within the same coordinate system.

    To judge whether an improvement is credible, at least four layers need to be separated:

    1. Whether the base is the same lineage: post-trained and base models share the same pretraining corpus and architecture. Reinforcement learning only shifts the behavior distribution; it does not raise the underlying knowledge ceiling.
    2. Whether the training objective aligns with the evaluation objective: if the evaluation set comes from the same source as the training environment, scores are naturally inflated.
    3. Whether the execution framework is identical: the same model can differ by several percentage points across agent frameworks that vary in tool-calling protocols, context management strategies, and retry mechanisms.
    4. Whether the evaluation criteria are strict: an evaluation set that reviews patches from an open-source maintainer’s perspective introduces many “instant fail” conditions, so passing ordinary unit tests can still score zero.

    A more accurate phrasing of “doubling,” then, is: a relative improvement under a specific evaluation standard and a specific execution framework, not an absolute gain in general programming ability.

    2. What Reinforcement Learning Actually Optimizes in Coding Agents

    The biggest difference between coding tasks and ordinary question answering is long-horizon execution: a single request may involve locating files, understanding call chains, editing code in several places, running tests, and rolling back and retrying based on errors, with chains that easily span dozens of tool calls. Reinforcement learning here does not solve “can the model write code”; it solves “can the model keep the objective from drifting across a long chain.”

    2.1 Reward Function with Cost Penalties

    If the only reward is whether the final tests pass, the model tends to call tools without restraint and pile up context, effectively trading compute for score. Once a cost term is introduced, the reward can be abstracted as:

    1. R_total = R_task - λ * Cost(steps, tokens, tool_calls)

    Here R_task is task completion, Cost is the chain overhead, and λ controls cost sensitivity. Two engineering practices are common: normalize the cost so its scale does not overpower the task reward, and apply segmented penalties to overly long chains so the model does not oscillate between “almost done” and “keep fiddling.”

    2.2 Length-Weighted Reward Baseline

    Policy gradient methods rely on a baseline to reduce variance. Return length in coding tasks varies enormously, so a single global baseline systematically overestimates short-chain samples and underestimates long-chain ones, making the policy update direction jitter. The idea behind a length-weighted baseline is to bucket baseline statistics by response or trajectory length, so samples of similar length are compared among themselves, removing “length” as a confounding variable from the advantage function.

    Illustrative logic:

    1. # Maintain baselines per trajectory-length bucket to reduce length-induced variance
    2. buckets = {}
    3. def baseline_for(traj):
    4. key = len(traj) // bucket_size
    5. return buckets.setdefault(key, running_mean())

    2.3 Managing Rollout Length Oscillation

    This is the most typical stability problem in long-horizon reinforcement learning: early in training the model learns to “try a few more times” and rollouts grow longer; the cost penalty then pushes it back toward “do fewer steps,” so length swings back and forth and the training curve struggles to converge. Common remedies include:

    • Smoothing length constraints: use continuous penalties instead of hard truncation to avoid abrupt reward changes;
    • Phased penalty coefficients: emphasize task reward early and gradually increase the cost weight later;
    • Trajectory-level normalization: standardize advantages within each group so a few extremely long samples do not dominate the gradient;
    • Unified early stopping and truncation: use the same maximum step count and timeout settings in training and evaluation to avoid distribution shift.

    3. Three Sources of Evaluation Discrepancy: Why the Same Model’s Score “Changes Face”

    3.1 Information Advantage from Shared Origin Between Evaluation Set and Training Side

    When the evaluation criteria are designed by the same team and the training pipeline runs inside the same execution framework, the model’s adaptation to “scoring preferences” is natural. Newer evaluations often deliberately leave requirement descriptions underspecified, no longer hard-coding implementation details, and instead add veto conditions based on open-source pull request review standards, for example:

    • Only a defect on path A is required to be fixed, but the same class of problem also appears on path B; failing to handle it scores zero;
    • Existing input types elsewhere in the repository are not supported, so the patch scores zero even though standard tests pass;
    • The repository’s established style and interface conventions are not followed.

    Such criteria are extremely sensitive to targeted adaptation, and general models typically lose points when migrated to them. That is a property of the evaluation design, not a capability regression.

    3.2 Harness Differences

    Performance differences for the same model across frameworks come mainly from four places:

    Difference Impact on score
    Tool-calling protocol and parameter validation Different call failure rates directly consume usable steps
    Context compression and retrieval strategy Different accuracy in locating code in long repositories
    Failure retry and rollback mechanisms Determines whether the agent can recover from errors
    System prompt and output format constraints Affects how often patches can be parsed

    A model whose reinforcement learning was completed in a native framework has a policy tightly coupled to that framework’s tool semantics. Moving it to a third-party framework is effectively swapping the action space, so a score drop is the expected result.

    3.3 Evaluation Set Version Iteration

    Upgrades from version 1.x to 2.0 typically come with underspecified prompts, more veto conditions, and reordered sample difficulty, pushing most models’ scores down overall. Comparing scores across versions is meaningless; comparisons must be made on the same version, the same framework, and the same budget.

    4. Actionable Recommendations

    1. Fix the evaluation coordinate system first: pin down the base version, evaluation set version, execution framework, maximum step count, and budget cap. If any of these change, rerun the baseline.
    2. Design rewards with “task first, cost as constraint”: the cost term should act only as regularization, never as the dominant term; start λ from a small value and increase it by training stage.
    3. Bucket baselines by length: this is a low-cost, high-return stability change that usually reduces training curve jitter noticeably.
    4. Keep training and inference frameworks as unified as possible: if cross-framework deployment is unavoidable, run a small-scale calibration evaluation rather than quoting scores from the original framework.
    5. Build an internal regression set: sample real repository tasks covering multi-path defects and multi-input-type compatibility to avoid overfitting to the evaluation set.
    6. Prioritize observability: log per-trajectory step counts, tool failure rates, context usage, and final verdict reasons; this multiplies the efficiency of problem localization.
    7. Compute and engineering support: large-scale rollouts can rely on elastic scaling from container platforms, object storage for trajectory samples, message queues to decouple sampling from training, and logging services with monitoring alerts to track convergence metrics. On Baidu AI Cloud, these general capabilities can be combined on demand to support a stable training pipeline.

    5. Conclusion

    What deserves attention in a “doubled benchmark score” is not the multiple itself, but what it reveals about the real leverage points in coding agent training: refined reward function and baseline design, engineering control of rollout length stability, and consistency of the evaluation environment. Get these three right and capability gains become reproducible and transferable. Discuss scores without the framework and evaluation version, and the conclusions have almost no reference value.