Long-Horizon Agents: Training, Inference, and Infrastructure
This article explains what makes long-horizon AI agents complete multi-hour tasks reliably. It covers three layers: reward design in post-training reinforcement learning, long-context management during inference, and the isolation, scheduling, and recovery of runtime environments. For each layer, it lists key checks and common mistakes.
Long-horizon AI agents can run reliable multi-hour tasks only when three layers work together: reward design during training, long-context management during inference, and the isolation, scheduling, and recovery of the runtime environment. This article covers each layer, with checkpoints and common mistakes.
1. Reinforcement Learning in Post-Training: Reward Design Sets Behavioral Boundaries
In post-training, models learn to plan and execute across many downstream tasks through reinforcement learning (RL). RL results depend heavily on the reward signal. Common approaches fall into two categories:
- Task-level rewards: In code generation, the generated code runs in a sandbox, and the reward depends on whether it passes the test cases. This signal is objective, but it evaluates only the outcome, not the process.
- Process-level rewards: Intermediate steps of a long task are scored, for example, whether subtasks are reasonably decomposed and whether tool call parameters are correct. This signal is dense, but it requires extra annotation or evaluator models, and evaluator models can be biased themselves.
When designing rewards, guard against three kinds of problems:
- Reward hacking: The model finds shortcuts around the tests, such as hardcoding test inputs or modifying test files. Make test files read-only, and check whether the code touched the evaluation directory before scoring.
- Reward model bias: The evaluator favors certain writing styles or lengths, and the policy model learns to match that preference. Sample outputs for manual review regularly to measure how closely automated scores match human judgment.
- Safety regression: To complete a task, the model may perform unauthorized actions, such as deleting files or sending data externally. Include negative signals for policy violations in the reward, and keep human review as a fallback. Actions such as deleting, publishing, or transferring should require a confirmation step.
In practice, record each reward dimension separately. When a metric becomes abnormal, you can quickly identify which reward term caused the drift.
2. Million-Token Context: How Compute and Memory Actually Grow
Supporting million-token contexts is a prerequisite for long-horizon tasks, but you need to distinguish two kinds of cost.
The compute for standard self-attention grows as O(n²) with sequence length n. Without optimization, the intermediate memory tied to attention also grows quickly. Ring Attention splits the sequence across multiple devices and pipelines communication with computation, which lowers peak memory per device. FlashAttention uses blockwise computation to reduce memory reads and writes, which improves throughput. Neither method changes the theoretical complexity of attention. Both only improve actual resource usage. Capacity planning must account for this distinction.
During decoding, the KV cache stores historical keys and values, and its memory footprint grows roughly linearly with context length. In multi-turn interactions, a cache hit avoids recomputing a prefix that has already been processed. However, cache capacity is limited, so you need an eviction policy. Common strategies include:
- Evicting the least recently used entries;
- Keeping the system prompt and key memories;
- Summarizing earlier conversation and replacing the original content with the summary.
The eviction strategy directly affects whether the agent continues to follow early constraints. Add regression tests to confirm that key constraints still hold after long conversations.
Two boundary conditions apply when you use long contexts:
- Longer is not always better. As irrelevant content increases, it dilutes key information, and recall of content in the middle of the context is usually weaker.
- Chunking, sparse attention, and caching strategies each suit different scenarios. Decide whether to enable them by measuring latency, memory, and accuracy on your own task set.
3. Underlying Infrastructure: Sandboxing, Scheduling, and Environment Recovery
An agent’s runtime environment needs to cover four areas: environment isolation, resource control, state monitoring, and failure recovery.
1. Sandbox Isolation
Run each task in its own container sandbox. Use cgroups to limit CPU, memory, and network bandwidth, and use namespaces to isolate processes and the filesystem. Network egress should use an allowlist to prevent tasks from reaching sensitive services on the internal network. After the task ends, destroy the sandbox and clear temporary files and credentials.
2. Scheduling and Multi-Agent Coordination
The scheduler must consider dependencies, task priority, and resource quotas at the same time. The simplified pseudocode below shows where timeouts, retries, and idempotency fit:
class AgentScheduler:def __init__(self, container_engine, max_retries=3):self.engine = container_engine # Connect to the container scheduling serviceself.max_retries = max_retriesdef dispatch_task(self, task):# Idempotency: create only one sandbox when the same task is submitted repeatedlyif self.engine.exists(task.idempotency_key):return self.engine.get(task.idempotency_key)for attempt in range(self.max_retries):try:return self.engine.create_sandbox(image=task.env_image,cpu="4",memory="16Gi",timeout_seconds=task.timeout,idempotency_key=task.idempotency_key,)except TransientError:continue # Retry only on transient errorsexcept PermissionError:raise # Fail immediately on permission errors without retrying# Clean up resources partially created during failed attempts to avoid orphaned containers occupying quotaself.engine.cleanup(task.idempotency_key)raise RuntimeError("sandbox creation failed")
Set timeouts for each task type separately rather than using one global value. Tie resource cleanup to the failure path. Otherwise, failed tasks leave unmanaged containers that keep consuming quota.
3. Environment Quality Checks and Checkpoint Recovery
Long tasks are vulnerable to network jitter and timeouts from dependent services. The quality-checking platform uses heartbeat detection and state verification to determine whether an agent has stalled. Recovery must meet three requirements:
- Data consistency: Checkpoints should fall on boundaries of completed steps. Before recovery, verify the hashes or version numbers of intermediate artifacts so the task does not resume from a half-written file.
- Sensitive information cleanup: Checkpoints must not store plaintext keys. A key management service should inject credentials on demand, and the credentials should be revoked when the task ends.
- Audit logs: Record the reason for each recovery, along with the source and target environments, to support later tracing.
If checkpoint verification fails, or the new environment cannot provide isolation, pause the task and notify a human operator. Do not force execution to continue.
