Long-Horizon Agent Post-Training: The Key Leap Forward

    This article explains why long-horizon agent tasks break conventional reinforcement learning, how sparse outcome rewards create a credit assignment problem, and two practical ways to address it: counterfactual partial branch valuation and adaptive optimization backed by large-scale sandbox environments. It also covers the resulting gains in coding and security capabilities, along with a practical checklist for reward design, trajectory filtering, cost control, evaluation, and reproducibility.

    1. Background: Why Long-Horizon Tasks Make Reinforcement Learning “Fail”

    Across recent model progress, coding and agent capabilities have become the most closely watched directions. One detail stands out: parameter count is not the only deciding factor. Models with less than half the parameters of their competitors have matched or surpassed larger models on long-horizon software engineering and security analysis benchmarks, which suggests that algorithm efficiency in the post-training stage and the scale of the environment are becoming a new source of capability gains.

    To understand why, look at the reward structure of a typical long-horizon task. An agent task often takes 30 to 80 interaction turns: reading a codebase, retrieving relevant files, locating a defect, designing a fix, running tests, and rolling back to retry based on errors. At the end, the environment returns a single scalar: whether the tests passed.

    This creates a serious credit assignment problem:

    1. Trajectory τ = [a1, a2, ..., a79, a80]
    2. If step 79 has a mistyped variable name → step 80 test fails → R(τ) = 0
    3. Policy gradient applies a negative update to all of a1..a80

    The first 78 steps may have been a completely correct understanding of the architecture and an accurate localization of the defect, yet the whole trajectory is rejected because of a typo in the last step. This resembles how Go is scored: in a lost game, brilliant moves and blunders are treated the same. There are three consequences:

    1. Hard to get started: the model learns that “less action is safer” and becomes conservative.
    2. Getting worse with training: correct exploration is suppressed, and capability regresses.
    3. Abnormally high token consumption: the model uses large amounts of repetitive reasoning to avoid risk instead of advancing the task.

    2. Why “Scoring Every Step” Is a Dead End

    A natural idea is to introduce process rewards: score each decision individually. But engineering hits a wall immediately. To judge whether the file retrieval at step 37 was “good enough,” the scorer itself must have software engineering judgment. This creates a closed-loop dilemma:

    • No engineering knowledge → no reliable scoring;
    • No scoring → the model gets no dense signal;
    • No model improvement → the scorer gets no better data to improve itself.

    Manual annotation is not viable here either. Step-by-step labeling of trillions of Go moves or massive code trajectories is unacceptable in both cost and consistency.

    3. Breakthrough One: Counterfactual Partial Branch Valuation

    One approach that has recently emerged in the industry can be abstracted as counterfactual partial branch valuation: instead of asking “was this step good,” ask “if we branch off from this step, how does the outcome distribution change.”

    The process can be described as follows:

    1. Save an environment snapshot at step k of the trajectory;
    2. Sample several short branches in parallel from that state (for example, 4 to 8 branches, each 3 to 5 turns);
    3. Use the mean return of the branches as the local value estimate V(s_k) for that state;
    4. Compute the advantage A_k = V(s_k) − baseline, replacing “the whole trajectory multiplied by a single 0.”

    The idea traces back to Monte Carlo tree search and to interventions in causal inference (the do-operator): by forcibly changing an intermediate variable and observing the shift in the downstream distribution, correlation is upgraded to causal attribution.

    Pseudocode sketch:

    1. def counterfactual_value(state, k, n_branches=6, depth=4):
    2. snapshot = env.clone(state) # Environment must support cheap snapshots
    3. returns = []
    4. for _ in range(n_branches):
    5. s = snapshot.restore()
    6. r = rollout(policy, s, steps=depth)
    7. returns.append(r)
    8. return mean(returns) - baseline(state)

    The key engineering constraint is snapshot cost. If every branch has to rebuild the container and dependencies, training throughput collapses. A workable approach is layered snapshots: copy-on-write at the file system layer, lightweight sandbox reuse at the process layer, and incremental commits only for the directories that need them.

    4. Breakthrough Two: Adaptive Optimization and Sandbox Scale-Out

    A parallel route is adaptive optimization: dynamically adjust exploration intensity, branch width, and rollback policy based on the current task state. Hard tasks get more branches and greater depth; easy tasks get fewer, which raises the density of useful signal under a fixed budget. This closely mirrors the scheduling logic of Go programs, where search depth varies with the complexity of the position.

    Supporting all of this is scaling out the sandbox environment. It can be understood as a kind of “environment-side scaling law”: when parameter growth on the model side slows down, put resources into the number of parallel interactive environments so that the number of valid trajectories per unit time rises by one to two orders of magnitude. In engineering terms, this usually requires:

    • A container orchestration platform to schedule thousands of isolated execution units;
    • Object storage to hold code snapshots and artifacts and reduce cold-start copy overhead;
    • A message queue to decouple task dispatch from result collection and smooth out idle time caused by long-tail tasks;
    • Logging and monitoring with alerting to track failure rate, average turns, rollback counts, and other metrics.

    It is worth stressing that environment scale-out is not simply adding machines. If sandbox images are inconsistent and dependencies are not reproducible, sampling noise will drown out the gains from the algorithm.

    5. Two Directions of Emerging Capability: Coding and Security

    The focus of coding capability evaluation has shifted from “write a function” to long-horizon delivery: cross-file refactoring, inferring defects from failing tests, and keeping changes minimally invasive in a large codebase. This requires the model to have stable tool-call formatting, a rollback-capable editing strategy, and a habit of self-verification.

    The emergence of security protection capability is more sensitive. The same set of skills—vulnerability understanding, code auditing, and automated verification—can be used for fixing and hardening, but can also be misused. The responsible approach is therefore to limit training and evaluation to authorized targets, isolate the network, retain audit trails, and add a human review step for high-risk outputs. The stronger the capability, the more the boundary constraints need to be put in place up front rather than patched afterward.

    6. Practical Checklist

    1. Reward design: keep outcome rewards as the main signal and local value estimates as an auxiliary term; avoid weighting process rewards so heavily that the model “games the steps.”
    2. Trajectory filtering: filter on two dimensions, final success or failure × local advantage, and prioritize keeping samples that were “process-correct but outcome-failed”—these are the most valuable training signals.
    3. Cost control: anneal the number of branch samples across training stages, dense early and sparse later.
    4. Evaluation: report success rate, average interaction turns, token consumption, and rollback rate together; a single success rate hides a tendency toward conservatism.
    5. Reproducibility: pin image and dependency versions, otherwise the gains from scaling the environment cannot be attributed.

    7. Conclusion

    The breakthrough in long-horizon agent post-training is essentially about turning the sparse, outcome-only signal into local causal signals that can be attributed, and using scale on the environment side to push the cost of that conversion into an affordable range. For developers, the real lesson is not any specific model or tool but three things: the environment must be snapshot-friendly, rewards must be attributable, and evaluation must be multi-dimensional. The combination of general capabilities at Baidu AI Cloud—container platforms, object storage, logging, and monitoring—happens to provide the foundation for building reproducible, scalable environments for agent training and validation.