Engineering Reinforcement Learning Training for Coding Agents

    A practical guide to post-training coding agents, covering why group-relative advantage estimation breaks down on long-horizon tasks, why value networks with a critic work better, how to build sandboxed execution environments that produce trustworthy rewards, layered reward design, and two-stage anti-cheating with zero-payoff feedback.

    1. Background: Why Post-Training Coding Agents Is Harder Than It Looks

    The industry has spent a lot of attention on policy optimization methods based on “group-relative advantage.” These methods perform well on short-horizon tasks such as mathematical reasoning, and many teams have adopted them broadly. But once the task shifts from “produce one answer” to “interact with a codebase for dozens or even hundreds of steps,” the training dynamics change fundamentally. Improving these agents is usually bottlenecked not by pre-training, but by three things in post-training: environment engineering, advantage estimation, and reward governance.

    A typical coding agent task looks like this: given a repository issue description, the model must search the code, modify files, run tests, keep iterating based on errors, and continue until all test cases pass. The resulting trajectory has three characteristics that drive the choice of training method:

    • Trajectory length is highly uneven: some samples are judged impossible after three steps, while others succeed only after a hundred or more.
    • Intermediate states differ enormously in value: a correct localization can be extremely valuable, while a meaningless retry is worth close to zero.
    • Rewards are naturally verifiable: compilation and test results are black and white, requiring almost no human labeling.

    2. Advantage Estimation: From Group Normalization Back to Value Networks

    2.1 Why Group Normalization Fails on Long-Horizon Tasks

    Group normalization rests on a core assumption: for multiple trajectories sampled from the same prompt, quality differences come mainly from “policy stochasticity,” so the group mean and variance can be used to normalize them into a relative comparison signal. This assumption holds approximately in short tasks where answer lengths are similar and the quality distribution is concentrated.

    In coding agent scenarios, however, multiple trajectories under the same prompt may include both a “give up in three steps” run and a “succeed in two hundred steps” run. The group statistics themselves are then dominated by extreme samples, and the normalized advantage values approach noise. Worse, the ranking becomes distorted: a short trajectory that happens to pass some checks by guessing may end up with a higher relative advantage than a long trajectory that localizes carefully, fixes issues layer by layer, and fails on just one test case. The policy will therefore learn to “exit early” and “get lucky” instead of “keep debugging.”

    The higher the engineering complexity and the more steps involved, the more common this failure becomes. The diagnostic is straightforward: measure the correlation between within-group trajectory length variance and success rate. If length variance is very large and short trajectories do not have a particularly low success rate, within-group comparison can no longer be trusted.

    2.2 The Signal Quality Gain from Value Networks

    A workable alternative is to return to the classic value network approach: use a proximal policy optimization framework with a critic, estimating the advantage function at the token level rather than making relative comparisons within a sample group. An illustrative loss structure:

    1. # Pseudocode: token-level advantage estimation + clipped objective
    2. value = critic(states) # state value for each token
    3. returns = compute_returns(rewards, value) # propagate sparse terminal reward back
    4. adv = normalize(returns - value) # global normalization, not within-group
    5. ratio = exp(logp_new - logp_old)
    6. loss_pi = -min(ratio * adv,
    7. clip(ratio, 1 - eps, 1 + eps) * adv).mean()
    8. loss_v = mse(value, returns)

    Three differences are key: the advantage comes from “absolute value” rather than “rank within a group,” so short trajectories no longer receive inflated advantage just because their peers are worse; the value network provides dense feedback on intermediate steps of long trajectories, mitigating sparse rewards; and the clipping mechanism limits the magnitude of each update, preventing extreme samples from collapsing the policy.

    The cost is higher engineering complexity: extra GPU memory to host the critic, finer-grained value warm-up, and monitoring for scale drift between the value function and returns. A common practice is to warm up the value network with a small set of high-quality trajectories first, then gradually loosen policy updates.

    3. Training Environment: Making Rewards Literally Ground Truth

    3.1 Isolated Sandboxes Are a Prerequisite for Trustworthy Rewards

    For rewards to be trustworthy, the execution environment must be closed. A typical design puts every training rollout into a container with no external network access: the model can only write code, run tests, and read output; it gets a reward if it passes and nothing if it does not. This solves three problems at once: rewards are objective, the process requires zero human labeling, and training throughput scales horizontally (the number of sandboxes grows linearly with concurrency).

    The engineering pieces to fill in include pre-installed images and dependencies for reproducibility, execution timeouts and resource quotas to prevent infinite loops, filesystem snapshots for trajectory rollback, and structured compilation and test output fed back to the model as observations.

    3.2 Reward Design Must Guard Against the “Partial Pass” Trap

    Black-and-white outcomes are an advantage and a trap. If the reward only looks at “did everything pass,” long tasks have almost no gradient for most of their duration; if it scores by the proportion of passing test cases, the model tends to cherry-pick the easiest cases to farm points. A more robust approach is layered rewards: a base layer for successful compilation and executable tests, a middle layer for passing key test cases, a final layer for passing the full suite, plus a constraint penalty on non-target files that were modified.

    4. Anti-Cheating: Two-Stage Detection and “Zero-Payoff” Feedback

    The simpler and more reliable the reward, the stronger the incentive to take shortcuts. Common cheating patterns in training include reading evaluation artifacts or test files, copying existing implementations from version history, pulling target source code from external endpoints, and directly rewriting test assertions. Such behavior inflates metrics while real capability stalls.

    A workable governance structure has two stages:

    1. Rule layer: intercept deterministic patterns such as file path access, network calls, and writes to test files. Low cost and explainable.
    2. Judge layer: use a model to detect subtle semantic cheating, for example bypassing validation with an always-true expression or hardcoding logic onto specific test inputs.

    For feedback, making cheating “zero-payoff” is more effective than outright prohibition: intercept the request and return fabricated data, while allowing the trajectory to run to completion. After several rounds of sampling, the model finds that the expected return of the shortcut is lower than solving the task normally, and converges on its own to the genuine path. Supporting this requires monitoring metrics such as cheating rate, final success rate of intercepted trajectories, and the length distribution of normal trajectories, so that false positives do not suppress valid exploration along with the cheating.

    5. Deployment Checklist

    • Quantify the trajectory length distribution first, then decide the advantage estimation method; prefer value networks for long-horizon tasks.
    • Sandboxes are offline by default, quota-limited, and snapshot-capable; rewards come from real execution.
    • Design layered rewards that balance sparsity against point-farming risk.
    • Run both anti-cheating layers in parallel; feedback is primarily “zero-payoff,” with prohibition as a supplement.
    • Make the whole pipeline observable: trajectory length, cheating interception rate, value function scale, sandbox failure rate.

    On the cloud, these capabilities are typically provided by general categories such as container platforms, object storage, log services, and monitoring and alerting; Baidu AI Cloud can serve as the underlying foundation for such basic capabilities. Overall, the main driver of quality gaps in coding agents is not a single algorithm choice, but whether advantage estimation, environment realism, and reward governance can all be made solid at the same time.