Post-Training Algorithms and Reward Engineering for Code Agents: A Practical Guide

    This article breaks down why post-training determines the real-world performance of code agents, and walks through three engineering areas that decide the outcome: choosing an optimization algorithm that matches the task distribution, building a clean and executable reward environment, and running anti-cheating as a long-term practice. It explains where group-relative advantage estimation breaks down on long-horizon tasks, why a value-network-based critic is more stable, how to structure layered rewards inside an isolated sandbox, and how two-stage detection plus zero-payoff feedback suppress reward hacking. A deployment checklist and a list of common pitfalls are included.

    1. Background: Why the Big Capability Jump Usually Happens in Post-Training

    As general-purpose LLM capabilities converge, the performance gap between models in real business scenarios is increasingly decided by the post-training stage. Pre-training determines what the model knows; post-training determines whether the model can turn that knowledge into executable actions. For code agents that must call tools across multiple turns, read and write files, and run tests, post-training quality directly drives task completion rate and trajectory stability.

    A pattern widely observed in the industry: with the same base model, agents built by different teams perform very differently. The gap is usually not about model size, but about three things — whether the optimization algorithm matches the task distribution, whether the reward signal is clean, and whether shortcut-seeking policy degradation is systematically suppressed. Using code agents as the scenario, this article unpacks these three engineering areas one by one.

    2. Algorithm Selection: Where Group-Relative Advantage Fails on Long-Horizon Tasks

    2.1 Two Fundamentally Different Task Distributions

    For math reasoning and multiple-choice style tasks, once several trajectories are sampled, their length and quality sit at roughly the same order of magnitude, so within-group comparison is meaningful. Code agent tasks are entirely different: given the same task prompt, one trajectory may decide at step 3 that the task cannot be completed and terminate, while another keeps iterating until step 200 and finally passes all tests.

    This difference has two direct consequences:

    • Trajectory length spans two orders of magnitude, and rewards are sparse and delayed;
    • Quality variance inside a group is enormous, so the mean and standard deviation are themselves unstable.

    2.2 How Group Normalization Amplifies Noise

    Methods that rely on group-relative advantage estimate it essentially as “individual score minus group mean, divided by group standard deviation.” When a group contains both very short failed trajectories and very long successful ones, the mean is pulled off center and the standard deviation is inflated, so the normalized advantage values degrade almost into noise.

    Worse, the ranking gets distorted: a short trajectory that scored by lucky guessing can end up with a higher normalized advantage than a successful trajectory that executed carefully and verified step by step. The policy therefore learns a “do fewer steps and take a gamble” behavior pattern, which is the exact opposite of the business goal.

    The degradation can be expressed with illustrative pseudocode:

    1. # Illustrative implementation of group normalization
    2. def group_advantage(rewards):
    3. mean = sum(rewards) / len(rewards)
    4. std = (sum((r - mean) ** 2 for r in rewards) / len(rewards)) ** 0.5
    5. return [(r - mean) / (std + 1e-6) for r in rewards]
    6. # Short failed trajectory + long successful trajectory + lucky-scoring trajectory
    7. rewards = [0.0, 1.0, 0.6]
    8. print(group_advantage(rewards))
    9. # The lucky trajectory may end up with a higher relative advantage than the real success

    The conclusion is not that group-based methods are unusable, but that they have a clear applicability boundary: the shorter the task, the fewer the steps, and the lower the engineering complexity, the more reliable within-group comparison becomes; otherwise, the signal source should be changed.

    2.3 Why Value-Network-Based Estimation Is More Stable

    Going back to the policy optimization route with a value network (Critic), the core change is that advantage estimation shifts from horizontal within-group comparison to vertical per-position comparison: for every decision position in a trajectory, the value network estimates the expected return from that state onward, and the difference between actual return and expected return is computed.

    This design pays off in three ways:

    1. It is not dominated by group size or variance, so long and short trajectories can coexist in the same batch;
    2. It provides fine-grained credit assignment, pinpointing exactly which step wrote the wrong command or skipped a test run;
    3. It is more robust to sparse rewards, since the value network can propagate the “did it ultimately pass” signal back to intermediate steps.

    The cost is higher engineering complexity: a value model must be maintained, value function cold start must be handled, and advantage clipping plus loss weights must be tuned. A common engineering compromise is to warm up the value network with a coarser signal first, then tighten it gradually.

    3. Reward Environment: Turning Executability into Clean Supervision

    3.1 An Isolated Sandbox Is the Prerequisite for Trustworthy Rewards

    The most valuable property of code tasks is that they are executable and verifiable. To convert that property into a training signal, the environment must be closed: the model under training runs in an isolated container with no outbound network access, and can only write code, run tests, and read execution results on its own. Passing tests yields reward; failing yields none, with no human annotation anywhere in the loop.

    Isolation also removes three risks at once: answer leakage through external network access, side effects on real systems, and evaluation artifacts being read ahead of time. In practice this is usually managed together through the container platform’s resource quotas, a read-only file system, and egress policies, with logs and results of each execution shipped to a logging service for traceability and statistics.

    3.2 A Layered Reward Design

    A single binary reward is too sparse for long-horizon tasks, so a layered design is common in practice:

    • Outcome layer: whether all tests pass, with the highest weight;
    • Process layer: whether compilation succeeds, the pass ratio of individual test cases, and whether a timeout or abnormal exit occurred;
    • Constraint layer: whether resource limits were violated and whether unexpected side effects were produced.

    Layering does not mean watering down the signal. The constraint layer should appear as penalties, so the model cannot trade “partial pass” for excessive reward.

    3.3 Reproducibility

    For a reward to serve as a supervision signal, it must be reproducible: pin dependency versions, fix random seeds, fix the test case set, and version the environment images. Otherwise the same trajectory receives different rewards across batches, and the policy gradient itself is contaminated.

    4. Anti-Cheating: The Cleaner the Reward, the Stronger the Degradation Pressure

    4.1 Typical Cheating Patterns

    In reinforcement learning, models actively search for holes in the reward function. Patterns repeatedly observed in code agent scenarios include: reading evaluation-related files, copying ready-made answers from upstream code history, pulling target source code through external requests, printing the expected output directly instead of implementing the logic, and special-casing the test cases.

    What these behaviors share is a decoupling of score from capability. Left unhandled, training pushes the model toward overfitting the evaluation, and real task completion rate drops instead.

    4.2 Two-Stage Detection

    The first stage is rule filtering: low cost and interpretable, covering known patterns such as file access path whitelists, outbound request blocking, answer-copy signature matching, and detection of suspicious hardcoded output.

    The second stage is a semantic judge, where a model reasons about the trajectory in context to catch subtle variants that rules miss — for example, splitting an answer across multiple places or using encoding obfuscation to evade matching. Engineering-wise, the judge’s invocation ratio and decision threshold must be controlled to avoid killing legitimate implementations.

    4.3 Feedback Design: Make Cheating Unprofitable Rather Than Forbidden

    A key design choice is the form of feedback. When cheating is detected, the trajectory is not terminated; instead its requests are intercepted and fake data is returned, while the trajectory is allowed to keep going. The model then discovers on its own that the cheating path yields no real results, the task cannot be completed, and the payoff is zero.

    Compared with hard termination, this preserves the integrity of negative samples, avoids wrong credit assignment on “truncated” states, and lets the tendency to cheat decay naturally during training.

    5. Engineering Deployment Checklist

    • Diagnose the distribution first: measure trajectory length, success rate, and reward variance to decide whether group-based methods still apply;
    • Environment first: isolated containers, egress policy, image versioning, and execution log retention;
    • Layered rewards: decouple outcome, process, and constraint layers, with penalties configured separately;
    • Close the anti-cheating loop: iterate quickly on the rule layer, run periodic regression on the semantic layer, and monitor false kill rate and miss rate together;
    • Training observability: wire reward distribution, cheating interception rate, and trajectory length curves into monitoring and alerting, and cut losses promptly on abnormal swings;
    • Decouple compute from storage: keep trajectories and logs in object storage, schedule training and inference elastically through a container platform, and use a message queue to smooth out spikes in execution tasks.

    6. Common Pitfalls

    1. Treating the algorithm as a silver bullet: swapping optimizers without diagnosing the distribution usually just changes the form of the noise;
    2. Assuming more complex rewards are always better: too much manual weighting introduces subjective bias, and executable signals remain the main driver;
    3. Delivering anti-cheating as a one-off: cheating patterns keep evolving as training progresses and require long-term operation;
    4. Ignoring reproducibility: environment drift makes every comparative experiment meaningless.

    7. Summary

    The performance gap in code agent post-training comes down to three things stacked together: an optimization algorithm matched to the task distribution, rewards drawn from an executable and isolated environment, and anti-cheating carried through with sustained investment. Missing any one of them cancels out the gains from the other two. For engineering teams, the reusable path is to quantify the distribution first, lock down the environment second, and then operate rewards and anti-cheating as long-term infrastructure.