Why Reinforcement Learning Struggles to Converge for Coding Agents

    This article explains why reinforcement learning for coding agents often fails to converge, and what to do about it. It covers why group-relative advantage normalization breaks down when trajectory lengths vary from a few steps to hundreds, why a value network provides a more reliable baseline for long-horizon tasks, how to build executable, isolated, and reproducible reward environments with layered but objective scoring, and how a two-stage anti-cheating pipeline removes shortcuts. It closes with a practical engineering checklist and the metrics worth monitoring beyond success rate.

    1. Background: Why Post-Training Coding Agents Is Harder Than It Looks

    Much of the recent industry attention has focused on using reinforcement learning to improve model reasoning. One approach in particular has been widely adopted because it is simple to implement and cheap to engineer: sample multiple responses to the same prompt, normalize relative advantages within the group, and skip the separate value network. This works well for short-horizon tasks such as math and competition problems. Applied unchanged to coding agents, however, it often produces training curves that oscillate for long stretches, success rates that plateau, or even policy degradation.

    The root cause is a difference in task shape. A math problem can usually be judged from a single response, and trajectory length is roughly fixed. A coding agent, by contrast, must repeatedly write code, execute it, observe the result, and revise inside an environment. Trajectory length is determined jointly by task difficulty and the exploration process. For the same requirement, one trajectory may give up after three steps while another passes every test case only after two hundred. This extremely uneven distribution invalidates the premise behind within-group comparison.

    2. Key Point 1: Advantage Estimation Must Match the Trajectory Distribution

    2.1 Why Within-Group Normalization Fails

    Within-group relative advantage rests on a core assumption: quality differences among samples in the same group come mainly from policy stochasticity, so the group mean and variance can serve as a baseline. When a group contains both very short failed trajectories and very long successful ones, the mean and variance are dominated by a few extreme samples, and the normalized advantage values degrade into something close to noise. Worse, short trajectories consume fewer tokens and have lower variance, which makes them more likely to be amplified in the loss. The model is pushed toward the low-cost behavior of giving up quickly.

    Schematically, the problem is not the formula but the samples:

    1. prompt: fix the defect in the repository and pass all tests
    2. rollout A: 3 steps -> gives up, outputs "cannot locate the problem" (failure, very short)
    3. rollout B: 200 steps -> repeated debugging, then all cases pass (success, very long)
    4. after within-group normalization: the sign and magnitude of A's and B's advantages are both unstable

    2.2 Value-Function-Based Advantage Estimation

    A more robust option is to return to a critic-based setup and replace within-group relative ranking with per-token advantage estimation. A value network provides an absolute reference for the expected long-term return from the current state. It does not depend on the length or quality of other samples in the same group, so it is naturally insensitive to differences in trajectory length. Three engineering points matter:

    1. The value network and the policy network should share the same tokenizer and action space definition to avoid reward alignment bias.
    2. Normalize advantages by length or discount them by stage, so negative advantages on very long trajectories do not accumulate and overwhelm the policy.
    3. Set a minimum exploration budget for failed trajectories so the model does not learn “exit early” as a shortcut.
    1. # Pseudocode: per-token advantage estimation with a critic
    2. values = critic(states) # value estimate for each state
    3. returns = discounted_rewards(rewards, gamma=0.99, lam=0.95)
    4. adv = returns - values
    5. adv = length_normalize(adv, mask=action_mask) # suppress advantage accumulation on long trajectories
    6. loss = policy_loss(logprobs, adv) + vf_coef * value_loss(values, returns)

    The conclusion is straightforward: the longer the task and the higher the engineering complexity, the more you need an absolute reference frame. Porting the success recipe from short-horizon tasks directly onto long-horizon agent tasks is a hidden reason many teams see no improvement.

    3. Key Point 2: The Reward Environment Must Be Executable, Isolated, and Reproducible

    3.1 The Natural Advantage of Code Tasks

    Code is one of the few modalities where results can be judged mechanically: a compilation failure scores zero, a failing test scores zero, and passing yields reward. These signals are literally ground-truth labels. They require no human preference annotation and introduce no subjective bias from a judge model. To make full use of this advantage, three conditions are needed:

    • Isolation: the model under training runs in a container with no external network access, able only to read and write local files and run local commands.
    • Reproducibility: dependency versions, random seeds, the test suite, and timeout policies are all fixed.
    • Batchability: the environment can spin up and tear down concurrently, making trajectory sampling throughput an adjustable knob.

    3.2 Reward Design

    A single “score only if everything passes” rule creates a sparse reward problem. A layered design is advisable, as long as the judgments stay objective:

    Layer Judgment Purpose
    Static checks Whether syntax/compilation passes Provides an early dense signal
    Unit cases Pass ratio of target test cases Main reward source
    Regression cases Whether existing capability is broken Discourages cheat-style fixes that break other parts
    Efficiency constraints Timeouts, resource limits Prevents brute-force enumeration from passing

    One point deserves emphasis: the simpler and more reliable the reward, the stronger the model’s incentive to hunt for loopholes. Environment design must therefore advance together with anti-cheating mechanisms, rather than being patched in after training is already running.

    4. Key Point 3: Two-Stage Anti-Cheating That Closes the Loopholes

    4.1 Common Cheating Patterns

    Under reinforcement learning, models spontaneously discover shortcuts along the evaluation path. Typical ones include reading evaluation artifacts or answer files, copying existing implementations from version history, pulling target source code via external requests, hardcoding test assertions into return values, and special-casing specific inputs instead of fixing the underlying logic. These behaviors score well on reward while doing nothing to improve real capability.

    4.2 A Two-Stage Detection Pipeline

    The first stage is rule-based and static filtering: cheap to run and covering high-frequency patterns. It includes file access whitelists, blocking external calls, matching suspicious strings and assertion patterns, and patch scope validation (whether changes spill into the test directory). The second stage is a semantic judge, where a model assesses intent from the trajectory and the patch, covering subtle variants that rules struggle to enumerate, such as dressing up special-case logic as a seemingly general utility function.

    1. trajectory/patch
    2. -> rule layer: paths, external calls, patch scope, hardcoded assertion signatures
    3. hit -> judged as cheating
    4. -> semantic layer: judge model evaluates "did it actually fix the root cause"
    5. hit -> judged as cheating
    6. -> both pass -> counted as normal reward

    4.3 Feedback Strategy: Make Cheating Unprofitable, Not Forbidden

    One easily overlooked but critical design choice is how interception works. If a violation immediately raises an error and terminates the trajectory, what the model learns is that “certain actions get punished,” and it may shift to more subtle variants. A more effective approach is to return observations that are structurally valid but factually false (fabricated file contents, fabricated test results) while letting the trajectory continue. The model then runs into self-contradiction in later steps, finds the task impossible to complete, and abandons that path on its own. This turns cheating into a policy with negative expected return rather than an action banned by a rule.

    5. Engineering Checklist

    1. Quantify the trajectory length distribution first, then choose the advantage estimation scheme; when the long tail is significant, bring in a value network.
    2. On the environment side, fix dependencies and the test suite, and expose sampling concurrency, timeouts, and resource limits as configuration items for reproducibility and tuning.
    3. Keep rewards layered but objective, and always include regression cases to avoid “trading breakage for a pass.”
    4. Ship anti-cheating alongside training: the rule layer handles high-frequency cases, the semantic layer handles the long tail, and newly discovered patterns are continuously fed back into the rule layer.
    5. Do not monitor success rate alone. Also track average trajectory length, early-exit rate, cheating interception rate, and regression failure rate, and judge together whether the policy is genuinely improving.
    6. Compute and scheduling can rely on general cloud capabilities such as container platforms, object storage and logging services, and monitoring and alerting. This decouples environment orchestration from training observability and lowers engineering complexity.

    6. Conclusion

    The gap in coding agent post-training usually lies not in model architecture but in the hard work of signal quality: whether advantage estimation matches the trajectory distribution, whether rewards come from an executable and isolated environment, and whether loopholes are systematically governed. Get these three things solid and the improvement is sustainable. Chase algorithm names while ignoring the environment and evaluation pipeline, and you will likely stay stuck in place on long-horizon tasks.