Reinforcement Learning for Long-Horizon Coding Tasks: Practical Training and Evaluation
Training coding agents for long-horizon software engineering requires more than a stronger base model. This article examines verifiable rewards, length-aware advantage baselines, rollout stability, data curricula, and evaluation protocols, with practical guidance for distinguishing genuine policy improvements from benchmark-specific adaptation.
Long-horizon software engineering tasks differ fundamentally from single-turn code completion. In a typical completion task, the model receives a clear function signature, input and output requirements, and limited context. Its response can be scored immediately.
A long-horizon task requires an agent to inspect a repository, locate a defect, modify multiple files, run tests, revise its changes based on failures, and deliver a mergeable patch within a budget. A retrieval, editing, or verification error at any intermediate step can derail the rest of the trajectory.
Simply replacing or scaling up the base model therefore does not reliably improve success rates. Training signals, trajectory sampling, and evaluation protocols often matter more than parameter count.
Where Capability Gains Come From
Interpreting a “doubling of coding benchmark scores” as a sudden improvement in the base model usually overstates what a single release demonstrates. More often, reinforcement learning for long-horizon interaction teaches a comparable base model to take fewer wrong turns within a fixed orchestration environment.
The model may not understand every language or domain better. Instead, it may become more consistent at following an effective sequence: reproduce the failure, make a minimal change, and run regression tests. It may also become more likely to reread failure logs rather than repeatedly submit similar patches.
These gains have three important limits:
- Dependence on tool interfaces. If file-reading, search, patching, or test-execution tools return different formats during evaluation than during training, the learned policy may fail.
- Dependence on verifiable outcomes. Optimization for automatically judged results may not transfer equally well to tasks with ambiguous requirements or implicit acceptance criteria.
- Dependence on the training distribution. Data concentrated on one defect category may not improve general editing, user interface, or 3D-related tasks. Distribution shifts may even weaken performance on those tasks.
Benchmark comparisons should therefore disclose the base model, orchestration environment, tool permissions, timeouts, and retry limits. Without these details, scores are difficult to interpret.
Rewards Should Capture More Than Final Success
Credit assignment is a central challenge in long-horizon trajectories. A task may involve dozens of steps, yet the training system only learns whether the tests pass at the end. With a reward of only 0 or 1, many exploratory actions remain indistinguishable, and the policy can drift toward large, speculative changes.
A more reliable approach is to separate the reward into verifiable components rather than invent detailed scores that cannot be checked:
- Outcome reward: Award the main positive reward only when hidden tests or agreed checks pass. This discourages overfitting to visible examples.
- Cost penalty: Penalize token consumption, tool calls, repeated reads, and ineffective edits to encourage short, productive trajectories.
- Constraint penalty: Penalize or terminate trajectories involving unauthorized changes, deleted tests, hardcoded answers, or unbounded retries. This limits reward exploitation.
- Sparse process reward: Give small rewards only for objectively verifiable events, such as reproducing a failing case, producing an applicable patch, or changing relevant tests from failing to passing. Process rewards must be automatically verifiable; otherwise, annotation noise becomes part of the learned policy.
Cost penalties must match task difficulty. Excessive penalties encourage the model to abandon difficult tasks too early. Weak penalties lead to longer trajectories, higher variance, and lower training throughput.
One option is within-group normalization: compare the costs of trajectories sampled for the same task rather than applying a global threshold based on absolute length.
Why a Length-Aware Baseline Matters
In policy-gradient training, advantage is the return minus a baseline. If the baseline ignores trajectory length, differences in accumulated costs or success achieved through additional attempts can systematically distort the advantages of longer trajectories. The result may be a bias that rewards length itself or suppresses any moderately long attempt.
A length-aware baseline compares a trajectory with the average return of trajectories of similar length or step count. The goal is for advantage to primarily reflect whether the agent performed better under a comparable budget.
The following example illustrates the structure:
def advantage(rewards, lengths, bucket_size=8):# rewards/lengths: a group of samples for the same promptorder = sorted(range(len(rewards)), key=lambda i: lengths[i])adv = [0.0] * len(rewards)for start in range(0, len(order), bucket_size):idx = order[start:start + bucket_size]baseline = sum(rewards[i] for i in idx) / len(idx)for i in idx:adv[i] = rewards[i] - baselinereturn adv
There is no universally suitable bucket size. Narrow buckets produce high-variance baselines; wide buckets can reintroduce length bias.
Validation should examine whether successful trajectory lengths have a unimodal distribution, whether failed trajectories stop growing without bound, and whether gradient norms remain stable. Length-aware baselines improve the basis for comparison; they do not replace correctness judgments.
Controlling Episode-Length Oscillation
Reinforcement learning can produce a recurring oscillation in episode length. In one iteration, the policy becomes more active: trajectories grow longer, timeouts increase, and the batch becomes harder. In the next iteration, pressure to reduce costs causes premature stopping and lower success rates. Exploration then expands again.
The visible symptom is large, periodic swings in loss and average step count rather than steady improvement.
Common causes include:
- Discarding timeout samples, effectively retaining only short successful samples.
- Increasing cost penalties abruptly.
- Failing to normalize advantages within groups.
- Using a learning rate that is too sensitive to sparse rewards.
- Allowing task difficulty to vary substantially across batches.
Several independent stabilization measures can be combined:
- Use a consistent return definition for timeouts and normally completed episodes instead of silently dropping timeout samples.
- Normalize advantages within each group and limit the gradient contribution of unusually long trajectories.
- Use a curriculum to set a conservative initial step limit, then relax it as success rates improve rather than allowing extremely long episodes from the start.
- Mix in some supervised trajectories or short successful trajectories selected through rejection sampling to provide a stable behavioral anchor.
Monitoring should include at least success rate, median step count, timeout rate, repeated tool-call rate, and patch size. A final leaderboard score alone will not reveal that oscillation has begun.
Training Data and Curriculum Design
High-quality tasks should reflect real software changes: defect localization, interface compatibility, error handling, and regression testing. A dataset consisting only of single-function toy problems does not adequately represent long-horizon work.
Each task should ideally include executable checks without forcing one unique implementation. Inputs should preserve repository conventions, relevant paths, and observed failures, but need not explain how to construct the patch.
A curriculum can progress through:
- Reproducible defects in a single file.
- Similar defects spanning multiple files.
- Tasks requiring additional boundary-case inputs.
If training covers only the path explicitly named in a prompt, the policy may learn to make local fixes. Performance can then drop sharply when acceptance requires fixing analogous paths or preserving compatibility with existing input types. This is a mismatch in objectives, not a mysterious benchmark effect.
Data leakage must also be controlled. Evaluation repositories, public solutions, and training trajectories need to remain separate. Otherwise, apparent gains may primarily reflect memorization rather than better search and editing strategies.
Why Evaluation Protocols Change Scores
The same model can receive different scores under different execution frameworks for four main reasons.
1. Prompt Specifications Differ
Some evaluations fully specify the expected behavior. Others describe only the symptoms and leave requirements implicit, while applying acceptance criteria similar to a maintainer’s code review.
Under the latter approach, a patch may fail because it leaves analogous defects outside the named path unresolved, breaks existing calling conventions, or weakens tests. Underspecification combined with disqualifying criteria can lower scores for models that were not trained for those expectations. That decline should not automatically be interpreted as degradation of the base model.
2. Policies Are Coupled to Orchestration
A policy trained with particular tool-output formats, retry rules, and context-trimming behavior may lose effectiveness when file-reading or test-execution wrappers change.
This demonstrates environment adaptation, not that another framework is inherently “more realistic.” Fair comparisons should either hold orchestration fixed or report results across multiple orchestration environments.
3. Budgets Differ
Maximum step counts, timeouts, and permission to rerun tests all affect the fraction of long-horizon tasks an agent can solve. Comparisons that omit budget details do not support meaningful conclusions.
4. Task Versions Differ
If scores fall across all models after an evaluation set is revised, the cause may be increased difficulty or changed scoring rules. That should not be conflated with model iteration.
Published results should include the task-set version, random seeds, sample size, and failure-category distribution.
How to Judge Whether an Improvement Is Credible
Use the following checklist rather than relying on a single aggregate score:
- Are base-model training data and subsequent training data separated from evaluation tasks, and is there evidence that gains are not due to memorization?
- Are training and evaluation orchestration identical? If so, has the result been checked under another fixed orchestration setup?
- Which costs and constraints are included in the reward, and how are timeout samples counted?
- Are successful trajectory lengths stable, or do they show periodic oscillation?
- Are prompts fully specified or intentionally underspecified? Do failures reflect incorrect code or a disqualifying acceptance criterion?
- Beyond the total score, are failures categorized—for example, incorrect localization, ineffective patches, test manipulation, or premature abandonment?
If a model leads substantially on an in-house evaluation but improves only modestly on independent tasks and orchestration, the appropriate conclusion is that “policy optimization is effective under this protocol,” not that “general coding capability has doubled.”
The reverse also matters. More investment in a specialized task may displace general repair data, strengthening the specialty while weakening long-horizon repair. Separate evaluations are needed; one aggregate score cannot establish the trade-off.
Engineering Considerations for Deployment
On the training infrastructure side, object storage is suitable for trajectory logs, patches, and test outputs. Task queues schedule parallel sampling, container platforms isolate build and test environments, and logging and monitoring help detect rising timeout rates and step-count oscillation.
These are general infrastructure capabilities, not dependencies on a proprietary interface. Baidu AI Cloud is one platform where object storage, container environments, and monitoring can support these roles, subject to the services available in the deployment region. Quotas, billing, and configuration must be checked against the documentation for the services actually provisioned. An undocumented dedicated training interface should not be assumed to exist.
For experiment management, change only one factor at a time: reward weights, the length-aware baseline, the step limit, or the data curriculum. Retain validation curves and failure examples to distinguish better code-editing behavior from better adaptation to a particular scoring script.
The following per-task reward example illustrates only the structure. Its weights must be recalibrated for the task and should not be treated as defaults:
def trajectory_reward(passed, cost, violated, weights):if violated:return weights["violation"] # Negative constant; terminate invalid trajectoriesscore = weights["pass"] * float(passed)score -= weights["cost"] * costreturn score
Conclusion
Visible gains in long-horizon coding agents largely depend on verifiable rewards, baselines that reduce length bias, sampling strategies that control episode oscillation, and evaluation protocols that either match training or disclose their differences clearly.
Interpreting scores within these conditions makes it possible to decide whether the next investment should target training stability or first address underspecified evaluation requirements and environment coupling.
