Reinforcement Learning for Coding Agents: Long-Horizon Optimization and Evaluation Calibration

    This article examines how to critically evaluate claims that RL-optimized coding agents outperform newer general-purpose models on code benchmarks. It breaks down why long-horizon software engineering tasks are well suited to reinforcement learning, how to build a reliable data and reward pipeline, how length-weighted reward baselines address trajectory length oscillation, and what sources of evaluation bias—task distribution, hidden acceptance criteria, execution harnesses, and budget alignment—must be checked before accepting benchmark results. It concludes with a practical cross-evaluation workflow and key engineering metrics for training and deploying RL-based coding agents.

    1. Decompose “Benchmark Scores Doubled” into Verifiable Questions

    Some technical reports offer eye-catching conclusions: by adding reinforcement learning on top of a general-purpose code model and optimizing for software engineering tasks, a specialized agent can achieve a dramatic lead on a specific code benchmark—even surpassing a newer general-purpose model. When you see such claims, the first step is neither to accept nor reject them outright, but to decompose the “score” into verifiable conditions: What is the task distribution? Are problem statements complete? Are acceptance criteria public? Is the execution harness the same? Are tool call limits, context length, retries, and sampling budgets aligned? Is there distributional overlap or leakage between training data and the test set?

    A software engineering agent’s score is not a direct readout of the model’s capability. It is the joint product of the model, the tasks, the execution environment, the scorer, and the budget:

    Score = model policy × task distribution × execution harness × acceptance criteria × compute budget × sampling strategy

    If any of these conditions differ, the comparison can be distorted. A specialized agent fine-tuned via RL on a target benchmark will naturally improve significantly when the problem style, repository structure, test feedback, toolset, and scoring criteria closely match its training environment—but that does not automatically mean it is better at all general software development tasks. Likewise, a newer general-purpose model placed in an execution harness it was not tuned for may be underestimated. Therefore, “2×” is first and foremost a conditional result: you need to know whether it is a relative multiple or an absolute percentage-point gain, single-attempt or multi-attempt pass rate, compared at the same budget or different budgets, a single benchmark or an average across benchmarks.

    As an engineering practice, rewrite conclusions in a verifiable form: “On benchmark X, under harness Y, tool budget Z, and scoring rubric W, RL optimization raised the pass rate from A to B. When the problem set, harness, and acceptance criteria change, does the gain still hold, and by how much?” Only such conditional statements are sufficient to support technology selection and production deployment.

    2. Why Long-Horizon Software Engineering Tasks Suit Reinforcement Learning

    Software engineering agents differ from ordinary code completion in two key ways: long horizons and closed loops. A complete task involves understanding the issue, browsing the repository, locating the defect, modifying multiple files, adding tests, handling compatibility, running validation, and continuing to fix based on failure feedback. The whole process may involve dozens of interactions, and the reward is highly sparse: only when the final tests pass, quality checks pass, and no regressions are introduced is the task truly a success.

    This is precisely where RL adds value. Supervised fine-tuning can teach a model to produce “something that looks like a correct patch,” but it cannot directly optimize the process of “making continuous decisions under tool feedback and ultimately landing the change.” RL—by sampling trajectories, executing validation, computing rewards, and updating the policy—gives the model a chance to learn:

    • When to keep searching for context and when to make the edit early;
    • How to narrow down a problem based on failing tests;
    • How to balance fix speed, change scope, and regression risk;
    • How to maintain plan consistency over long tasks and avoid going in circles.

    But long-horizon RL is inherently difficult. First, rewards are sparse: most trajectories fail, and if only the final outcome is provided, the model cannot tell which steps were right or wrong. Second, the environment is noisy: flaky tests, missing dependencies, and random failures contaminate the reward. Third, trajectory length varies widely: some tasks produce a patch quickly, while others involve long exploration; length and success rate are not independent, and if left unaddressed, gradients will be biased by the length distribution. Fourth, sampling is expensive: every trajectory requires executing code and tests in an isolated environment, so throughput and stability directly affect training feasibility.

    The “long-horizon tasks” and “trajectory length oscillation” mentioned in the original discussion are concrete manifestations of this fourth problem. When trajectory lengths swing between long and short, a global reward baseline becomes unreliable: long trajectories naturally get more attempts but may also introduce more errors through redundancy; short trajectories may succeed, or they may give up prematurely. If the global mean is used directly as the baseline, the model receives unstable—even contradictory—advantage signals.

    3. The Data Loop: A Step That Comes Before the Reward Function

    When discussing RL, attention tends to focus on reward design. But for software engineering agents, data and environment often determine the ceiling. A trainable data loop should include, at minimum: the task, the repository state, the problem description, executable validation, a reference change, and acceptance criteria. If the data quality is poor, even the most sophisticated reward function may just be fitting noise.

    High-quality data curation should focus on the following points.

    1. Tasks must be verifiable and environments reproducible

    Tasks must reproduce reliably in isolated environments. Dependency versions, test commands, initialization scripts, random seeds, and external service mocks should all be version-controlled within the environment. If a task runs today but fails tomorrow, rewards become incomparable, and training will show the illusion of “the same policy drifting in score.” Flaky tests should be executed multiple times and only stable results accepted—or the task should be excluded from training entirely.

    2. Problem statements should match real maintenance scenarios, but not be entirely undecidable

    In real software maintenance, requirements are often incomplete, and maintainers make judgment calls based on project conventions, compatibility, performance, and security. Such “implicit criteria” can indeed filter for stronger agents, but if used for training and public comparisons, there must be an explainable scoring explanation. Otherwise, an agent may fail not because of technical capability, but because of guessing at hidden intent. Training should provide the necessary acceptance dimensions: whether interface changes are allowed, whether backward compatibility is required, whether edge-case inputs must be covered, whether the change scope is restricted. Hidden tests can remain hidden, but hidden rules must not be entirely unguessable.

    3. Filter low-information and reward-hackable data

    If a task can be passed by changing one line of configuration, or if test coverage is extremely weak, the model may learn to game the system: deleting tests, changing assertions, working around the problem, or expanding the change scope to get lucky. Data preparation should include anti-gaming checks: forbid modifying tests, forbid suppressing exceptions, limit file change scope, check for regressions. Samples that can be passed via no-ops or hard-coding should be down-weighted or removed.

    4. Prevent train/test contamination

    Long-horizon tasks often come from public repositories. Without controls, the test set may already appear in the training corpus in some form. You should perform duplicate detection, near-duplicate patch retrieval, repository-level and time-based splits, and hold out unpublished variants for the evaluation set. Especially for “new benchmark versions,” if training and test sets come from the same batch of task styles, a style advantage forms even without direct duplication. Public comparisons must disclose the split strategy.

    4. The Reward Function: Extending “Pass” into Multi-Objective Engineering Quality

    If the reward is simply whether the tests pass, the policy will naturally gravitate toward the shortest path to passing— not necessarily a maintainable change. A more sensible reward should account for outcome, quality, regression, and cost. A general form can be written as:

    1. reward = outcome reward
    2. + quality reward
    3. + regression-check reward
    4. + partial-progress reward
    5. - change cost
    6. - tool-call cost
    7. - timeout and risk penalties

    Here the outcome reward is whether final validation passes; the quality reward covers readability, change scope, interface compatibility, and exception handling; the regression-check reward confirms existing tests were not broken; cost terms constrain excessive deliberation and meaningless tool calls. Note that smaller cost penalties are not inherently better. Penalties that are too strong push the model toward short but unusable patches; penalties too weak encourage aimless exploration. The right approach is to find the “success rate vs. average cost” Pareto frontier on a validation set, rather than chasing the highest pass rate alone.

    The “cost-penalized reward function” mentioned in the original discussion can be understood as constraining trajectory length, tool call count, execution time, or change size. Its value goes beyond saving money—it suppresses reward hacking and ineffective exploration:

    • Prevents the model from passing by luck through unlimited retries or repeatedly reading irrelevant files;
    • Encourages the model to form a hypothesis first, then run targeted verification;
    • Makes successful and failed trajectories comparable on the cost dimension;
    • Reduces the impact of long-tail trajectories on training throughput, GPU memory, and storage.

    But cost penalties must be tied to task difficulty. A fixed penalty may be too heavy for easy tasks and too light for hard ones. Normalize cost by task category, initial repository size, test count, or historical success rate—for example, using “length ratio relative to a baseline policy” as the penalty unit. Also, if the cost term uses many hyperparameters, run ablation experiments; otherwise it is hard to tell whether gains come from reward design or tuning.

    5. Length-Weighted Reward Baseline: Solving Trajectory Length Oscillation

    RL commonly uses an advantage function to measure “how much better a trajectory was than expected.” If the baseline is just a global average and the policy produces trajectories of widely varying lengths at different stages, advantage estimates become biased. The goal of a length-weighted reward baseline is to place trajectories of different lengths in a fairer reference frame for comparison.

    A simple implementation buckets trajectories by length: short, medium, long, and extra-long, with reward means and variances computed per bucket; advantages are normalized only within the same or adjacent buckets. A smoother approach fits a regression model to predict expected reward from length, tool call count, and task difficulty, then subtracts the prediction from the actual reward. Pseudocode:

    1. for batch in task_batch:
    2. trajectories = policy.sample(batch, tool_budget, max_steps)
    3. for t in trajectories:
    4. outcome = run_validation(t.patch)
    5. quality = evaluate_maintainability(t.patch)
    6. regression = run_regression_checks(t.patch)
    7. cost = w1 * t.token_length
    8. + w2 * t.tool_calls
    9. + w3 * t.execution_time
    10. + w4 * t.patch_size
    11. t.reward = outcome_score(outcome)
    12. + quality_weight * quality
    13. + regression_weight * regression
    14. - cost
    15. for bucket in length_buckets(trajectories):
    16. baseline[bucket] = moving_average(reward, bucket)
    17. scale[bucket] = std(reward, bucket) + epsilon
    18. for t in trajectories:
    19. t.advantage = (t.reward - baseline[t.length_bucket]) / scale[t.length_bucket]
    20. update_policy(normalize_advantage(trajectories))

    The key to a length-weighted baseline is not just “weighting by length” but handling heteroscedasticity. Long trajectories differ from short ones in success rate, reward variance, and cost. With a global baseline, occasional high rewards on short trajectories produce oversized positive advantages, while common failures on long trajectories get wrongly punished. Bucketing, regression, or stratified baselines let the policy compare “who does better among tasks of similar difficulty and similar length,” reducing the impact of length oscillation on training stability.

    In practice, add three safeguards:

    1. When a bucket has too few samples, fall back to the global baseline or smoothed statistics to avoid small-sample noise;
    2. Use log scaling for lengths rather than raw values, so extra-long trajectories do not dominate the baseline;
    3. Track successful and failed trajectories separately, so a surplus of failures does not drag down the success baseline.

    6. Training Stability: Curriculum, Sampling, and Isolated Execution

    Long-horizon RL stability comes not only from the reward but also from training workflow design. Start with short, clearly-specified tasks, then gradually increase repository size, tool count, and hidden-test complexity. Curriculum learning mitigates early reward sparsity, letting the model first learn the basic “locate–modify–verify” loop before moving on to multi-file changes and compatibility maintenance.

    Control variance during sampling. Sampling multiple trajectories per task and comparing within the group is more stable than updating on single trajectories. For simple tasks that fail repeatedly, check whether the task or environment itself is broken; for tasks that keep succeeding without quality improvements, add stricter acceptance criteria or replace the data. Set a budget cap on extra-long trajectories and emit an explicit failure signal when it is reached, rather than letting the model try indefinitely.

    Execution environments must be isolated and auditable. All code execution should run in sandboxes without sensitive credentials, with boundaries on the file system, network, resource usage, and time. Training and evaluation should use the same execution specification, but test sets and hidden cases must be strictly separated. For tasks with unavailable external dependencies, use stable images or mocked services and record environment versions. Otherwise, today’s high score may come from environmental luck, and tomorrow’s failure may be irreproducible.

    7. Sources of Evaluation Bias: Problem Statements, Criteria, Harnesses, and Sample Size

    Returning to the question of “a specialized agent dramatically outperforming a general-purpose model on a single code benchmark,” at least four categories of bias must be checked.

    1. Same-origin bias in problem statements and acceptance criteria

    If a benchmark deliberately understates requirements, leaving many real maintenance requirements implicit, and then applies maintainer-perspective veto criteria, the benchmark is closer to a “real merge-quality test” than an ordinary unit test. This design has legitimacy: in real engineering, fixing one defect must not introduce another, must not break existing input types, and must not only satisfy the current tests. But if the training team deeply understands these hidden criteria and optimizes its data, rewards, and problem statements accordingly, while the comparison model does not get equivalent treatment, the gap includes a “criteria-alignment advantage”—not purely a difference in general programming ability.

    This does not mean the benchmark is invalid; it means the conclusion must be qualified. It is suitable for measuring “maintenance quality as defined by this benchmark,” not for directly extrapolating a ranking on all coding tasks. For public comparisons, the scoring dimensions should be disclosed, models should be allowed equal numbers of adaptive attempts, or at minimum, results without targeted training should be provided as a baseline.

    2. Execution harness differences

    The same model in different execution harnesses may face different tool definitions, context compression, error feedback formats, maximum steps, file reading methods, and retry mechanisms. As noted in the original discussion, the same general-purpose model can differ by several percentage points just by switching to a different command-line execution harness, and scores change further in a more general harness. This shows the execution harness is itself part of the capability—and an evaluation variable.

    A fair comparison should:

    • Use the same toolset and permissions;
    • Use the same maximum steps, tool call limits, and retry counts;
    • Provide the same initial repository state and dependency environment;
    • Use consistent settings for failure retries, temperature, and sampling counts;
    • Run at least one round each in the training harness, a general-purpose harness, and a third-party harness.

    If the comparison happens only inside the specialized RL harness, it is unsurprising that the specialized model wins; it is more like “testing the same policy on its own training ground” and cannot serve alone as proof of cross-scenario capability.

    3. Single benchmarks and point fluctuations

    When only one benchmark shows a huge gap while others show little, beware of local amplification caused by task distribution and scoring criteria. Report results broken down by category—bug fixing, feature implementation, compatibility maintenance, refactoring, multi-file changes, test generation—rather than a single total score. Also report absolute gains, relative gains, confidence intervals, and sample sizes. At low pass rates, a relative doubling may just mean moving from a low level to a mediocre one; the practical significance must be judged against cost and acceptance thresholds.

    4. Overlap between training data and the evaluation time window

    If the RL data comes from repositories, defect types, or even time windows close to the evaluation set, the improvement may include contamination or distributional overlap. Hold out time-external, repository-external, and style-external test sets. For a specialized model, the most important question is whether it retains its gains on new tasks that were not part of training.

    8. A Practical Cross-Evaluation Workflow

    To judge whether “long-horizon optimization” is genuinely effective, adopt the following evaluation process.

    1. Build a stratified test set: stratify by task type, repository size, number of files changed, and dependency complexity; maintain separate development and frozen test sets. Test sets must not participate in reward design or hyperparameter selection.
    2. Unify the execution harness: evaluate in the in-house training harness, a neutral general-purpose harness, and a production-oriented integration harness. Record tool calls, context length, retries, and cost for each.
    3. Align budgets: the same model scores differently at different budgets; set at least low, medium, and high budget tiers and report success-rate-vs-cost curves.
    4. Report multiple metrics: final pass rate, relative improvement over baseline, absolute percentage points, average tool calls, average execution time, regression rate, maintainability score, and human-review pass rate.
    5. Ablation validation: separately remove the cost penalty, the length-weighted baseline, the quality reward, curriculum learning, and data filtering, and observe each module’s contribution. If gains come mainly from data curation rather than the RL algorithm, say so honestly.
    6. Repeat experiments: run key conclusions multiple times and report means and variance. A single high score does not demonstrate stability.
    7. Safety and compliance checks: verify the model did not modify tests, suppress exceptions, access irrelevant files, or introduce unsafe dependencies. The stronger a long-horizon agent becomes, the more it needs execution boundaries and auditing.

    9. Engineering Architecture and Key Metrics

    Within an enterprise, these methods can be organized into a pipeline: task registration → sandbox execution → trajectory sampling → reward computation → policy training → cross-evaluation → staged rollout. Task registration version-controls repositories, problem statements, tests, and acceptance criteria; sandbox execution runs patches and tests in isolation; trajectory sampling records model decisions and tool calls; reward computation outputs outcome, quality, regression, and cost; the training module consumes trajectories and updates the policy; the evaluation module runs regression tests on frozen sets across multiple harnesses.

    On Baidu AI Cloud, you can use the general-purpose container platform to host isolated execution environments, object storage to store task snapshots and trajectories, logging services to record execution processes, and monitoring and alerting to track training stability and resource consumption. The key point here is not any specific product capability, but establishing reproducible environments, traceable trajectories, and comparable evaluations as the engineering foundation.

    Recommended metrics to monitor closely:

    • Final pass rate and relative improvement;
    • Average tool calls, average token consumption, and execution time;
    • Trajectory length distribution and drift before/after training;
    • Success-rate-vs-cost Pareto frontier;
    • Regression test breakage rate;
    • Human-sampled pass rate on maintenance quality;
    • Score variance across execution harnesses;
    • Correlation between training reward and frozen test set performance.

    If training reward keeps rising while the frozen test set does not, it usually means the reward is being exploited, data is leaking, or the task distribution is too narrow. If average cost drops quickly while the success rate drops in tandem, the cost penalty may be too strong. If scores differ dramatically across harnesses, tool adaptation and execution interfaces remain the main bottleneck and cannot simply be attributed to model capability.

    10. Conclusion: Local Optimization Can Lead, but Conclusions Must Be Conditional

    RL targeting software engineering tasks can indeed enable a specialized agent built on a general-purpose code model to surpass a newer general-purpose model—on a specific benchmark, in a specific execution harness, under specific acceptance criteria. The technical sources are not mysterious: a high-quality task loop, a cost-constrained reward function, length-weighted or stratified advantage estimation, curriculum-based sampling, and stable sandbox execution all significantly improve learning efficiency on long-horizon tasks. In particular, trajectory length oscillation, if unaddressed, directly corrupts advantage estimation and training stability; cost penalties, length-bucketed baselines, and budget control let the policy focus on “completing tasks with high quality at reasonable cost.”

    But such results cannot be reduced to “model X leads across the board.” If the benchmark was designed with deep involvement from the training team, the problem statements contain many implicit acceptance criteria, and official scores are produced only in the specialized execution harness, the gap necessarily mixes criteria alignment, harness adaptation, and budget alignment factors. The more reasonable conclusion is: specialized RL can significantly improve software engineering performance on a specific distribution, while the true capability ranking of general-purpose models must be re-verified across multiple benchmarks, multiple harnesses, unified budgets, and public scoring criteria.

    Therefore, evaluating any “doubled benchmark score” should answer at least three questions: On what task distribution does it hold? What execution conditions and budgets does it depend on? Does it still hold on unseen tasks, in general-purpose harnesses, and under strict regression checks? Only when these three questions are answered can both the technical progress and the evaluation methodology stand on solid ground.