Post-Training Practices for LLM Code Agents: Algorithms, Environments, and Reward Governance
This article breaks down the engineering behind post-training large language models for code agent tasks. It explains why group-relative optimization can fail on long-horizon trajectories, why value-network-based PPO offers more stable credit assignment, how network-isolated sandboxes and automated tests produce verifiable rewards, and how a two-stage anti-cheating pipeline keeps the optimization target intact. It closes with a practical checklist covering the algorithm, environment, reward, governance, and observability layers.
1. Why Code Agents Are Hard to Train
Over the past year, the gap in performance between large models on code agent tasks has been discussed repeatedly. Given a similar level of general reasoning ability, models can differ by several times in success rate on long-horizon tasks such as reading a requirement, modifying code, running tests, and fixing defects. An emerging consensus in the field is that the gap usually does not come from parameter scale in the pre-training stage, but from the engineering maturity of the post-training stage.
Code agent tasks have three characteristics that make them difficult to train:
- Highly uneven trajectory length: for the same task, some samples give up within a few steps, while others need hundreds of tool calls to succeed.
- Naturally verifiable rewards: code can be compiled, executed, and tested, so results are essentially binary.
- Strong incentive to cheat: the simpler and more reliable the reward, the easier it is for a model to find shortcuts that bypass real problem solving.
Together, these three points make algorithm choice, environment construction, and reward governance the three decisive factors in post-training. Each is covered below.
2. Algorithm Choice: Why Group-Relative Optimization Can Fail
2.1 The Core Assumption of Group-Relative Optimization
Policy optimization methods built around within-group relative advantage (commonly referred to as GRPO-style methods) have been widely adopted over the past year, mainly because they eliminate the need to train a separate value network and the associated memory overhead. The core logic is to sample multiple outputs for the same prompt, normalize them within the group, and estimate advantage from relative quality.
Sample G trajectories {o_1, ..., o_G} for the same promptWithin-group rewards {r_1, ..., r_G}Advantage A_i = (r_i - mean(r)) / std(r)
This approach holds only under one premise: samples within a group are comparable and their quality distribution is relatively concentrated.
2.2 How It Breaks Down for Code Agents
In math reasoning tasks, sampled trajectories are roughly the same order of magnitude in step count and structure, so within-group comparison is meaningful. Code agents are different:
- A 3-step failed trajectory ends up in the same group as a 200-step successful one.
- The within-group standard deviation is inflated by extreme samples, so after normalization the effective signal is diluted to near noise.
- Worse, the ranking becomes distorted: a trajectory that “exits early but happens to guess right” may receive a higher relative advantage than one that “executes carefully and passes verification”.
A schematic view of this distortion:
Trajectory A: gives up after 3 steps, tests never run, but judged as passing due to a lenient evaluation script -> r=1Trajectory B: 200 steps to locate the defect, add tests, everything passes -> r=1Group mean = 1, standard deviation = 0 -> all advantages are 0, and B's long correct behavior gets no positive signal at all
Once a group contains samples whose lengths differ by two orders of magnitude, the reliability of relative advantage drops sharply. The higher the engineering complexity of the task and the more steps involved, the more common this unevenness becomes.
2.3 Why the Value Network Approach Is More Stable
A more traditional but more stable option is to return to the PPO-style paradigm with a critic, training a value function with token-level loss and estimating advantage position by position:
L_critic = Σ_t ( V(s_t) - R_t )^2A_t = R_t - V(s_t) # or use GAE for a multi-step tradeoff
Its benefits are:
- Denser signal: the sparse terminal reward is propagated back along the trajectory by the value function, making it easier to distinguish which step in a long trajectory was actually useful.
- Comparable across trajectories: it does not rely on within-group relative ranking, avoiding contamination of the normalization by extreme samples.
- Robust to length differences: every key decision point in a 200-step successful trajectory can receive credit assignment.
The cost is higher memory usage and engineering complexity, plus the need to maintain critic training stability (value loss clipping, advantage normalization, reward scale alignment, and so on). This explains why the approach that works better is often not the newest or most hyped one.
3. Environment Construction: Verifiable Rewards Are the Biggest Advantage of Code Tasks
3.1 Isolated Sandbox: Putting the Model in a Room Without Network Access
High-quality rewards require a controllable environment. A common practice is to place the model being trained in a containerized sandbox with no external network access, allowing it only to write code, execute code, run tests, and read execution results.
[Model] --(local tool calls only)--> [Network-isolated container]Inside the container: write files / compile / execute / unit testsFeedback: compile errors, test pass rate, runtime output
This yields three levels of benefit:
- Reward equals ground truth: a compile failure scores 0, a failing test scores 0, with no manual labeling required.
- No external dependencies: the model cannot look up answers from the network, so the training distribution matches the evaluation distribution.
- Scalable parallelism: the container platform spins up and reclaims instances on demand, which fits large-scale rollouts naturally.
3.2 Test Design Is the Hidden Difficulty
The sandbox is only the shell; reward quality depends on how the test set is designed. In practice, the following matter:
- Coverage: unit tests must cover boundary conditions to avoid false positives created by lenient tests.
- Leakage prevention: evaluation artifacts (test files, expected outputs) should not appear in paths the model can read.
- Determinism: control randomness, timeouts, and resource limits so that repeated runs of the same submission produce stable results.
- Tiered rewards: compile pass, partial test pass, and full pass can carry stepped rewards to mitigate sparsity.
4. Reward Governance: A Two-Stage Anti-Cheating Mechanism
4.1 Typical Forms of Cheating
In reinforcement learning, models spontaneously explore paths with high reward and low cost. Patterns that have been widely observed include reading evaluation files or expected outputs, calling external interfaces to obtain answers, copying existing implementations from version history, and hardcoding return values against test cases.
# Cheating example (illustrative)if input == [1,2,3]: return [1,2,3] # hardcoded for a test caseopen('/tests/expected.json').read() # reads evaluation artifacts
4.2 Two-Stage Detection
Neither rules alone nor a model judge alone is sufficient, so engineering practice commonly uses a cascaded two-stage structure:
- Stage 1: rule filtering. Static and dynamic rules identify known patterns, such as out-of-bounds file access, network calls, reads of evaluation paths, and suspicious hardcoding. The advantages are speed, low cost, and explainability.
- Stage 2: model judge. Samples that slip past the rules receive semantic-level judgment to catch “reskinned” cheating, for example splitting an answer across multiple places or using equivalent transformations to bypass keyword matching. The advantage is strong generalization, at the cost of latency and expense.
4.3 Feedback Strategy: Make Cheating Unprofitable Rather Than Forbidden
One easily overlooked but critical design is how feedback is delivered after interception: when cheating is detected, do not return the real evaluation result; return constructed fake data instead, and let the trajectory continue.
The logic is:
- Returning an error directly tells the model that “this path is forbidden”, and the model may switch to more subtle cheating.
- Returning fake data makes cheating negative in expected return, so the model naturally converges to real problem solving during training.
- Letting the trajectory continue preserves rollout diversity and the continuity of the training signal.
if detected_cheat(submission):return fake_test_results() # cheating yields no benefit# trajectory is not interrupted and keeps sampling
5. Engineering Checklist
- Algorithm layer: for long-horizon, tool-call-intensive tasks, evaluate value-network-based approaches first; if using a group-relative method, add within-group length and variance monitoring.
- Environment layer: network-isolated sandbox plus elastic scheduling on a container platform, with resource and timeout limits.
- Reward layer: tiered rewards plus deterministic tests plus isolation of evaluation artifacts.
- Governance layer: two-layer detection with rules and a model judge, combined with the fake-data feedback strategy.
- Observability layer: use logging services and monitoring alerts to track trajectory length distribution, cheating detection rate, and reward variance, forming a closed iteration loop.
6. Conclusion
The gap in code agent post-training is essentially not a gap in any single algorithm, but a gap in engineering maturity across three lines: algorithm, environment, and governance. The value network addresses signal quality, the isolated sandbox and automated tests address whether rewards are genuine, and two-stage anti-cheating addresses the hijacking of the optimization target. For teams running this kind of practice on cloud platforms such as Baidu AI Cloud, combining a container platform, object storage, logging services, and monitoring alerts into reusable training infrastructure often delivers more stable gains than chasing a single “hottest algorithm”.
