Reinforcement Learning for Long-Horizon Coding Agents: Reward Design and Evaluation Pitfalls

    Post-training coding agents is often reduced to "run more reinforcement learning rounds and the score goes up." In practice, the real differentiators on long-horizon tasks are how rewards are defined, how trajectories are sampled, and which execution environment the agent is evaluated in. This article examines why sparse pass/fail signals break down on repository-level tasks, how cost penalties and length-conditioned baselines improve training stability, why trajectory length oscillation signals instability, and how much of a leaderboard gap may simply reflect evaluation conditions rather than genuine capability gains.

    Reinforcement Learning for Long-Horizon Coding Agents: Reward Design and Evaluation Pitfalls

    Post-training for coding agents is often reduced to “run more RL rounds and the score goes up.” In engineering practice, the base model usually already has the basic abilities to write patches, run tests, and navigate a repository. What actually separates strong agents from weak ones is how rewards are defined on long-horizon tasks, how trajectories are sampled, and which execution environment the agent is placed in during evaluation. Score differences can be substantial—on a single leaderboard they can even look like a doubling—but they may come from cleaner training signals, or from evaluation and training environments being highly aligned. Separating these two effects is more valuable than chasing a single number.

    What Makes Long-Horizon Coding Tasks Hard

    For short Q&A or single-function completion, feedback is nearly instantaneous: right or wrong, pass or fail. Repository-level changes are different. An agent must locate files across multiple turns, understand implicit constraints, modify code, run tests, and iterate based on logs—all mixed with a large amount of exploration unrelated to whether the final change gets merged. A single trajectory can be very long, and successful samples are rare.

    Three structural difficulties stand out.

    First, credit assignment spans a long horizon. The final test passing does not reveal which intermediate step was decisive; a large, seemingly reasonable refactor midway can push later search into a dead end.

    Second, the action space is open-ended. The model can keep reading files, editing unrelated modules, or rerunning similar commands. If the reward only checks “did it pass in the end,” the policy learns to buy marginal success-rate gains with longer, more expensive trajectories.

    Third, requirements are often incomplete. Real maintainers review patches against more than “does the bug on the specified path disappear.” They check whether the same class of issue recurs on other paths, whether existing input types in the repository still work, and whether unrelated changes were introduced. If the evaluation hard-codes these implicit standards while the prompt deliberately leaves them unstated, a large gap appears between “passing the unit tests” and “mergeable by maintainer standards.”

    So post-training should not be understood as making the base model “twice as smart.” It should be understood as helping the policy more reliably find acceptable patches under incomplete specifications, long trajectories, and expensive execution.

    Rewards Should Not Look Only at Final Correctness

    With only sparse pass/fail signals, policy-gradient variance is high, and optimization drifts toward “keep trying until it passes, regardless of cost.” A more robust approach is to add explicit process constraints on top of correctness. Two common and conceptually clean designs follow.

    Cost-penalized rewards. Give positive reward for task success while penalizing tool-call counts, trajectory length, repeated commands, unrelated file changes, or failed executions. A typical form is: success reward minus accumulated cost penalties, with failure receiving mainly the cost plus a small negative reward. This pushes the policy toward shorter, effective paths instead of unbounded search.

    Penalties must be interpretable and reproducible. Mixing subjective preferences like “elegant refactoring” into the main reward turns labeling noise directly into policy noise. Cost terms should come from objective counts in the execution environment: steps, commands, lines changed, test reruns, and so on.

    Length-conditioned reward baselines. In RL, the advantage function is typically “return minus baseline.” Long trajectories have higher return variance; if all samples share one global baseline, short successes and long failures contaminate each other’s estimates. Bucketing trajectories by length, or conditioning the baseline estimate on length, lets comparable-length samples be compared: among trajectories that took many steps, which made more effective progress; among those that finished quickly, which actually solved the problem and which gave up too early.

    Neither technique is mysterious on its own, but together they change the optimization direction: the model stops chasing “one lucky pass” and starts optimizing for “passing reliably within an acceptable cost.” On long-horizon tasks, this alone can visibly shift a base model’s leaderboard standing. What it mainly improves is search efficiency and stability within a task—it does not necessarily raise the model’s ceiling across every coding format.

    A schematic advantage estimate can stay simple; what matters is that the comparison group is matched:

    1. advantage = (task_reward - cost_penalty) - baseline(length_bucket)

    There is no magical new loss here. task_reward comes from tests and rule checks, cost_penalty comes from environment counters, and baseline is estimated only over trajectories of similar length. The critical implementation detail: the scale of the cost term must be comparable to the task reward. Otherwise the penalty either has no effect, or the model refuses to finish tasks in order to save steps.

    Trajectory Length Oscillation Is a Classic Symptom of Instability

    A frequently overlooked phenomenon in long-horizon RL is trajectory length swinging back and forth. In one phase the policy becomes “diligent”—step counts rise and occasional success rates improve. In the next, cost penalties or timeouts crush it into “stopping too early” and scores drop again. The optimizer oscillates between two local behaviors; the loss curve may look converged while evaluation results seesaw.

    Length oscillation is rarely caused by a single hyperparameter. It usually results from several factors stacking up:

    • Too few successful samples, so advantage estimates get dominated by a handful of very long trajectories.
    • Timeout truncation merges “not finished yet” with “confirmed failure” into the same negative signal, so the model cannot tell whether to continue or stop.
    • Reward scales shift with repository size and test duration, so the same coefficients mean completely different things across tasks.
    • When sampling temperature or tool error rates rise, trajectories get longer—but longer does not mean more effective exploration.

    Practical stabilization measures include: truncating and bucketing trajectory lengths so that extremely long samples do not monopolize gradients; normalizing cost penalties so that step counts are comparable across repositories; assigning different returns to “reached a definitive failure conclusion” versus “timed out unfinished”; estimating baselines with a sliding window instead of a single batch; and monitoring quantiles of the length distribution, not just mean return. When the average step count is stable but the long tail suddenly thickens, oscillation is often imminent.

    The value of these measures is making the training curve interpretable. If only the final leaderboard score is reported, outsiders cannot distinguish “better reward design” from “sampled a few lucky long trajectories.”

    How Much of the Score Gap Comes from Evaluation Conditions

    Even if training genuinely improved, a large gap on a single leaderboard cannot be read directly as a doubling of general coding ability. At least four conditions systematically amplify score differences.

    Evaluation and training share the same execution environment. The agent’s available tools, working-directory conventions, test entry points, retry behavior, and log formats together form the scaffold. A policy trained with RL inside one scaffold internalizes that environment’s idioms: which check to call first, what failure logs look like, when to stop. Moved to a different command line or generic executor, the same base model may immediately lose a chunk of score. This is not “the model suddenly got dumber”—the policy learned environment details too. Fair comparison should at minimum fix the scaffold, or report results under multiple scaffolds.

    Information asymmetry between benchmark authors and trainers over grading details. If a leaderboard is maintained by the same organization that trains a model, and a new version adds many unstated veto conditions, the party that knows these veto rules best can more easily cover them in data and rewards ahead of time. Scores dropping across the board on a new version is unsurprising: the specification got stricter. One model dropping less may indicate better targeted coverage, not stronger base reasoning.

    Prompt omissions and one-strike vetoes. Evaluations can deliberately under-specify requirements: fix a defect on one path, but if the same issue exists on another path, or the patch breaks existing input types the repository already supports, the entire task scores zero. Ordinary unit tests may still pass. This design is closer to real code review and better distinguishes “can patch” from “can finish to maintainer standards.” Its side effect: models without data coverage against that grading rubric drop collectively, and rankings become extremely sensitive to whether a model has seen such veto rules.

    Task distribution shift. If a team invests heavily in games, 3D, or specific interaction formats during a period, performance on general repository repair may weaken relatively; conversely, pushing all data and rewards onto one class of bug fixes sacrifices other coding formats. When a leaderboard covers only one distribution, it cannot answer whether general ability was diluted.

    More useful questions when reading a leaderboard: were the baseline model, tool permissions, timeouts, and sampling counts identical across systems? Were failures functional errors, or triggered by undisclosed veto rules? Did score gains come with cost reductions, or were they bought with longer trajectories? Without this information, multiple-order differences carry only promotional meaning.

    Design Controlled Experiments, Not Leaderboard Chasing

    Teams applying RL to coding agents should structure experiments into falsifiable layers rather than directly comparing “our score versus their score.”

    1. Fix the base model, change only the reward. Compare pure success reward, success minus cost, and length-conditioned baselines. Record pass rate, median steps, timeout rate, and the proportion of unrelated changes. Only if pass rate rises while cost falls is the reward design actually working.
    2. Fix the reward, change the scaffold. Evaluate in at least two execution environments. If the advantage exists only in the training environment, the conclusion should be “in-environment policy optimization works,” not “leading in coding ability overall.”
    3. Make veto rules explicit. Track separately whether same-class issues were fully fixed, whether existing input types broke, and whether unrelated changes were introduced—rather than looking only at total score. This reveals whether the model genuinely finishes better, or merely memorized a grading rubric.
    4. Monitor the length distribution, not just the mean. Quantiles, timeout share, and repeated-command rates expose oscillation early. During unstable training, do not report a single best checkpoint.
    5. Report specialized and general results separately. Repository repair, algorithmic problems, and UI or graphics generation should not collapse into one “coding ability” number. Rising data investment in one direction at the cost of another is capacity allocation, not an accident.

    Restraint matters on the data side too. Rather than stacking problems that superficially resemble benchmark items, cover failure modes: missing same-class fixes on other paths, test fixtures diverging from real call sites, treating symptoms instead of shared logic, and deleting assertions to make tests pass. These samples map directly to the sources of one-strike vetoes and are closer to actual maintenance work.

    Conclusion

    RL on long-horizon coding can拉开—can widen the gap between systems built on the same base model. The core levers are usually cost constraints in the reward, length-matched baselines, and stabilization against trajectory length oscillation, not mysterious new algorithms. At the same time, evaluation scaffolds, prompt omissions, and implicit veto rules can amplify “can this agent finish by this rubric” into a score chasm.

    So when a coding model dramatically outperforms its base model on a single leaderboard, the reasonable interpretation is: it may be better at completing long tasks in a specific environment under specific cost constraints. Whether this represents a multiple-fold improvement in general coding ability depends on controlled comparisons across scaffolds, across failure types, and across task distributions. Only when rewards, stability, and evaluation conditions are documented together do scores become engineering metrics rather than stories.