How Code Agents Improve: Post-Training and the Data Flywheel
This article explains why code agent improvements cannot be attributed to any single algorithm. It breaks down the four interdependent pillars of post-training for code agents—real verifiable tasks, credit assignment over long trajectories, reward design, and reward hacking prevention—and compares group-relative policy optimization with value-model-based PPO. It also covers how to build executable task datasets, scale data without scaling noise, sandbox execution environments, design reliable rewards, and validate genuine engineering capability through a closed loop of data, environment, and algorithms.
How Code Agents Improve: Post-Training and the Data Flywheel
1. Frame the Problem First: Agent Progress Cannot Be Attributed to a Single Algorithm
Before discussing why code agents perform better, we must distinguish two capabilities: generating code snippets from a description, and working in a real repository—reading the project, locating issues, editing multiple files, running tests, and iterating based on feedback.
The latter is not a single text generation pass. It is a multi-step decision process in which the context at each step is shaped by previous actions. One wrong file edit, one inappropriate test command, or ending a task too early can change the final outcome.
Post-training for code agents therefore involves at least four interdependent components:
- Whether tasks are realistic, executable, and verifiable;
- Whether the optimization algorithm can extract useful signal from trajectories of varying length;
- Whether test-based rewards align with actual engineering goals;
- Whether the model can exploit environment loopholes to achieve false success.
Final benchmark results alone cannot tell you which algorithm a system used, nor prove that alternative approaches cannot reach the same outcome. A more reliable analysis decomposes the mechanisms above and evaluates contributions through controlled experiments.
2. The Core Difficulty of Long-Horizon Tasks: Assigning Final Outcomes to Intermediate Decisions
A coding task can be represented as a trajectory:
Task description → inspect files → analyze dependencies → modify code → run tests → adjust based on results → submit.
The same task can produce very different trajectories. Some fail quickly; some succeed after several repair rounds; others run for a long time without ever touching the real problem.
The training system may ultimately receive only a coarse outcome: success or failure. But what the model needs to learn is whether each action was worth taking in its current state. This is the credit assignment problem.
For example, a successful fix may hinge on three key decisions: spotting a boundary condition, locating the faulty function, and adding a necessary check. The same trajectory may also contain a large amount of useless searching. Applying the same positive signal uniformly to every action risks reinforcing inefficient behavior alongside the useful parts.
Long-horizon code training therefore cannot care only about “did it pass in the end.” It must also consider how rewards propagate, how trajectories are truncated, how samples of different lengths are weighted, and whether failure causes can be distinguished.
3. Group-Relative Optimization vs. Value Estimation: How to Choose
Group-relative policy optimization is a common approach: sample multiple candidate trajectories for the same task, then compute relative advantages from their rewards. It typically avoids training a separate value model, reducing some training and maintenance cost.
One precondition for this method to work well is that rewards differ meaningfully across candidates. If every trajectory in a group fails, or all receive the same score, the learning signal from intra-group comparison can be very weak.
Long-horizon code tasks add further complications: trajectory lengths, tool call counts, and failure points vary widely. How sequence-level rewards are assigned to generation positions, and whether the loss is normalized per trajectory or per generated unit, both affect the actual optimization direction.
That said, differing trajectory lengths do not mean group-relative optimization necessarily fails, nor can we conclude that short trajectories always gain an unfair advantage. The outcome also depends on reward design, sampling strategy, length handling, and optimization implementation.
The other route is proximal policy optimization with a value model. The value model estimates expected future cumulative return from the current state and helps compute the advantage:
Advantage ≈ actual or estimated return − expected return of the current state.
Intuitively, this asks: was this step better than what the model would typically do in this state?
For tasks with multi-turn tool interaction, value estimation can provide finer-grained learning signals. But it has costs: extra model compute and training data, and potentially large prediction errors under sparse rewards and complex states.
Algorithm selection should therefore compare complete systems, not names. A reasonable experiment at minimum holds constant the task distribution, sampling budget, execution budget, and evaluation criteria, then compares success rate, training stability, and compute cost.
4. Data Is Not Q&A Text—It Is a Set of Executable Task Assets
Dataset construction for code agents cannot stop at collecting “problem description plus reference answer.” A task suitable for post-training usually needs:
- A clear problem statement with acceptance boundaries;
- A reproducible initial project state;
- A pinned or traceable dependency environment;
- Visible tests and protected acceptance tests;
- Resource limits, execution constraints, and the permitted scope of modification;
- Auditable execution traces and final results.
Together, these form a training sample. Without the environment and verification conditions, no amount of rich text description can produce a stable reinforcement learning signal.
Tasks can come from licensed bug-fix records, feature change requests, controlled synthetic defects, and existing test-driven engineering exercises. Whatever the source, they must pass executability screening.
For example, the initial state should genuinely reproduce the problem; there should be a reasonable path to a passing fix; failures should not stem mainly from missing dependencies or environment faults. Otherwise the model spends its effort on obstacles unrelated to the objective.
Reference patches can help reviewers audit tasks, but correctness should not be defined as matching the reference patch. The same problem can have multiple valid implementations; acceptance should center on behavioral constraints rather than textual similarity.
5. Scaling Data Without Scaling Noise
Before expanding task volume, establish quality gates. A workable pipeline looks like:
Task collection → license check → environment reconstruction → defect reproduction → acceptance validation → deduplication and stratification → small-scale trial training → continuous回收 of anomalous samples.
(That final step means continuously recycling anomalous samples back into review.)
Three items deserve special attention.
First, split data by project and change affiliation. Random text-level splitting can place highly similar code and patches in both training and evaluation sets. High scores obtained this way do not necessarily indicate generalization.
Second, distinguish failure types. A wrong model edit, a broken test script, a resource limit breach, and an execution environment crash should not be lumped together as the same failure. Error labels produced by system faults directly contaminate the training objective.
Third, preserve reproducible evidence. Task versions, environment versions, test versions, and execution records should be linked. Otherwise, when rewards fluctuate, you cannot tell whether the cause is the model, the tests, or the environment.
Task difficulty also needs dynamic management. A flood of overly easy tasks saturates quickly; a flood of nearly impossible tasks may starve the system of positive signal for a long time. A more robust approach adjusts sampling proportions across difficulty levels based on the current model’s success rate and task coverage.
6. Isolated Execution Aims to Establish Trustworthy Boundaries
Code is executable, so automatic feedback is available through compilation, tests, and runtime results. But “the program ran” does not equal “the task is done.”
Tests only verify the behavior they cover. Uncovered edge cases, concurrency issues, performance regressions, and security flaws can still slip through. Test results should be treated as verification evidence with explicit boundaries, not unconditional ground truth.
Training environments typically need the following isolation measures:
- Block external network access by default; prepare dependencies in advance through controlled channels;
- Separate the working directory from acceptance resources;
- Restrict access to critical files and evaluation configuration;
- Limit CPU, memory, disk, runtime, and subprocess counts;
- Reset to a clean state after each execution;
- Log file changes, tool calls, and anomalous behavior.
Containerization helps with environment reproducibility and resource management, but a container alone should not be treated as a complete security boundary. When executing untrusted code, combine it with privilege reduction, syscall filtering, and stronger runtime isolation.
Critically, authoritative acceptance must not depend entirely on scripts the model can modify. In-workspace tests can help the model debug, but the final score should come from a protected execution path.
7. Reward Design: Avoid “Easy to Score, Off Target”
The simplest reward assigns a positive value for success and zero for failure. It is easy to understand, but the learning signal in long-horizon tasks can be too sparse.
Auxiliary signals can help—for example, whether the build is restored, whether the pass rate of target tests improved, or whether existing functionality regressed. Intermediate rewards must be used carefully, however.
Reward the number of modified files, and the model may manufacture meaningless changes. Reward test runs, and it may execute tests repeatedly. Reward only pass rate, and it may try deleting failing test cases.
Sounder principles:
- Use protected final acceptance as the primary basis;
- Intermediate rewards assist learning but never replace the final objective;
- Evaluate efficiency only after correctness is basically assured.
Also avoid mixing incomparable test results into a single score. Test counts, coverage, and difficulty differ across tasks; “passing 90% of tests” can mean entirely different things in two projects.
8. Anti-Cheating Is Not an Add-On—It Is Part of the Reward System
Wherever a reward has an exploitable loophole, the model may discover it during optimization. Common risks include modifying the evaluation entry point, reading hidden answers, faking success output, exploiting leftover state, and obtaining the target implementation through external channels.
Defenses should operate at three levels.
Level one: permission and structural isolation. Hidden tests are inaccessible, critical configuration is read-only, and external access is controlled—enforced by system mechanisms first, not by relying on the model’s judgment after the fact.
Level two: deterministic detection. Build audit rules for sensitive path access, abnormal file modifications, privilege escalation, and suspicious execution behavior. Rules suit well-defined events and are reproducible and explainable.
Level three: semantic review. For suspicious behavior expressed through dynamically constructed paths or indirect calls, full trajectories can support auxiliary judgment. But LLM judges also make mistakes and cannot be the sole basis for decisions.
Handling should distinguish normal exploration, policy violations, and infrastructure anomalies. Clear violations can terminate execution and flag the sample; ambiguous trajectories can go to review. Controlled experiments may study what happens if execution continues, but returning fabricated results to the model should not become general practice—it introduces new environmental uncertainty that interferes with both learning and auditing.
9. How to Prove the Model Learned Development Skills
Rising rewards on the training set only show the model is better at the current reward system. Alone, this does not prove genuine engineering capability has improved.
Evaluation should cover:
- Correctness: is the target functionality implemented, and is existing functionality intact?
- Generalization: can it handle unseen projects, different code structures, and different task phrasings?
- Efficiency: under a unified time and execution budget, what are the success rate and call costs?
- Robustness: is it stable under incomplete prompts, test noise, and complex dependencies?
- Compliance: does it respect boundaries on file access, external access, and data usage?
For high-variance tasks, run repeated trials and report the range of variation. When comparing approaches, keep the running budget equal. A system allowed to retry for a long time and a system limited to short executions cannot be compared on final success rate alone.
For real deliverables, add human code review, static analysis, and necessary security assessment. Automated tests are infrastructure, not a substitute for engineering responsibility.
10. What Actually Works: A Closed Loop of Data, Environment, and Algorithms
Post-training for code agents can be summarized as:
Build reproducible tasks → generate trajectories in a controlled environment → verify results through protected mechanisms → identify anomalies and reward loopholes → optimize the policy and value estimates → test generalization on held-out tasks.
This loop explains why “more data” does not always help. If the task environment is unstable, more data amplifies label noise. If acceptance has loopholes, stronger optimization reinforces gaming behavior. If evaluation leaks, rising scores can mask stagnant capability.
For development teams, the higher-priority investment is not chasing a single algorithm, but solidifying task definition, execution reproducibility, reward trustworthiness, and evaluation independence. The algorithm determines how the signal is used; the data and environment determine whether that signal is worth trusting. Only when both hold can training gains translate into transferable, auditable engineering capability.
