Building Long-Horizon Agents: Post-Training, Long Context, and Sandboxing
Developing long-horizon agents capable of executing multi-step tasks requires addressing challenges in reinforcement learning post-training, context management, and execution security. This article explores essential agent capabilities, strategies for scaling RL post-training across domains, and techniques like Ring Attention, FlashAttention-2, and PagedAttention to reduce memory and compute pressure during long-context inference. It also covers acceleration methods such as speculative decoding and KV Cache reuse, best practices for building secure sandboxes, writing reliable task scheduling loops, trade-offs between managed and multi-agent systems, evaluating code agents, and common pitfalls to avoid.
What Capabilities Do Long-Horizon Agents Require?
A long-horizon agent refers to a model that continuously executes multi-round tasks in a real-world environment: calling tools, reading feedback, discovering errors, and correcting them until the task is complete. The difference from standard Q&A is that each step depends on the result of the previous one, and errors accumulate progressively. Therefore, the evaluation criteria shift from “whether a single answer is correct” to “whether the task is ultimately completed, and whether the time and cost are acceptable.”
How to Scale Reinforcement Learning Post-Training Across Multiple Domains?
The computational investment in the post-training stage has significantly increased. The traditional approach involves pre-training plus supervised fine-tuning (SFT), while modern approaches run reinforcement learning (RL) across multiple downstream domains. During implementation, three main engineering issues need to be addressed.
First, the experience replay pool should be bucketed by domain to prevent easy task samples from overwhelming difficult ones. A common practice is to set sampling ratios for each domain and dynamically adjust them as training progresses.
Second, multi-domain joint training is prone to catastrophic forgetting, where the model’s general capabilities decline as it becomes stronger in new domains. Countermeasures include retaining general data in the training mix, using a smaller learning rate for domain adaptation, and continuously monitoring degradation with a fixed general evaluation set.
Third, reward design must be granular enough. Coding tasks can use unit test pass rates as rewards, while document-based tasks require human or model scoring. The noise levels of these two types of rewards differ and need to be calibrated separately.
How to Reduce Memory and Compute Pressure in Long-Context Inference?
Million-level token contexts amplify two types of costs: attention computation and memory footprint. Different techniques address different problems and must be understood separately.
Ring Attention splits long sequences across multiple devices. Each device sequentially exchanges Key and Value blocks, distributing a context that cannot fit on a single card across the cluster. Its goal is to expand the processable sequence length, at the cost of inter-device communication volume increasing with the number of devices.
FlashAttention-2 reduces reads, writes, and recomputations to high-bandwidth memory (HBM) through block-wise computation, thereby reducing memory footprint and increasing speed. It does not change the O(n²) theoretical complexity of attention; longer sequences still require more computation.
On the training side, tensor parallelism (TP) and pipeline parallelism (PP) are often combined. TP splits matrix operations within a single layer and requires high-speed intra-node interconnection. PP splits the model by layers, with less inter-layer communication, but creates pipeline bubbles. The general practice is to keep TP within the same node and use PP across nodes.
On the inference side, PagedAttention manages the KV Cache in fixed-size blocks, reducing memory fragmentation and thus supporting more concurrent requests. During stress testing, first-token latency, tokens per second, and memory utilization should be observed simultaneously, and different solutions should be compared under the same concurrency.
How Much Acceleration Can Speculative Decoding and KV Cache Reuse Bring?
Speculative decoding uses a small model to quickly propose candidate tokens, which are then verified in parallel by a larger model. KV Cache reuse avoids repeatedly computing the same prefix. Both can increase output speed, but the magnitude of improvement depends on the specific scenario.
There is currently no uniform acceleration multiplier. The acceptance rate of candidate tokens, batch size, sequence length, and hardware model all affect the results. To determine if a solution is effective, A/B testing should be conducted on your own workloads, recording baseline throughput, hardware configuration, batch settings, and measurement tools. Do not directly adopt the speedup ratios claimed by others.
How to Build a Secure Sandbox Environment?
When an agent executes code or calls tools, it needs to run in an isolated and resource-constrained environment. There are four core requirements for a sandbox.
Resource isolation: Limit CPU, memory, disk, and network egress to prevent a single task from exhausting host resources or accessing the intranet.
Snapshot and rollback: Save environment snapshots before critical steps to revert to the last available state upon failure. The snapshot frequency requires a trade-off between storage cost and recovery granularity.
Data cleanup: Delete temporary files, credentials, and caches after the task ends to prevent sensitive information from remaining for the next task.
Health monitoring: Continuously collect sandbox startup time, crash rate, and resource usage. If an abnormal node is detected, remove it from the scheduling pool.
Risks to watch for include sandbox escapes, agents accidentally deleting files, and resource leaks caused by long-running operations. Before going live, destructive operations should be rehearsed in an isolated environment to confirm the rollback process is functional.
How to Write a Reliable Task Scheduling Loop?
The following pseudocode illustrates a scheduling loop with a step limit and exception handling. It cannot be deployed directly; the interfaces must be implemented according to the actual system.
MAX_STEPS = 30class SandboxError(Exception):passclass LongHorizonAgent:def __init__(self, llm_client, sandbox_factory):self.llm = llm_clientself.sandbox_factory = sandbox_factorydef execute_task(self, task_prompt):sandbox = self.sandbox_factory() # Returns an object with run, available_tools, destroy methodscontext = [{"role": "user", "content": task_prompt}]try:for step in range(MAX_STEPS):action = self.llm.generate(context, tools=sandbox.available_tools())if action.get("type") == "finish":return action.get("result")try:result = sandbox.run(action) # Returns {"ok": bool, "output": str}except SandboxError as e:result = {"ok": False, "output": f"sandbox error: {e}"}context.append({"role": "assistant", "content": str(action)})context.append({"role": "tool", "content": result["output"]})raise RuntimeError(f"Exceeded maximum steps {MAX_STEPS}, task not completed")finally:sandbox.destroy()
The step limit prevents the model from getting stuck in an infinite loop. Sandbox exceptions are converted into observations returned to the model, allowing it to adjust its actions accordingly. The finally block ensures that the sandbox is destroyed whether the task succeeds or fails. In actual systems, context also needs to be truncated or summarized; otherwise, the context for long tasks will continue to grow.
Trade-offs Between Managed Agents and Multi-Agent Collaboration?
Managed agents delegate state management, checkpoint recovery, and log collection to a cloud harness. Developers define goals and acceptance criteria, and the platform handles long-running execution. Logs should save the inputs, actions, and observations of each step for decision backtracking. When selecting a platform, data retention periods, access permissions, and cost limits should also be confirmed.
A common multi-agent pattern is the Manager-Worker model. A main agent breaks down tasks and distributes them, while sub-agents handle code writing, test verification, and document organization respectively. Results are returned asynchronously via a message queue. This approach can split complex engineering tasks but introduces coordination costs, redundant reasoning, and state inconsistency issues. If the task has few steps and strong dependencies, a single agent is usually simpler and has lower maintenance costs.
How to Evaluate Code Agents and Control Costs?
Code agent evaluation can focus on the following metrics: pass@k (the proportion of at least one pass in k attempts), fix success rate, error type distribution, and token waste rate (the proportion of invalid output to total output). An internal long-horizon code evaluation set should include cross-file modification tasks from real open-source projects, not just single-function generation.
For costs, Prefix Caching is effective for frequently reused System Prompts and background knowledge. When a prefix hits the cache, input billing usually decreases, but the hit rate depends on the request structure. Placing fixed content at the front of the request and variable content at the back helps improve the hit rate. Billing rules vary by platform, so actual bills should be used for accounting.
Common Mistakes to Avoid
- Treating long context as infinite memory, ignoring omissions caused by attention dispersion.
- Only performing process isolation in the sandbox without restricting network egress, leading to key leakage.
- Not setting limits on steps and costs, causing the agent to continuously consume resources after getting stuck in a loop.
- Only looking at average scores while ignoring long-tail failure cases.
- Directly using reported speedup ratios for selection without validating them on your own workloads.
