Long-Horizon Coding Reinforcement Learning: Rewards and Evaluation

    This article explains why long-horizon software engineering tasks are difficult for reinforcement learning, how to design rewards that balance correctness, review constraints, and cost, how grouped baselines can control trajectory-length oscillation, why leaderboard gains may be tied to the evaluation environment, and what practical training and evaluation practices make results more transferable.

    Long-horizon software engineering tasks require an agent to read code in a real repository, locate defects, modify multiple files, run tests, and keep iterating from failure information until the change is mergeable. The difference from single-turn code completion is not whether the model can write a function. The difference is the length of the decision chain: every step consumes context, tool calls, and compute budget, and any misjudgment along the way can invalidate the rest of the trajectory. When the industry uses reinforcement learning to further optimize such policies on top of a base model, leaderboard scores can sometimes be much higher than those of a model without same-distribution post-training. It is not rigorous to interpret the gain as “the base model suddenly became twice as strong.” More often, the reward is closer to the review criteria, sampling is more stable, and the evaluation environment heavily overlaps with the training environment. The following sections cover five parts: task characteristics, rewards, stability, evaluation bias, and engineering deployment.

    What Makes Long-Horizon Tasks Hard

    A software engineering trajectory can be viewed as a finite-horizon sequential decision process. The state includes the current repository snapshot, files already read, terminal output, and acceptance conditions that remain unmet. Actions include retrieval, editing, running commands, and writing commit messages. Returns are often extremely sparse: only final test passage or review approval provides a positive signal, while dozens of intermediate steps provide almost no gradient.

    Sparse returns have three direct consequences. First, successful trajectories are rare, advantage estimates have high variance, and the policy tends to oscillate in noise. Second, the model is incentivized to trade longer trial and error for occasional success, so length and cost both inflate. Third, a small distribution shift—for example, prompts no longer hard-code the path, input type, and boundary conditions—can break a policy that previously “happened to match the test.” Therefore, post-training usually should not focus on adding more general-purpose corpus. It should align rewards, baselines, and data distribution with “maintainable patches,” not “patches that happen to turn green.”

    Rewards Must Account for Both Correctness and Cost

    Rewarding only “tests pass” encourages test gaming: repeated runs, meaningless refactoring, loosening assertions, or fixing only the single path named in the prompt. A more reasonable reward separates outcome, constraints, and cost.

    The outcome term gives a positive score only when objective checks pass, and the checks should cover existing regressions rather than only a single newly added test case. The constraint term corresponds to vetoes in review: missing other instances of the same defect, breaking existing input types, introducing unrelated large-scale formatting changes, or lacking necessary compatibility notes. Once such a condition is triggered, the outcome score should go to zero or be heavily discounted, preventing a high score when “the main path is correct but the repository semantics are wrong.” The cost term penalizes tool-call count, generated tokens, failed retries, and final diff size. A common form is to subtract a term proportional to length or expense from the success reward, so an equally correct short trajectory beats a long one.

    As an illustration, the return of a trajectory can be written as:

    1. R = I(pass) * (R_success - λ_veto * V - λ_cost * C) - λ_fail * (1 - I(pass)) * C_partial

    Here I(pass) indicates whether acceptance passed, V is the count of veto items, C is normalized cost, and C_partial prevents failed trajectories from endlessly trying without any penalty. The coefficients must be calibrated on a validation set: if the cost weight is too large, the model gives up too early; if it is too small, length grows out of control. This formula is a teaching abstraction, not a fixed interface for any particular platform.

    Process rewards require caution. Giving credit for “read relevant files” or “ran tests” can alleviate sparsity, but it is easily gamed through repeatedly opening the same file or running idle commands. A safer approach is to use process signals mainly for advantage baselines or curriculum sampling weights, rather than adding them directly to the main reward that can be maximized.

    Length Oscillation and Baselines

    When reinforcement learning samples programming trajectories, a common instability appears: one batch suddenly becomes longer, with more timeouts and truncations, and the next batch becomes collectively shorter and stops too early. This is trajectory-length oscillation. The causes usually compound. If advantage estimation uses the mean return of the whole batch as the baseline, an occasional high score from a long trajectory raises the baseline, short trajectories are all judged negative, and the policy then learns to “go a little longer.” Context-window or step limits truncate overly long samples into failures, and gradients push the policy back. If the cost term in the reward is subtracted from unnormalized absolute length, tasks of different difficulty are mixed in the same batch, making the baseline even less comparable.

    The mitigations are reproducible in engineering and do not depend on a proprietary training framework.

    • Estimate baselines by task or difficulty bucket, so short successes on easy problems and long successes on hard problems do not contaminate each other.
    • Use length-weighted or group-normalized return baselines: compare “who does better under the same budget,” not “who has the higher absolute score.”
    • When doing truncated value estimation for overly long trajectories, explicitly record an incomplete penalty; do not treat truncated samples as ordinary failures or ordinary successes.
    • Move the curriculum from short fixes to cross-file edits, limit the maximum number of steps at each stage, and raise the step cap slowly as the success rate improves.
    • Monitor length quantiles, truncation rate, and cost per success, not only average pass rate. If average score rises while P90 length runs away, the next stage is often about to collapse.

    A cost-penalized reward combined with grouped baselines essentially says: the policy should optimize for “stable delivery within budget,” not “search indefinitely until it happens to get it right.”

    Why the Same Model Can Score Very Differently

    If evaluation shares the same execution scaffold as training, scores will be systematically inflated. The agent learns the tool semantics, retry format, and stopping conditions of that environment. With a different command line or general agent framework, these habits may become a burden. A score drop after a third party changes the environment does not necessarily mean the weights are invalid; it only means part of the capability is environment-bound.

    Under-specified prompts further amplify the gap. Suppose a task deliberately leaves requirements sparse and only asks to fix one path, but scoring checks against maintainer review standards: whether similar defects are handled together, whether other valid inputs remain compatible, and whether the change is minimal. A model can pass ordinary unit tests and still receive zero. Models not trained for that rubric will drop across the board; systems that helped define the rubric and used similar rules for reinforcement learning look as if they “saw the exam in advance.” This is not sufficient evidence of numerical fraud, but it is enough to show that a single leaderboard cannot serve as an unbiased estimate of general programming ability.

    When interpreting score gains, check at least four things: whether the evaluation set was defined or repeatedly revised by the training party; whether official numbers were produced only in the vendor’s own execution environment; whether prompts are complete enough to reproduce and veto rules are public; and whether the comparison model was allowed the same tools, step count, and retry budget. If any of these is missing, it is inappropriate to conclude that “general capability doubled.” If a base model allocates capacity to interaction, multimodality, or specific scenarios, a relative decline on a pure repository-repair leaderboard is normal, and it does not prove that post-training data must be problematic, or vice versa.

    Practical Training and Evaluation Practices

    Data should come from repository tasks that can be judged automatically: failing tests, minimal reproductions, and explicit non-goals such as “do not modify unrelated modules.” Annotation should focus on acceptance scripts and veto conditions, not on making people write a unique patch. Multiple correct fixes for the same defect should all count as success; otherwise the policy is locked into one style.

    Keep failed trajectories during sampling. Failures are the main body of long-horizon tasks. If they are discarded, cost penalties and early stopping cannot be learned. At the same time, perform decontamination: evaluation repositories, prompts, and patches must not appear in supervised fine-tuning or reward-model corpora.

    For the training loop, use small-step validation. Change only one reward component per round—for example, first add vetoes, then add cost—and compare pass rate, veto trigger rate, average cost, and length variance with fixed seeds. If a reward model uses another generative model for scoring, spot-check it with a rule-based checker to prevent both sides from learning to please comments rather than pass tests.

    Evaluation should include at least three independent settings: a scaffold isomorphic to training, another general tool loop, and a stress test in which some prompt information is removed. Reports should give intervals and failure types, not a single maximum score. The stress test is more informative: when only one path is named, does the model still check similar call sites? After tests turn green, does it proactively run adjacent cases?

    When deploying to an internal R&D workflow, restrict the agent to an isolated working copy, a read-only dependency cache, and an auditable command allowlist. Logs should retain edit diffs, test commands, and exit codes, so it is possible to determine afterward whether a failure was a model error or environment collateral damage. Object storage can archive trajectories, message queues can run evaluation asynchronously, container platforms can launch one-shot execution environments, and monitoring alerts can track truncation rate and cost percentiles. These are uses of generic cloud capabilities and do not require binding to a proprietary coding product.

    Conclusion

    In long-horizon coding reinforcement learning, what actually works is writing review criteria into the reward, using grouped baselines to suppress length oscillation, and bringing the training distribution closer to realistic under-specified requirements. A large lead over the base model often means the policy is better adapted to that acceptance process and scaffold; it cannot by itself prove that general coding ability has made a proportional leap. People doing training should disclose the environment, budget, and veto rules. People reading leaderboards should test again with a different scaffold and a different level of prompt completeness. Only when both sides align do score gains come closer to transferable engineering capability.