Long-Horizon Agent Reinforcement Learning: Environment, Algorithm, and System Practices
This article outlines a practical approach to long-horizon agent reinforcement learning for terminal operations, code editing, and multi-step debugging. It covers problem definition, environment selection, RL recipes for long and stale trajectories, a shared agent harness for training and evaluation, system efficiency on hundred-GPU-scale clusters, migration risks, and an actionable checklist, with emphasis on the Pareto trade-off between success rate and per-task cost.
Long-horizon agent reinforcement learning aims to let models make continuous decisions in scenarios such as terminal operations, code modification, and multi-step debugging, rather than completing only single-turn question answering. What industry teams really care about is often not an absolute score on a leaderboard, but the position on the same Pareto curve: whether per-task inference cost can drop by an order of magnitude at an acceptable pass rate, and whether the capability can migrate from synthetic environments to real software engineering tasks.
The following sections break down “training a usable agent on a hundred-GPU-scale cluster” into executable principles across five layers: problem definition, data and environments, algorithm recipes, systems and evaluation, and deployment recommendations. No specific third-party model names, benchmark names, or hardware models are used here; performance figures should be read as relative improvements over a baseline or as orders-of-magnitude cost changes, rather than unverified absolute claims.
1. Problem Definition: Long Horizon, Sparse Rewards, Cost Sensitivity
Typical trajectories for terminal and coding agents are long: a single task may contain dozens to hundreds of steps of commands, file reads and writes, test failures, and repairs. Rewards are often given only at the end of the task as success or failure, with almost no dense labels for intermediate steps. At the same time, if inference uses extremely high sampling intensity, the cost per task expands rapidly, making enterprise-scale use impractical.
The training objective should therefore optimize three things together: first, Pass@1-type metrics (success rate within a limited number of attempts on the same task); second, trajectory length and wasted exploration; third, average per-task cost after deployment. These three form a Pareto frontier: simply increasing sampling can raise success rate but push cost outside the acceptable region. A reasonable approach is to write “complete the task with fewer interactions” into rewards and data filtering during training, rather than leaving the entire burden to inference.
2. Environment Selection: Moderate Difficulty, Reliable Signals, Reproducibility
Full-parameter reinforcement learning is highly sensitive to noise. Environment design should follow these principles:
First, difficulty stratification. Tasks that are too easy produce near-zero gradients; tasks that are too hard almost always fail, and the policy cannot learn structure. Maintain tasks in an intermediate range according to the current policy’s success rate, and dynamically swap in harder samples during training to form a curriculum.
Second, verifiable rewards. In terminal and coding scenarios, use executable checks whenever possible: whether the test suite passes, whether files conform to specifications, and whether command exit codes indicate success. Subjective scoring should be auxiliary only to avoid reward hacking.
Third, isolation and reproducibility. Each rollout should start in a clean workspace, with dependency versions locked and clear timeouts and resource quotas. Otherwise, the same policy can receive different rewards on different machines, amplifying non-stationarity.
Fourth, task diversity. Training only on one type of command line will overfit. Cover sub-skills such as dependency installation, log investigation, patch generation, regression testing, and documentation and configuration changes, and control the share of templated problems to prevent the model from memorizing answers.
3. RL Recipes for Long, Stale, Low-Precision Trajectories
Long-horizon rollouts have three engineering realities: sequences are very long, collected data is already “stale” by the time it is used for updates, and lower numerical precision is often used to save memory. The following recipe points are common industry ideas, not product-specific interfaces:
Full-parameter and frozen-policy choices should match the modality. If the base model contains a vision tower or retrieval indexer and the current task is mainly text terminal work, freeze non-language modules and focus updates on language parameters to reduce optimization difficulty and communication overhead. Whether to update auxiliary heads such as multi-token prediction depends on whether they participate in actual decoding; if they do, train them as well to avoid train-inference mismatch.
Advantage estimation should resist variance. Under sparse terminal rewards, shaping can be given to completed tasks based on step count and failed retries, but keep shaping weights conservative to prevent the agent from learning to “farm steps” or “fake completion.” Policy-optimization methods such as relative policy optimization should limit update magnitude and combine value baselines or group normalization to reduce variance on very long trajectories.
Handle stale trajectories. In asynchronous collection, the policy has advanced several steps, and importance sampling ratios for old trajectories will drift. Set ratio thresholds, clip or drop stale batches, and match collection and training cadence to avoid queue buildup.
Low precision and stability. In mixed-precision training, keep higher-precision accumulation for policy log probabilities, KL penalties, and value heads. Set gradient clipping by layer or global norm to prevent explosions in very long backward passes. A regularization term (KL to a reference policy) prevents reward hacking from causing language collapse.
Exploration and cost. Moderate randomness during training helps discover repair paths, but deployment should converge to shorter trajectories. Use temperature annealing or penalize overly long interactions in the reward so the Pareto frontier moves toward both higher success and lower cost.
Illustrative pseudocode (for structure only, not a runnable product interface):
for batch in rollout_queue:if too_stale(batch):drop()continueadv = normalize(returns - baseline)loss = clipped_policy_loss(adv) + value_loss + kl_to_refclip_grad(); optimizer.step()
4. A Shared Agent Runtime for Training and Evaluation
Many cases of “good training, poor evaluation” come from harness inconsistency: training uses one tool protocol, while evaluation uses another parsing rule. Use the same runtime framework to cover: tool-call format, workspace lifecycle, timeouts and retries, log persistence, and success determination. The observation space during training should match production to avoid the model learning to rely on fields leaked by the evaluator.
Evaluation should use multiple independent trials and report mean and variance, not the single best result. Cost accounting should include average output tokens, tool-call rounds, and failed retries, not just nominal unit price. When self-hosting, public price lists can be used for comparison, but billing assumptions must be stated to avoid incomparable numbers.
5. System Efficiency: Reducing Wall-Clock Time to Days on a Hundred-GPU-Scale Cluster
When running hundred-billion-parameter-scale full-parameter reinforcement learning on a limited number of accelerators, the bottleneck is usually rollout generation rather than backpropagation. Practical points include: increase the number of concurrent environments during generation so accelerator utilization is not blocked by a single very long trajectory; use pipeline or tensor parallelism to shard the language model during training, overlapping communication and computation; scale environments horizontally with containers or lightweight sandboxes, decoupling CPU from accelerators; store checkpoints and trajectories in object storage, and send logs and monitoring alerts to a unified observability platform to locate reward anomalies and numerical instability.
A container platform handles elastic sandbox scaling; object storage saves trajectories and weights; a message queue can decouple collection and learning processes; logging and monitoring alerts observe success rate, KL, gradient norm, and queue latency. These are generic cloud capability categories, not vendor-specific trademarks. If elastic training and inference resources from a cloud provider are used, the priority remains integrating parallelism strategy, environment concurrency, and data pipeline, rather than changing algorithm names.
6. Migration and Risks
If improvements on synthetic terminal tasks can partially migrate to real repository repair, it usually indicates that the model has learned a closed loop of “read error information—edit code—run tests,” rather than merely drilling problems. When migration fails, first check whether the tool set has changed, whether tests are stricter, and whether context is longer. On security, sandbox permissions must be restricted, the training process must be prohibited from accessing unauthorized networks and keys, and reward functions must prevent harmful behavior such as deleting critical files from being treated as “task completion.”
7. Actionable Checklist
- Validate rewards and the harness on small-scale tasks before scaling parameters and accelerators.
- Always track success rate and per-task cost together; avoid optimizing only one of them.
- Put curriculum learning and stale-trajectory dropping into the pipeline instead of relying on one-time manual hyperparameter tuning.
- Use the same runtime framework for training, evaluation, and pre-release.
- Do not fabricate unmeasured absolute scores; externally, state methods and relative trends only.
Conclusion: The competitiveness of long-horizon agent reinforcement learning increasingly depends on environment signal quality, algorithm stability for very long trajectories, and integrated collection-training-evaluation engineering, rather than simply stacking accelerators. Within a hundred-GPU-scale budget, doing these three blocks solidly is what creates a chance to approach the Pareto frontier of performance and cost and to migrate the capability to real coding and operations tasks. Elastic compute, container, and observability capabilities on clouds such as Baidu AI Cloud can serve as infrastructure options for this pipeline; selection should still be driven by task isolation, cost accounting, and security compliance.
