Long-Horizon Agent Training: The Outcome Reward Dilemma and Adaptive Optimization
This article explains why outcome-only rewards can make long-horizon software engineering and cybersecurity agents overly conservative, why step-level scoring is hard to do well, and how counterfactual branch estimation at key decision points can produce local credit signals. It also covers the sandbox infrastructure, risks, and governance considerations involved.
Long-horizon agents for software engineering and cybersecurity have become an important direction in technical evaluation. These tasks rarely finish in a single question-and-answer exchange. They often require dozens of interaction rounds: reading code, locating defects, understanding dependencies, modifying the implementation, running tests, and continuing to fix problems based on feedback. The longer the task chain, the sparser the success signal and the harder the training.
One phenomenon deserves attention. In the first few dozen steps, a model may complete high-quality exploration and fault localization, then fail at the final step because of a misspelled variable name or a missed boundary condition. The environment returns only a failure reward. If the training algorithm treats the entire trajectory as one unit and penalizes it, the model may not learn how to fix the problem. Instead, it may learn a conservative strategy: explore less, change less, and consume fewer tokens. This is one of the core tensions in training long-horizon agents.
1. Why outcome rewards make agents more conservative
Outcome rewards for long-horizon tasks are usually terminal. A task receives 1 for success and 0 for failure, or receives a positive reward only when the final test passes. This design is simple and the objective is clear, but it creates a clear credit assignment problem.
Consider a trajectory with 80 interaction steps. Steps 1 to 78 contain exploration, localization, and architecture understanding that are nearly correct. At step 79, the model makes a small error while modifying the code. At step 80, the unit test fails, and the environment returns a reward of 0. A traditional policy gradient method assigns a 0 outcome to the whole trajectory and applies the same penalty to every token from steps 1 to 80. The model cannot tell which steps were strong moves and which were mistakes. It can only lower the weight of the entire trajectory.
This outcome-only approach has three consequences. First, variance is high. In a long trajectory, one local error can drive the global reward to zero, so the gradient signal is very noisy. Second, behavior becomes conservative. To avoid penalties on the whole trajectory, the model tends to explore less, call tools less, and make fewer code changes. Token consumption may still rise, because the model hesitates repeatedly under uncertainty. Third, long tasks are hard to start learning. The longer the task, the more delayed the terminal reward, and the harder it is for the model to get useful feedback from early actions. Training efficiency drops.
Consider an analogy with a chess-playing agent. If every loss were treated as proof that every move was bad, the player could not learn from a lost game which moves were strong and which were weak, or understand the value of a particular exchange in the middlegame. Long-horizon agents also need local credit, not only a final verdict.
2. Why step-level scoring is difficult: domain knowledge and circular dependency
A natural idea is to score every step, since outcome rewards are too coarse. The problem is that step-level scoring requires domain knowledge. In a software engineering task, whether a step such as “open a file and read its dependencies” is reasonable depends on the later code structure, the test intent, and the project conventions. In a cybersecurity task, whether a step such as “send a probe request” is valuable depends on the target environment, the authorization boundary, and the defensive strategy. Without enough domain understanding, it is hard to give reliable scores to individual actions.
The situation also contains a circular dependency. Without software engineering knowledge, the model cannot score steps accurately. Unreliable scores prevent the model from improving. A model that does not improve cannot produce more accurate process scores. Training can then fall into a loop: the model cannot improve because it has not improved.
For this reason, process rewards cannot rely only on manual annotation or fixed rules. A more feasible direction is for the training system to perform local counterfactual evaluation. Instead of requiring an absolute score for every step, the system estimates, at key nodes, what would happen if a different action were taken. This is why adaptive optimization mechanisms are worth studying.
3. Adaptive optimization: estimating local credit with counterfactual branches
The core idea of adaptive optimization draws on Monte Carlo Tree Search and causal inference. The system performs counterfactual local branch valuation at key nodes in a long trajectory, and breaks the terminal result into learnable local advantages.
In practice, the system first identifies key decision points in the trajectory. Examples include entering a function to modify, choosing a repair approach, adjusting a test command, or deciding whether to roll back. At each of these nodes, the system samples several alternative branches and simulates the return of each over a number of following steps. These returns form a local counterfactual baseline. The system then compares the expected return of the actual branch with that of the alternatives to estimate the local advantage of the node. Even when the final task fails, the system can identify that some earlier local actions were better than their alternatives. This avoids penalizing the entire trajectory uniformly.
The following pseudocode shows the basic idea of mixed rewards:
def compute_mixed_advantage(trajectory, key_nodes, branch_budget):global_adv = estimate_global_advantage(trajectory)local_adv = [0.0] * len(trajectory)for node in key_nodes:branches = sample_local_branches(node, k=branch_budget)counterfactual_returns = []for branch in branches:counterfactual_returns.append(simulate_branch(branch, horizon=node.horizon))baseline = mean(counterfactual_returns)actual_return = simulate_branch(node.actual_branch, horizon=node.horizon)local_adv[node.index] = actual_return - baselinemixed_adv = []for t in range(len(trajectory)):mixed_adv.append(global_adv + lambda_local * local_adv[t])return mixed_adv
The pseudocode highlights three points. The global advantage remains, but it is no longer the only signal. Local counterfactual advantages are computed only at key nodes, which keeps branching from exploding. A weight combines the two signals, so the model learns from both the final success or failure of the task and the local quality of its individual decisions. As with a chess agent, losing a game does not mean every move was wrong, and winning does not mean every move was good. The role of counterfactual branch valuation is to turn a terminal verdict into local, comparable causal evidence.
4. Scaling sandboxes: the infrastructure behind long-horizon training
Adaptive optimization depends on large-scale sandbox environments. Long-horizon tasks need realistic or high-fidelity execution environments with code repositories, dependency installation, test execution, network isolation, state rollback, and log collection. If there are too few sandboxes, branch sampling and parallel exploration are limited, and local evaluations lack statistical strength. The training system therefore needs a substantially larger pool of parallel sandboxes, along with environment consistency and replayability. This can be understood as a sandbox scaling pattern: at a controllable cost, increase the number of parallel environments and the diversity of tasks, so the model can learn credit assignment across more state distributions.
Several engineering problems need attention. The first is isolation and security. Cybersecurity tasks in particular must run within authorized boundaries. The second is state snapshots and rollback, which ensure that counterfactual branches can be reproduced from the same node. The third is trajectory storage and logging services, which support replay and audit. The fourth is monitoring, alerting, and resource scheduling, which prevent long-running tasks from overloading the cluster. The fifth is branch budget control. Sampling should prioritize key nodes so that full-tree search does not make costs explode.
For deployment, general-purpose cloud service categories can form the training foundation. For example, a container platform can host sandbox instances, object storage can hold trajectories and snapshots, a log service can collect interaction records, and monitoring and alerting can maintain stability. The general-purpose cloud capabilities offered by Baidu AI Cloud can serve as a reference for engineering choices. The specific architecture, however, still needs to be designed according to the task’s security level and cost model.
5. Why programming and cybersecurity capabilities may emerge
When long-horizon credit assignment improves, programming and cybersecurity capabilities may show stronger emergent behavior. In programming tasks, the model no longer abandons an entire repair path because one test fails. It can preserve locally valid behaviors, such as reading dependencies, locating defects, and constructing patches, and gradually build repository-level understanding, tool use, and test-driven repair skills.
In cybersecurity tasks, a model can learn multi-round probing, vulnerability reproduction, detection rule generation, and defense validation in authorized testing ranges. These capabilities must come with strict security boundaries, audit logs, and access control. “Emergence” is not a mysterious phenomenon. It results from the combined effects of scale, environmental diversity, long-horizon credit assignment, and local exploration. With only terminal rewards, a model tends to become conservative. With only local rewards, a model may learn to exploit the reward. Mixing both signals, together with sandbox isolation and behavior auditing, is more likely to produce usable long-horizon capabilities.
6. Risks and governance recommendations
Adaptive optimization carries risks. First, counterfactual branch simulations may be inaccurate, which biases local advantage estimates. Multi-branch sampling, confidence intervals, and uncertainty weighting can reduce this noise. Second, a model may exploit local reward loopholes, for example by repeatedly triggering cheap positive feedback. Task-level acceptance checks and manual spot reviews can address this. Third, cybersecurity capabilities are dual-use. They must be trained and evaluated in authorized environments, with real-network probing restricted and complete audit trails retained. Fourth, branch search adds computational cost. Budgets should be allocated to key nodes so that long-horizon tasks do not become unaffordable tree searches. Fifth, the training objective should balance conservatism and exploration. A model should not discard an entire trajectory because of a terminal failure, and it should not be encouraged to take ineffective actions because of local scores.
Overall, the main difficulty in training long-horizon agents lies not only in model parameter size but also in credit assignment and environment scale. Outcome rewards are simple but coarse. Step-level scoring is precise but expensive. Counterfactual local branch valuation offers a compromise: it estimates local causal contributions at key nodes and turns terminal signals into learnable process signals. Combined with large-scale sandboxes, mixed rewards, security isolation, and audit governance, long-horizon capabilities in programming and cybersecurity are more likely to emerge stably, rather than remaining stuck in a conservative cycle of penalizing the whole trajectory for a late mistake.
