Optimizing Reward Design and Training Stability for Long-Horizon Coding Tasks with Reinforcement Learning

    This article examines the common engineering challenges of applying reinforcement learning to long-horizon coding tasks, focusing on reward design, baseline selection, rollout length oscillation, and evaluation environment variance. It explains why benchmark score jumps after post-training often reflect alignment or harness differences rather than genuine capability gains, and offers practical mitigations such as cost-penalized rewards, length-stratified baselines, soft length constraints, and a reproducible evaluation checklist for teams building code agents, automated repair, and repository-level training pipelines.

    Optimizing Reward Design and Training Stability for Long-Horizon Coding Tasks with Reinforcement Learning

    A recurring topic in technical communities is a phenomenon where a base model with already strong coding ability shows a multiplied score increase on some coding benchmarks after one round of reinforcement learning (RL) targeting software engineering tasks. Most of the debate around this focuses on whether the scores are trustworthy. But if you shift the perspective from “rankings” to “training methodology,” what developers should really care about is not the position on a leaderboard, but several shared engineering problems in RL for long-horizon coding tasks: how to design rewards, how to choose baselines, why rollout length oscillates, and how much variance the evaluation environment itself introduces.

    This article abstracts these problems into a reusable methodology for teams working on code agents, automated program repair, and repository-level task training.

    1. The conclusion first: score jumps usually don’t mean a stronger base model

    When a model’s score rises sharply after post-training, there are usually three possible sources that need to be separated:

    1. Genuine capability improvement: the model has actually learned longer-horizon task decomposition and stronger error recovery.
    2. High alignment between the training objective and the evaluation objective: the reward function or data distribution happens to cover the evaluation set’s decision logic.
    3. Systematic bias from the evaluation environment: differences in the harness (the agent runtime framework), prompt templates, and tool-calling conventions can cause noticeable score differences for the same model.

    The core skepticism in the original discussion lands on points 2 and 3: when a team controls both the “task generation criteria” and the “model training pipeline,” its self-reported scores naturally carry an alignment advantage. This is not a moral issue but a matter of common sense in evaluation methodology—once any benchmark shares the same decision logic as the training objective, its discriminative power drops.

    The practical takeaway for developers: don’t judge model capability by a single number; look at whether the model performs consistently across evaluation frameworks from multiple independent sources.

    2. Reward function design: the core difficulty in long-horizon tasks is that rewards are sparse and delayed

    Rewards in traditional RL are often immediate and dense, whereas feedback for repository-level coding tasks is naturally sparse: a single task may involve dozens of tool calls, several rounds of compilation and testing, and only one final “pass/fail” signal.

    2.1 Reward with a cost penalty

    A widely adopted practice is to add a resource cost term on top of the final reward, which can be abstracted as:

    1. # Illustrative pseudocode, not any specific product interface
    2. def reward(trajectory):
    3. task_score = evaluate_by_tests(trajectory) # 0/1 or graded score
    4. cost = token_cost(trajectory) + step_cost(trajectory)
    5. length_term = lambda * normalize_length(trajectory)
    6. return task_score - alpha * cost - length_term

    The key is the magnitude of alpha. If the penalty is too heavy, the model tends to “exit early” and submit an incomplete patch when it encounters a slightly harder task; if the penalty is too light, the model falls into meaningless repeated trial and error, filling the context with logs without reaching a conclusion. In practice, it usually takes different penalty coefficients bucketed by task difficulty rather than one global constant.

    2.2 Length-weighted baseline

    Policy gradient methods need a baseline to reduce variance. When the task length distribution spans a wide range (some tasks finish in three steps, others need hundreds), a single global baseline lets short tasks contribute too much gradient while long tasks get drowned out. The idea of a length-weighted baseline is to estimate expected return bucketed by trajectory length, so each length class gets a relatively unbiased advantage estimate. In engineering terms, this is equivalent to stratified normalization:

    1. baseline = {bucket: mean_return_of_bucket for bucket in length_buckets}
    2. advantage = return_of(traj) - baseline[bucket_of(traj)]

    This step often improves the stability of the training curve more than switching to a larger base model.

    3. Rollout length oscillation: the most typical failure mode in long-horizon RL

    The “rollout length oscillation” mentioned in the original text is a very real problem worth expanding on separately. It shows up as: average trajectory length rises steadily early in training, then swings violently up and down, and model capability collapses or stalls accordingly.

    The causes usually have three layers:

    • Reward coupling: length appears both in the cost penalty and, indirectly through the baseline, in the advantage estimate, forming a positive feedback loop.
    • Interaction between sampling temperature and tool failure rate: tool call failures induce the model to retry, retries lengthen the trajectory, and longer trajectories are more likely to trigger the next failure.
    • Context inflation: historical observations keep accumulating, the effective signal-to-noise ratio drops, and model output tends toward verbosity.

    Actionable mitigations include:

    1. Apply a soft constraint on length rather than a hard cutoff; a hard cutoff also penalizes “legitimately long tasks.”
    2. Introduce format and tool-legality checks that filter automatically determinable errors before the reward, keeping noise out of the gradient.
    3. Use length-stratified sampling quotas to ensure every length bucket has enough samples.
    4. Monitoring metrics should include length percentiles (P50/P90); looking only at the mean hides oscillation.

    4. Evaluation environment variance: a severely underestimated source of score noise

    The most informative observation in the original text is that the same model’s score fluctuated by a few percentage points from merely swapping the agent runtime framework. This is very common in practice, because the framework determines:

    • prompt templates and system instructions;
    • the available tool set and return formats;
    • failure retry policies and context trimming policies;
    • the execution order of patch application and verification.

    Therefore, comparing scores across frameworks is almost equivalent to comparing two different experiments. A reasonable approach is to fix the four-tuple of “model + framework + prompt + decoding parameters” before making horizontal comparisons, and to explicitly state these four items in the report. If an organization needs to select a model internally, it is advisable to build an internal repository task set covering different languages, sizes, and build complexities, and run all candidate models under the same framework; only then do the conclusions carry decision-making value.

    5. Benchmark evolution: why “everyone’s score drops on the new benchmark”

    When a benchmark is upgraded from 1.x to 2.x and most models’ scores drop sharply, it is usually not a collective model regression but stricter decision criteria. Common changes include:

    • prompts no longer spell out requirements, leaving substantial gaps that test the model’s ability to proactively clarify and infer;
    • the introduction of “single-veto” items, such as failing to remain compatible with other existing input types in the repository, not following the project’s existing conventions, or incidentally modifying unrelated files;
    • upgrading from “unit tests pass” to “meets the standard of an open-source maintainer reviewing a PR.”

    The intent of such design is to improve discriminative power, but a side effect is that the payoff from targeted adaptation to the benchmark is extremely high. So for information like “a model leads by a large margin on some new benchmark,” the rational reading is: first confirm whether the benchmark’s publisher and the model’s trainer are the same source, then check whether there are reproduction results from an independent third-party framework.

    6. A checklist for practitioners

    If you are doing post-training for a code agent, you can self-check in the following order:

    1. Is the reward decomposable and interpretable, and are the cost coefficients bucketed by difficulty?
    2. Is the baseline stratified, and are long tasks drowned out by short-task gradients?
    3. Do you monitor length percentiles and tool failure rate, rather than only success rate?
    4. Are the training framework and the evaluation framework decoupled, avoiding inflated scores from “same-source alignment”?
    5. Do you keep an independent evaluation set that does not participate in training, for the final judgment?
    6. Do you record the full four-tuple (model, framework, prompt, decoding parameters) for reproducibility?

    Conclusion

    The narrative “same base model + reinforcement learning = multiplied score gains” is not technically mysterious: reward shaping, baseline stratification, and length governance stacked together can indeed bring considerable gains on long-horizon coding tasks. But how much of the gain is capability, how much is alignment, and how much is environment variance must be separated by independent evaluation. For engineering teams, rather than chasing leaderboard positions, it is better to make evaluation methodology, reward design, and training stability solid—these are the transferable, reusable long-term assets.