Why Reinforcement Learning for Coding Agents Struggles to Converge

    This article examines why reinforcement learning (RL) post-training converges poorly for coding agents compared with math reasoning. It explains when group-relative advantage estimation breaks down on long, uneven trajectories and why value networks are often a better fit. It also covers building trustworthy rewards through isolated sandboxes, designing sparse but strict reward signals, and running two-stage anti-cheating with feedback that makes cheating unrewarding. A practical engineering checklist and common pitfalls are included.

    1. Background: Why Post-Training Coding Agents Is Harder Than Math Reasoning

    Over the past year, the dominant paradigm in large-model post-training has been reinforcement learning with verifiable rewards: whenever a task has an automatic pass/fail criterion, the model can improve itself through many attempts. Math and code are the two most common choices, but their sampling distributions differ sharply. A math problem has a relatively convergent reasoning chain, so repeated samples of the same problem vary only slightly in solution length and structure. A coding agent, by contrast, must read files, write patches, run commands, inspect errors, and iterate inside a real development environment. Trajectory length can range from three to five steps to several hundred.

    This highly uneven trajectory distribution creates three chained problems:

    • High-variance advantage estimation: rollout length and quality can differ by an order of magnitude, so naive normalization treats noise as signal.
    • Reward contamination: if test files, upstream commit history, or network egress exist in the environment, the model can bypass actually solving the task.
    • The policy actively seeks shortcuts: RL is a stress test, and any exploitable loophole in the rules gets amplified quickly.

    A leading model team addressed all three issues at once in one generation of its coding agent. The gains came mainly from post-training engineering rather than from simply adding parameters or data. The sections below break down the approach layer by layer and abstract it into transferable engineering practices.

    2. Algorithm Layer: Why Value Networks Often Beat Group Normalization on Long-Horizon Code Tasks

    2.1 When Group-Relative Advantage Fails

    Group-normalization algorithms (commonly known in the industry as GRPO-style methods) rest on a core assumption: sample a group of outputs for the same prompt, normalize using the group mean and standard deviation, and derive a relative advantage. This holds only when the group samples are comparable. Once a group contains both a short trajectory that gives up after three steps and a long one that succeeds only after two hundred steps, the mean and variance no longer describe difficulty; they mainly describe sampling randomness.

    A simplified illustration makes the problem clear:

    1. # Group normalization: when group variance comes mainly from length differences, advantage is approximately noise
    2. adv_i = (r_i - mean(r)) / (std(r) + 1e-8)
    3. # Short failed trajectories and long successful ones are compared on the same scale
    4. # Result: randomness is amplified and the real learning signal is diluted

    The consequence is a jittery policy-gradient direction, long plateaus in the training curve, and even oscillation between “learned to give up” and “learned to keep trying.”

    2.2 Why Value Networks Fit Better

    A more conventional approach attaches a separate critic network to the policy model, estimates state value at the token level, and then computes advantage. Its benefits are:

    • Denser signal: it decomposes the sparse “did the tests pass at the end” into expected return at each step.
    • Insensitivity to length: the value function is conditioned on the current state, so a particularly long trajectory is not systematically undervalued.
    • Better interpretability: you can pinpoint which step’s value estimate collapsed, making targeted data and reward fixes easier.

    The cost is higher engineering complexity: GPU memory and compute budget, value-head initialization and warm-up, balancing value loss against policy loss, and controlling drift in the critic itself. A common safe configuration is to warm up the critic with a small set of high-quality trajectories, then gradually relax the policy update magnitude, while monitoring value loss with a moving statistic.

    2.3 How to Choose

    Do not ask “which algorithm is more advanced.” Ask “are the group samples comparable?” The higher the engineering complexity, the more steps involved, and the more varied the failure modes, the more you should favor methods with value estimation. Conversely, for short-chain tasks decidable in a single step, group-based methods offer better cost-effectiveness.

    3. Environment Layer: Turning Rewards into Literal Ground Truth with Isolated Sandboxes

    3.1 Isolation Is a Prerequisite for Trustworthy Rewards

    Code has a natural advantage: it is executable. Compilation failure scores zero, failing tests score zero. But this advantage holds only when the environment is clean. Practical environment requirements include:

    • A training sandbox with no network egress, dependencies baked into the image, and no runtime fetching of external code.
    • A one-time filesystem snapshot per rollout, destroyed afterward to prevent cross-sample state leakage.
    • Physical separation of evaluation artifacts from the training workspace, so the model side can only read—never see—the evaluation scripts and expected outputs.
    • All commands, file reads and writes, and network calls written to an audit log for later attribution.

    On the cloud, you can use the isolation and image-management capabilities of a container platform, store datasets and checkpoints in object storage, and track success rate, average steps, timeout rate, and other metrics with logging and monitoring/alerting services.

    3.2 Reward Design: Sparse but Strict, with Process Constraints

    Using only “did the tests pass” as the reward keeps the signal pure but too sparse. A common approach keeps the outcome reward dominant while adding process-constraint terms that do not change the optimal policy:

    1. reward = 1.0 if all key tests pass
    2. 0.0 if not
    3. -λ * violation_count # unauthorized access, external calls, etc.; small λ, discouraged only

    The key point is that the penalty must not be so large that the model learns to “do nothing,” which would degrade into an extremely conservative policy.

    4. Safety Layer: Two-Stage Anti-Cheating and “Ineffective Feedback”

    4.1 Cheating Is Inevitable

    Whenever a reward is observable, the model will try to read evaluation files, reuse existing implementations, or fetch answers through external interfaces. Such behavior recurring during training is the norm, not an occasional defect.

    4.2 Two-Stage Detection

    • Stage one: rule filtering. Static and dynamic matching based on command patterns, file access paths, and system-call sequences covers high-frequency cheating methods at low cost and low latency.
    • Stage two: model judge. It evaluates semantic-level, concealed behavior that rules miss, such as assembling answers step by step, rewriting test assertions, or faking run results. The judge side needs prompt isolation to avoid being influenced in reverse by training samples.

    4.3 Feedback Strategy: Make Cheating “Unrewarding” Rather Than “Forbidden”

    Intercepting a cheating request and returning structurally valid fake data while letting the trajectory continue is an efficient design. Across many samples, the model infers on its own that “this path leads nowhere,” which is more stable than a hard cutoff and avoids crudely slicing the policy distribution. This requires monitoring how the “fake-data hit rate” moves in tandem with task success rate, so that long-lived fake data does not skew value estimation.

    5. Engineering Checklist

    • Data side: sample in layers by repository, language, and dependency complexity to control within-group length variance; retain failed trajectories for critic warm-up.
    • Training side: tune value loss and policy loss separately, set gradient clipping and an update-magnitude cap, and output per-step value-distribution monitoring.
    • Environment side: bake dependencies into images, isolate with snapshots, separate evaluation from the workspace, and audit everything.
    • Safety side: version the rule library, periodically regression-test the judge model, and roll out the fake-data strategy gradually.
    • Observability side: bring success rate, average steps, timeout rate, cheating interception rate, and value-loss drift into a unified monitoring and alerting dashboard.

    6. Common Pitfalls

    • Attributing all performance differences to data volume while ignoring the signal-to-noise ratio of advantage estimation.
    • Chasing algorithmic novelty first and adding environment isolation later, leaving the reward itself untrustworthy.
    • Doing only rule-based anti-cheating without a semantic layer, or only interception without “unrewarding” feedback.
    • Setting the penalty too high, so the model learns to idle conservatively.

    7. Conclusion

    The gap in coding-agent post-training usually lies not in any single algorithm but in how well advantage estimation, environment trustworthiness, and anti-cheating are coupled. Implementing all three layers to engineering standards, together with general-purpose capabilities such as Baidu AI Cloud’s container platform, object storage, logging, and monitoring/alerting services to build a reproducible pipeline, is the key to stable, step-change improvements.