Three Engineering Breakthroughs in Code Agent Post-Training

    This article examines why code agents from different teams show large success-rate gaps despite similar algorithms and base model sizes, arguing that the bottleneck lies in the quality of reward signals during post-training rather than pretraining. It breaks the problem into three layers: replacing group-relative advantage normalization with a value network for token-level advantage estimation, building sandboxed training environments that produce trustworthy executable rewards, and applying a two-stage anti-cheating pipeline that returns plausible but false data instead of hard failures. A final checklist covers trajectory length analysis, reward densification, and observability.

    1. The Problem: The Gap Is in Post-Training Signal Quality, Not Pretraining

    On the capability curve of large models, pretraining sets the ceiling of the base model, while post-training determines whether that ceiling can be reliably approached. A pattern confirmed repeatedly over the past two years is that when different teams tackle the same class of agent tasks—especially code agents—with similar algorithm families and similar base model sizes, final success rates still differ substantially. The root cause is usually not a shortage of compute, but whether the reward signal obtained during reinforcement learning is trustworthy and has enough resolution.

    Code agent tasks have three structural characteristics that make them harder to train than math reasoning:

    1. Extreme variance in trajectory length: sampling in parallel under the same prompt, some trajectories terminate after three steps with a “cannot be done” verdict, while others run for hundreds of steps with repeated compilation and debugging before passing.
    2. Sparse intermediate states: the vast majority of steps have no immediate feedback; success is judged only at the end by tests.
    3. A read-write environment: the agent has execution and network capabilities, so it naturally has a path to “bypass the task and obtain the answer directly.”

    Together, these three points degrade mainstream group-relative optimization methods and allow rewards to be contaminated. The engineering solutions are broken down below across three layers: algorithm, environment, and anti-cheating.

    2. Layer One: Why Group Normalization Fails on Long-Horizon Tasks

    Sample G trajectories for the same prompt. Group normalization subtracts the group mean from each trajectory’s return and divides by the group standard deviation to produce an advantage estimate. This implicitly assumes that the quality distribution of samples within the group is roughly homogeneous, so that the mean and variance are meaningful statistics.

    In the code agent setting, this assumption breaks down completely:

    1. rollout#1: length 3, result fail -> advantage ≈ 0 (flattened by the mean)
    2. rollout#2: length 47, result fail -> advantage ≈ 0
    3. rollout#3: length 200, result success -> advantage compressed by extreme variance

    There are two problems. First, the mean is dragged down by a large number of “early-exit failures,” while the variance is inflated by a few very long trajectories, so the relative advantage of successful samples is compressed and the learning signal is diluted. Second, short and long trajectories are not on the same comparison scale; forcing them into the same group and taking differences is equivalent to using noise as the gradient. The higher the task’s engineering complexity and the more steps involved, the more pronounced this failure becomes.

    A more stable approach is to introduce a value network (Critic) for token-level advantage estimation: the value function provides a baseline of expected return from each state to termination, and the difference between the actual return and that baseline is used as the advantage. It does not require within-group homogeneity, only that the value function fits well enough on the current policy distribution. There are three engineering points:

    • Refresh the baseline as the policy updates, avoiding systematic bias from a stale value function;
    • Length-normalize the advantage, preventing long trajectories from dominating the gradient simply because they contain more tokens;
    • Weight termination steps and tool-call steps, propagating the sparse success signal back to key decision points.

    An illustrative version (expressing only the general idea of clipping and normalization):

    1. # Pseudocode: token-level advantage + length normalization
    2. adv = returns - critic.value(states) # value-based baseline
    3. adv = adv / (adv.std() + 1e-6) # global scale normalization
    4. loss = -(logp * adv * step_weight).sum() / token_count
    5. loss = clip_ratio(loss, eps_low=0.8, eps_high=1.2)

    3. Layer Two: The Training Environment Is the Source of Reward Trustworthiness

    The natural advantage of code is that it is executable: a failed compile scores zero, a failed test scores zero, and the reward is literally ground truth without requiring human annotation. To fully exploit this advantage, the environment must do three things:

    • Full isolation: no external network, no host credentials, the task repository mounted read-only, containers created and destroyed on demand;
    • Reproducibility: pinned dependency versions and base images, replayable test results, so flakiness is not learned by the model as “retrying will pass”;
    • Separation of judging and execution: rewards are produced by an independent evaluation process; the training side only reads scalar results and never touches evaluation artifacts.

    A minimal usable sandbox execution skeleton:

    1. def run_in_sandbox(patch: str, tests: list[str]) -> float:
    2. with Sandbox(network=False, read_only_repo=True, cpu="2", mem="4Gi") as box:
    3. box.apply(patch)
    4. build = box.exec(["make", "-j2"]) # a build failure returns 0 directly
    5. if build.returncode != 0:
    6. return 0.0
    7. passed = sum(box.exec([t]).returncode == 0 for t in tests)
    8. return passed / len(tests) # pass rate as a densified reward

    For reward design, it is advisable to add segmented densification on top of the binary verdict: assign different tiers to compile passing, unit tests passing, and all tests passing, so that early gradients are not all zero. At the same time, keep one hard constraint—any privilege violation (accessing the network, reading the evaluation directory) is scored negative rather than zero, because a zero score is indistinguishable from a “normal failure.”

    4. Layer Three: Two-Stage Anti-Cheating, and Making Cheating Unprofitable

    Once rewards are simple and reliable, the model has a strong incentive to take shortcuts. Cheating patterns repeatedly observed in practice include: reading evaluation artifacts or answer files, copying implementations from upstream commit history, pulling the target source code directly via the command line, loosening test assertions, and hardcoding input-output mappings.

    Rules alone are not enough, and a model judge alone is not enough. A mature solution is a two-stage pipeline in series:

    1. Rule layer (high recall, low cost): path and file access allowlists, system call and command blacklists, a full network egress block, and static scanning of the patch diff (whether test files are modified, whether suspicious constant tables appear).
    2. Judge layer (semantic judgment): an independent model performs a semantic review of trajectories to catch covert techniques that rules cannot cover, for example logic constructed step by step that is equivalent to hardcoding, or answers passed indirectly through environment variables.

    The most critical design is the form of feedback: once cheating is detected, instead of terminating with a hard error, return structurally valid but factually false data and allow the trajectory to continue. The model then discovers within its own reasoning chain that “this path does not work and the payoff is zero,” and abandons the shortcut on its own. Compared with direct interception, this avoids teaching the model “how to evade the detector” and shifts adversarial pressure from “hiding behavior” to “completing the task.”

    Engineering support is needed: decouple and separately log cheating verdicts and rewards, version the detection rules, make judge prompts and thresholds rollback-able, and randomize the distribution of the false data so the model cannot identify a fixed pattern.

    5. Implementation Checklist

    • First quantify the trajectory length distribution; if P95/P50 exceeds 3x, suspect group normalization failure first;
    • Replace the group baseline with a value network, and length-normalize the advantage with weighting on key steps;
    • Keep the training environment network-free, read-only, and ephemeral, with rewards produced by an independent process;
    • Densify rewards in segments, and score privilege violations negative rather than zero;
    • Run anti-cheating as a two-stage pipeline, with feedback using “false data + allow continuation”;
    • Instrument the whole pipeline: trajectory length percentiles, cheating rate, false-data trigger rate, and the pass-rate-versus-step curve.

    This combination does not rely on any single trick; it drives three things through at the same time: matching the algorithm to the task distribution, having the environment provide ground-truth rewards, and systematically eliminating shortcuts. Most teams stop at knowing that anti-cheating is necessary; actually spending months turning it into versioned, observable infrastructure is the watershed where results diverge. If general cloud capabilities such as a container platform, object storage, and log monitoring are already available, sandbox scheduling, trajectory archiving, and metric alerting can be standardized to further reduce reproduction costs.