Improving Long-Horizon Task Capabilities of Code Agents with Reinforcement Learning
This article explores how to enhance the long-horizon task performance of code agents using Reinforcement Learning (RL). It breaks down benchmark score discrepancies into training-side and evaluation-side factors, introduces hierarchical verifiable rewards and length-bucketing baselines to stabilize rollouts, and provides a practical checklist for building reproducible and robust code agents in software engineering tasks.
1. Background: Score Differences Do Not Necessarily Reflect a Model Capability Gap
In code agent and software engineering tasks, it is common to observe the same base model scoring significantly differently across various versions, execution frameworks, and evaluation benchmarks. Meanwhile, an agent version optimized with reinforcement learning might show a massive lead on a specific benchmark. When encountering claims of “doubled benchmark scores,” engineers should avoid directly attrib this to “doubled general model capability.” Instead, the issue should be decomposed into training-side and evaluation-side factors.
Training-side factors include: long-horizon task data construction, reward function design, rollout length stability, policy update constraints, curriculum learning, and data ratios. Evaluation-side factors include: benchmark strictness, review rules, execution host consistency, tool calling protocols, context management, failure retry strategies, and whether the evaluator and the trainer share the same engineering assumptions. Only by separating “model capability” from “evaluation conditions” can we explain why certain versions show obvious advantages on specific leaderboards, but see the gap narrow in general evaluations or third-party retests.
2. Training Side: The Key to Long-Horizon RL is “Verifiable Rewards”
Long-horizon tasks for code agents typically involve multi-file reading, bug localization, modification, testing, and regression verification. If only the final unit test pass is used as a reward, the signal is sparse and easily “fooled” by local patches. A more robust approach is to construct hierarchical rewards:
- Outcome Rewards: Whether the task is completed, whether tests pass, and whether regressions are introduced.
- Process Constraints: Whether the correct path was modified, whether existing input types are compatible, and whether similar bugs are handled.
- Cost Penalties: Penalties for excessive tool calls, overly long contexts, and repeated attempts to suppress invalid long trajectories.
- Length-Weighted Baseline: Estimating the baseline by bucketing trajectory lengths to reduce the systematic advantage long trajectories gain from reward accumulation.
The schematic pseudocode is as follows:
for batch in rollout_tasks:trajectory = agent.run(task)reward = success_reward(trajectory)reward += partial_credit(trajectory)reward -= cost_penalty(trajectory.tool_calls, trajectory.tokens)bucket = length_bucket(trajectory.length)advantage = reward - baseline[bucket]policy.update(advantage, kl_constraint)
Here, the length bucket baseline serves a specific purpose: when successful tasks naturally favor longer trajectories, a standard baseline will cause the policy to lean towards “the longer, the better.” After bucketing, comparing advantages within the same length interval mitigates length inflation. The cost penalty incorporates “invalid exploration” into the optimization objective, prompting the agent to stop earlier and reduce repetitive tool calls.
3. Stability: Causes and Control of Rollout Length Oscillation
When training code agents with RL, rollout length oscillation is a common issue. Its manifestation is that the policy suddenly favors extremely long trajectories after several update rounds, followed by a sharp drop due to cost penalties or truncation, leading to training instability and increased reward variance. Common causes include:
- Successful samples are concentrated in long trajectories, and baseline estimation bias amplifies length advantages.
- Outcome rewards are sparse, and the policy increases steps to “try its luck.”
- Retry strategies after tool call failures are not modeled, creating a pseudo-correlation between length and success rate.
- Sudden changes in the difficulty distribution of training data, with insufficient curriculum learning.
- KL constraints are too loose, causing rapid policy drift.
Engineering solutions can adopt a combination of measures: length bucket baselines, difficulty-based curriculum sampling, segmented truncation of overly long trajectories with partial rewards, increased penalties for tool call failures, dynamic adjustment of KL constraints, and monitoring the success rate and cost of each length bucket. The focus is not to simply limit the length, but to ensure “necessary length” is rewarded and “redundant length” is penalized. Training logs should record length distribution, success rate, number of tool calls, and reward breakdowns to facilitate locating the source of oscillation.
4. Evaluation Side: Strict Benchmarks and Execution Hosts Amplify Gaps
Score differences often originate from the evaluation benchmarks themselves. If a benchmark upgrades from “explicit requirements + unit test pass” to “executed according to open-source maintainer review standards,” incorporating numerous implicit compatibility requirements, ordinary models are likely to lose points. For example: a task only requires fixing a bug in path A, but path B has a similar problem; or the modification does not accommodate existing repository input types. Unit tests might pass, but strict reviews will veto it. Such benchmarks are closer to real-world merge request reviews. If the training data does not cover these review patterns, model performance will drop significantly; conversely, if training and evaluation share similar assumptions, the advantage is amplified.
The execution host is equally critical. An agent trained on a specific command-line host, tool protocol, and context compression strategy will experience changes in tool call formats, failure recovery, and context window management when moved to another host. In third-party retests, the same model showing considerable score differences when switching execution hosts indicates that “host adaptation” is a significant source of evaluation variance. Therefore, when comparing different models, the host should be fixed, or at least cross-tested on multiple hosts, reporting confidence intervals and failure type distributions.
5. The Trade-off Between Specialized and General Capabilities
Specialized RL can significantly improve long-horizon code tasks, but it does not necessarily mean that general reasoning is comprehensively ahead. In multi-objective training, data ratios, model capacity, and training steps must be allocated across directions like coding, general reasoning, and multimodality. If a version leads significantly on a specific code benchmark, it might be because the training data is closer to the task format of that benchmark, the reward function matches the review rules better, or the execution host is more consistent, rather than all capabilities improving simultaneously. Evaluations should be reported across dimensions: bug fixing, compatibility, regression control, long-context localization, and tool usage efficiency.
6. A Practical Checklist for Reproducible Results
- Fix the execution host and tool protocols, and record complete trajectories and failure reasons.
- Retest on at least two or more hosts to avoid single-host overfitting.
- Split the reward function into four parts: outcome, process, cost, and length, and perform ablation studies.
- Use a length bucket baseline and monitor the success rate and average cost of each bucket.
- Construct data involving implicit compatibility and similar bugs to prevent fixing only explicit paths.
- Conduct manual spot checks under strict review rules to distinguish between “unit test pass” and “mergeable.”
- Report means, variances, and confidence intervals instead of comparing only single highest scores.
In summary, significant leads on software engineering benchmarks by code agents are usually not the result of a single technique, but the combined effect of long-horizon task data, verifiable rewards, rollout stability control, and evaluation conditions. Engineering teams should treat benchmark scores as “observations under a specific training-evaluation loop.” Only through multi-host retesting, reward ablation, and strict review reproduction can the true capability boundaries be determined.
