Evaluating Long-Horizon Coding Agents: From Outcome Rewards to Step-Level Credit Assignment
Long-horizon coding agents often receive only sparse outcome rewards, which makes credit assignment across many interaction steps difficult. This article explains why final-result-only training can penalize correct exploration, then discusses counterfactual branch value estimation: restoring sandbox snapshots, rolling out multiple branches under the same policy, and comparing estimated state values to measure each step’s contribution. It also covers engineering constraints, evaluation dimensions, and cybersecurity evaluation and governance considerations.
1. Background: Why Long-Horizon Coding Tasks Are Hard to Train
Coding agents usually need to complete a sequence of operations in a sandbox environment: read code, locate defects, understand module relationships, modify files, and run tests. A real task often requires dozens of interaction turns—sometimes twenty or thirty steps, sometimes close to one hundred.
The reward signal for such tasks is usually sparse. The environment gives only one result at the end of the task, such as 1 point if all tests pass and 0 otherwise. There is no direct feedback for intermediate steps.
Suppose a trajectory has 80 steps. The first 78 steps correctly locate and analyze the problem, but step 79 writes a wrong variable name while modifying code, so the unit test at step 80 fails and the final reward is 0. In common policy gradient methods, all steps in the same trajectory share the same final return. This means all tokens from step 1 to step 80 receive the same negative update. Correct exploration in the first 78 steps is also suppressed.
This mechanism has three direct consequences. First, the agent has difficulty obtaining effective positive signals during early exploration, and training can stall in the initial stage. Second, to avoid failure, the model tends to reduce exploration and shorten reasoning, making behavior more conservative. Third, to reduce the probability of errors, the model may consume more tokens on redundant validation, increasing inference cost.
It should be noted that many public materials report specific benchmark scores for models. These numbers depend on test conditions, evaluation versions, and environment configurations. Without complete reproduction information, this article does not cite those numbers and discusses only methods and evaluation approaches.
2. Why Not Simply Score Every Step
Since outcome rewards are insufficient for attribution, an intuitive idea is to score every step. This idea has three engineering difficulties.
First, the value of an intermediate step depends on subsequent direction. The same modification may lead to completely different results under different contexts and follow-up operations. It is hard to judge whether a single step is good or bad in isolation.
Second, scoring requires domain knowledge. Judging whether a code modification is reasonable usually requires understanding project architecture, dependencies, and test intent. If humans or another model label every step, the cost is high, and the labels themselves may be wrong.
Third, process rewards are easy to exploit. If a reward function rewards behavior that “looks like progress,” the model will learn to game process metrics rather than actually solve the problem.
Therefore, practice usually requires balancing two types of approaches:
| Approach | Advantages | Disadvantages |
|---|---|---|
| Outcome reward | Clear objective, unbiased | Sparse signal, high variance, coarse attribution |
| Process reward | Dense signal, easier attribution | High labeling cost, exploitable, potentially biased |
A more robust route is to keep outcome rewards as the main objective while using verifiable methods to estimate each step’s contribution. Counterfactual branch value estimation belongs to this category.
3. Basic Idea of Counterfactual Branch Value Estimation
Counterfactual branch value estimation borrows from the Monte Carlo tree search practice of “expanding branches and counting outcomes,” combined with the causal reasoning idea of comparing “what would have happened if a different choice had been made.”
The core steps are as follows.
First, keep the complete context up to step k-1 and restore the environment to the state before step k begins. This requires the sandbox to support snapshots and rollback.
Second, from that state, let the same policy independently roll out N subsequent trajectories. Each trajectory receives a final outcome, such as 1 for success and 0 for failure.
Third, use the average success rate of the N trajectories to estimate the value V(sk) of that state. By comparing the values of adjacent states, the contribution of step k can be estimated. If V(s_k) is clearly higher than V(s{k-1}), the operation at step k increased the success probability. If it is clearly lower, the step introduced a problem.
An illustrative pseudocode version is as follows:
def estimate_state_value(prefix_snapshot, policy, env, n_branches):outcomes = []for _ in range(n_branches):sandbox = env.restore(prefix_snapshot) # Restore to the state before step kresult = policy.rollout(sandbox) # Same policy continues the taskoutcomes.append(result.reward) # 1 for success, 0 for failurevalue = sum(outcomes) / len(outcomes)spread = standard_error(outcomes) # Uncertainty of the estimatereturn value, spreaddef step_contribution(snapshot_before, snapshot_after, policy, env, n):v_before, _ = estimate_state_value(snapshot_before, policy, env, n)v_after, _ = estimate_state_value(snapshot_after, policy, env, n)return v_after - v_before # Positive value indicates a favorable step
The key point is that this approach transforms “whether this step is good” into “whether the subsequent success rate changes from this step onward.” Attribution is based on repeatable environment outcomes rather than subjective judgment.
4. Go Analogy for Step-Level Attribution
In Go, a “good move” and a “bad move” are not completely determined by the final win or loss. A brilliant move may reveal its value dozens of moves later, while a mistake may only become apparent at the end of the game. Professional players often use life-and-death problems and local position judgment to evaluate the quality of a move, rather than looking only at the final result.
Counterfactual branch value estimation follows this idea. Suppose that after step 78, multiple rollouts from the same state have a high success rate, while the specific modification at step 79 causes a large drop in success rate. Then the problem can be attributed to the execution detail at step 79, rather than the localization and analysis at step 78.
This judgment has two preconditions. First, rollout results of the same policy from the same state must be stable enough; otherwise, estimation noise will drown out the signal. Second, the number of rollouts must be large enough, usually adjusted dynamically based on variance estimates.
It should be noted that this method estimates the value of the current policy in the current environment. If the policy itself is not capable enough, the estimates will be generally low, and the reference value of step-level attribution will decrease. Therefore, it is better suited to models that already have basic capability and are in an iterative optimization stage.
5. Key Engineering Issues
Bringing the above idea into a training pipeline requires consideration of the following aspects.
Sandbox snapshot and rollback capability
Branch estimation relies on precise state restoration. The file system, dependency versions, process state, and random seeds all need to be controllable. If the environment has non-reproducible external dependencies, estimation results will be distorted.Compute cost control
Expanding N branches at each critical step multiplies computation. In practice, branch estimation can be performed only for high-uncertainty steps, such as code modification, test execution, and key assumptions.Mixed use of rewards
A more robust approach is to combine outcome rewards with step-level advantage estimates. Outcome rewards ensure that the training objective is consistent with the task, while step-level estimates reduce variance and improve credit assignment. The weights of the two need to be determined experimentally.Avoid overfitting the evaluation environment
If training and evaluation use the same set of environments, the model may learn environment-specific shortcuts. It is advisable to keep independent validation environments and periodically change task sources.Curriculum training
First train basic localization and modification capabilities on shorter tasks, then gradually increase task length. This can reduce early exploration stagnation in long-horizon tasks.Monitoring metrics
In addition to success rate, monitor average turns, token consumption per task, tool-call error rate, and the number of steps required for the first effective modification. If success rate increases while token consumption also surges, the model may be relying on redundant validation to obtain results.
6. Evaluation Framework for Coding Ability
When evaluating coding agents, a single pass rate cannot reflect the full picture of capability. It is advisable to judge from the following dimensions.
Task completion quality: beyond whether the final tests pass, also check whether the modification introduces regressions, changes unrelated files, or is inconsistent with the project’s code style.
Process efficiency: including the number of turns used to locate defects, the proportion of invalid operations, and the number of repeated file reads.
Stability: the distribution of success rates for the same task across multiple random seeds. Excessive variance indicates unreliable model behavior.
Cost: average token consumption and inference time. Cost should be considered together with success rate; looking at either alone can be misleading.
Generalization: performance on unseen code repositories and tasks in different languages.
7. Evaluation and Governance of Cybersecurity Capabilities
As coding capability increases, model performance on security-related tasks may also improve. Such capabilities are dual-use. The same capability can be used to find and fix vulnerabilities, but it can also be misused for attacks. Therefore, evaluation and governance need to proceed together.
At the evaluation level, it is advisable to focus on defense-oriented tasks: reproduce known vulnerabilities in isolated environments, determine whether the model can identify the root cause, whether it can generate a fix that passes regression tests, and whether it can explain the scope of impact of the fix. Evaluation reports should not include operational details that can be directly used for attacks.
At the governance level, at least the following measures are needed.
First, evaluation and training environments should be completely isolated, and sandboxes should be prohibited from accessing the real external network.
Second, complete operation logs should be recorded for later auditing.
Third, phased thresholds should be set for the release of high-risk capabilities, with human review.
Fourth, a vulnerability disclosure process should be established to notify affected parties when problems are found, rather than spreading them publicly.
For developers, this means that when introducing coding agents, they should assume that the agent has permission to modify files and execute commands, and design least-privilege policies accordingly.
8. Conclusion
The core difficulty of long-horizon coding tasks is credit assignment. Training that relies only on final outcomes amplifies punishment for innocent steps and suppresses exploration. Counterfactual branch value estimation provides a verifiable approach: through snapshot rollback and multiple rollouts, it estimates the impact of each step on success rate. The method has high cost and high requirements for environment reproducibility, but it shifts attribution from subjective judgment to repeatable experiments.
At the evaluation level, outcome quality, process efficiency, stability, cost, and generalization should be considered together. In cybersecurity, capability improvements need to advance together with isolation, auditing, and disclosure mechanisms. Only in this way can progress in coding agents translate into reliable engineering gains.
