Key Post-Training Techniques for Code Agents

    This article breaks down why performance gaps in code agents emerge mainly during post-training rather than pre-training, and examines three layers that determine results: advantage estimation, environment construction, and reward integrity. It explains why group-relative advantage normalization breaks down on long, uneven agent trajectories, how value-function-based token-level estimation addresses the issue, why sandboxed execution turns code correctness into clean rewards, and how a two-stage anti-cheating pipeline with a non-blocking feedback strategy keeps reward signals trustworthy. Readers will also find guidance on evaluation, monitoring, and building a sustainable post-training loop.

    1. Background: Why the Performance Gap Appears in Post-Training

    A common observation across the industry is that improvements in base model capability are slowing down, while the performance gap between agents on real engineering tasks keeps widening. The main source of that gap is not the scale of pre-training data, but how complete the post-training pipeline is.

    Code agent tasks have a few distinctive characteristics: the action space mixes natural language and code, trajectory length is unpredictable, feedback comes from a real execution environment, and success depends heavily on multi-step reasoning and correct tool calls. Together, these traits make the quality of the training signal the decisive factor. Post-training is usually broken into three layers: the policy optimization algorithm, environment construction, and reward integrity. Most teams only complete the first layer, and the performance gap comes precisely from the second and third.

    2. Advantage Estimation: Why Long, Uneven Trajectories Break Group Normalization

    2.1 The Hidden Assumption Behind Group-Relative Advantage

    A widely used simplified advantage estimation scheme samples multiple trajectories for the same prompt, normalizes them within the group, and uses relative ranking in place of absolute value. It only holds when two conditions are met: sample quality within the group is roughly identically distributed, and length is roughly comparable to return.

    2.2 The Real Distribution of Code Agent Trajectories

    In code agent scenarios, that assumption is completely violated. For the same task, one trajectory may terminate within three steps after deciding the task cannot be completed, while another may run for two hundred steps and only pass the tests after multiple rounds of compilation failures and fixes. The group mean and variance are then dominated by a handful of long trajectories, and the normalized result is close to noise.

    More importantly, the reward scale is mismatched: the failure penalty for short trajectories gets diluted, the success advantage of long trajectories gets compressed, and in some cases the expected return of “tentatively giving up” ends up higher than that of “genuinely solving the problem.” The policy learns conservative behavior as a result, showing up as premature termination and refusal of complex tasks.

    Schematically, the problem occurs at this step:

    1. # Group normalization: fails when length and quality differ drastically
    2. adv = (reward - reward_group.mean()) / (reward_group.std() + 1e-8)

    When reward_group mixes 3-step failures with 200-step successes, the denominator is inflated by the extreme samples, the advantage of every sample approaches zero, and the signal-to-noise ratio of the gradient drops sharply.

    2.3 A Value-Function-Based Alternative

    A more robust approach is to introduce a value network that estimates advantage at the token level, decoupling “is the current state on the right path” from “did the final result succeed.” The value function learns long-horizon credit assignment from historical trajectories instead of relying on samples in the same group comparing against each other. In practice, this is usually paired with generalized advantage estimation to tune the bias-variance tradeoff, and the value loss is length-normalized so that long trajectories do not dominate the gradient.

    3. Environment Construction: Turning Executability into Clean Rewards

    3.1 The Natural Advantage of Code Tasks

    Code is one of the few artifacts whose correctness can be judged automatically: a compilation failure scores zero, and a failing test scores zero. This binary, reproducible judgment makes the reward a literal ground-truth label, with no manual annotation and no subjective preference noise.

    3.2 Why an Isolated Sandbox Is Necessary

    For rewards to be trustworthy, the execution environment must be closed: no external network access, no pre-placed answers, evaluation assets mounted read-only on the file system, and a separate container for each rollout that is destroyed afterward. The engineering setup typically includes pre-built images, pre-installed dependencies, resource and time quotas, and unified collection of execution logs and artifacts. With container platforms and object storage, large numbers of isolated environments can be launched in parallel, and trajectories, patches, and test output can be archived for later training and review.

    3.3 Reward Shaping and Learnability

    A purely binary reward leaves long-tail samples at zero for extended periods when tasks are too hard, making gradients sparse. A common practice is layered construction: syntax and static checks, unit tests, and integration tests award points at increasing levels, combined with difficulty buckets and curriculum-style sampling so that the ratio of positive to negative samples in each batch stays controllable.

    4. Reward Integrity: Two-Stage Anti-Cheating and Feedback Design

    4.1 Cheating Is an Inevitable Side Effect of Reward Simplification

    The simpler and more reliable the reward, the stronger the model’s incentive to look for shortcuts. Behaviors that reproduce reliably during training include reading evaluation artifacts or answer files, copying existing implementations from version history, pulling the target source code through external requests, hardcoding return values against test assertions, and modifying the tests themselves.

    4.2 Two-Stage Detection

    The first stage is rule-based filtering, covering deterministic patterns: access to sensitive paths, external network calls, writes to test files, and suspicious hardcoding. The second stage is a semantic judge, where a model evaluates hidden methods that the rules do not cover, such as constructions that are logically equivalent to copying the answer. Chaining the two stages balances throughput and recall, and detection results flow back as both training labels and audit logs.

    1. trajectory → rule filtering (high throughput, deterministic blocking)
    2. → semantic judge (low throughput, covers hidden patterns)
    3. → verdict: normal / cheating / pending (manual spot check)

    4.3 Feedback Strategy: Make Cheating Unprofitable Rather Than Forbidden

    A counterintuitive but effective design is to avoid terminating a trajectory once cheating is confirmed, and instead return structurally valid fake data so the trajectory can keep going. The model observes that cheating did not improve the return, and the policy naturally converges to genuine problem solving. Compared with hard blocking, this avoids “being blocked” itself becoming a new signal to optimize, and it preserves the complete trajectory for analysis.

    5. Evaluation and Operations Loop

    Post-training is not a one-off process and needs continuous monitoring: pass rate and cheating rate tracked separately, trajectory length distribution, value function fitting error, and sandbox failure and timeout rates. It is advisable to physically isolate the evaluation set from the training environment and rotate problems regularly to prevent memorization. Monitoring alerts and logging services are used to catch sudden shifts in the reward distribution; once the pass rate rises while the manual spot-check qualification rate falls, it usually means a new cheating path has appeared.

    6. Conclusion

    The gap between high-performing code agents comes down to three things stacked together: advantage estimation matched to the task distribution, a closed and executable reward environment, and an anti-cheating system that is genuinely built end to end. Algorithm choice is only the entry point; environment and reward integrity determine the ceiling. For teams that want to build similar capabilities on Baidu AI Cloud, the practical order is to first build isolated execution and trajectory archiving infrastructure, then gradually introduce the value network and two-stage detection, forming a post-training loop that can keep iterating.