Long-Horizon Agents: Reinforcement Learning and Production Engineering
A practical guide to training and deploying long-horizon AI agents, covering rollout capacity planning, multi-domain rewards, sandbox isolation, long-context inference, checkpoint recovery, multi-agent communication, and coding-task evaluation. All numerical examples are hypothetical and intended to illustrate calculations rather than production benchmarks.
Long-horizon agents can make repeated tool calls, read and write files, and complete complex tasks over many steps. Compared with single-turn question answering, these workloads place greater demands on post-training methods, infrastructure, and inference efficiency.
This article focuses on general architectures and engineering decisions rather than any specific product. All numerical examples are hypothetical; replace them with measured data when planning a deployment.
1. Scaling Reinforcement Learning Across Domains
Traditional reinforcement learning from human feedback (RLHF) primarily optimizes alignment and harmlessness, with rewards often derived from preference scores for individual responses. For long-horizon agents, the objective should shift toward task completion across multi-step environment interactions. Rewards must evaluate the entire tool-use trajectory, not just the wording of the final response.
A training framework needs to address two central challenges.
Heterogeneous Resource Scheduling and Rollout Throughput
RL training data comes from interactions between the model and its environment. Rollout generation often becomes a bottleneck before training does.
Suppose each trajectory contains an average of 30 tool calls. Each environment response takes approximately two seconds, and model inference takes one second per step. At three seconds per step, a trajectory takes about 90 seconds. One environment can therefore complete approximately 40 trajectories per hour.
Collecting 10,000 trajectories per hour requires roughly 250 parallel environments, along with enough inference capacity to handle their requests.
This can also be estimated in steady state:
- Concurrent trajectories = new trajectories per second × trajectory duration.
- 10,000 trajectories per hour is approximately 2.8 new trajectories per second.
- Multiplying by 90 seconds gives approximately 250 concurrent trajectories.
- Each trajectory issues an inference request every three seconds, producing approximately 83 inference queries per second (QPS).
The following table shows several capacity levels. GPU counts assume that one GPU can sustain 10 QPS; actual capacity must be established through load testing.
| Trajectories per hour | New trajectories per second | Parallel environments | Inference QPS | Reference GPU count at 10 QPS per GPU |
|---|---|---|---|---|
| 10,000 | Approximately 2.8 | 250 | Approximately 83 | Approximately 9; reserve additional headroom |
| 50,000 | Approximately 13.9 | 1,250 | Approximately 417 | Approximately 42 |
| 100,000 | Approximately 27.8 | 2,500 | Approximately 833 | Approximately 84 |
The scheduler should allocate GPU resources dynamically based on rollout queue depth. Inference, environment execution, and training should use separate resource pools so that slow environment execution does not tie up inference or training resources.
Combining Rewards Across Domains
Reward sources differ substantially by domain. Coding tasks can use automated tests. Financial research requires checking whether cited data can be traced to its original source. General conversation relies on preference models.
Three principles help combine these signals:
- Enforce hard constraints first. Failed tests, unverifiable citations, and unauthorized access should set the reward to zero or a negative value. Other scores must not offset hard-constraint violations.
- Weight soft objectives. Combine conciseness, formatting, and clarity using weighted scores. Weights can change during training: emphasize correctness early, then gradually increase the weight assigned to conciseness.
- Monitor reward quality. Track agreement between rewards and human ratings alongside task pass rates. Spearman correlation is a common measure. If pass rates rise while errors in human spot checks also increase, the model may be exploiting weaknesses in the reward rules, and validators need tightening.
2. Infrastructure for Long-Horizon Agents
Continuous interaction with an environment requires three foundations: sandboxing, scheduling, and environment quality checks.
Sandbox Isolation and Resource Quotas
When an agent executes terminal commands, writes code, or calls external tools, the sandbox is the main barrier protecting the host. A common approach combines containers with lightweight virtual machines and applies the following restrictions:
- Deny outbound network access by default, allowing only allowlisted domains.
- Limit CPU, memory, disk usage, and process counts.
- Create a fresh instance for each task and destroy it afterward rather than reusing it.
- Never place real production credentials in the sandbox.
The following pseudocode illustrates timeouts, snapshots, and rollback. Output from a timed-out command is not returned to the model, and the caller must treat the timeout as a failure. If no snapshot exists, the code raises an exception rather than claiming recovery; the upper-level workflow must mark the task as failed.
class SandboxRollbackError(Exception):passclass AgentSandbox:def __init__(self, image_tag, resource_limits, snapshot_every=5, max_snapshots=10):self.image_tag = image_tagself.resource_limits = resource_limitsself.container = create_container(image=image_tag, limits=resource_limits)self.snapshot_every = snapshot_everyself.max_snapshots = max_snapshotsself.step_count = 0self.snapshots = []self.audit_log = []def execute_command(self, cmd, timeout_s=30):self.step_count += 1result = self.container.run(cmd, timeout=timeout_s)self.audit_log.append({"cmd": cmd, "exit_code": result.exit_code,"timed_out": result.timed_out})if result.timed_out:self.container.kill_process_group()self.mark_dirty()return self.rollback_to_last_snapshot()if self.step_count % self.snapshot_every == 0:self.snapshots.append(self.container.snapshot())self._prune_snapshots()return result.outputdef mark_dirty(self):self.container.flag_unhealthy()def rollback_to_last_snapshot(self):if not self.snapshots:self.audit_log.append({"event": "rollback_no_snapshot"})self._rebuild_container()raise SandboxRollbackError("no snapshot available, task marked failed")last = self.snapshots[-1]self._rebuild_container()self.container.restore(last)self.audit_log.append({"event": "rollback", "snapshot_id": last.id})return last.iddef _rebuild_container(self):self.container.destroy()self.container = create_container(image=self.image_tag, limits=self.resource_limits)def _prune_snapshots(self):while len(self.snapshots) > self.max_snapshots:old = self.snapshots.pop(0)old.delete()
Failure-Handling Checklist
Define responses to common failures before running long-horizon tasks rather than making ad hoc decisions during execution.
| Failure or event | Response |
|---|---|
| Individual command timeout | Enforce a per-command timeout, terminate the entire process group, log the event, and roll back to the latest snapshot. |
| Total task duration exceeded | Save the current checkpoint, mark the task as resumable or failed, and release resources. |
| Out-of-memory (OOM) event | Enforce cgroup memory limits, mark the environment as dirty, rebuild the instance, and restore from a snapshot. |
| Unauthorized network request | Reject the connection, record the destination, and terminate the task if violations exceed a defined threshold. |
| Filesystem access outside permitted paths | Restrict mounted paths; reject out-of-bounds writes and record them in the audit log. |
| Rollback without an available snapshot | Rebuild the instance, mark the task as failed, and retain audit records for manual review. |
| Task completion | Destroy containers and volumes, erase temporary sensitive files, and verify that no residual data remains before releasing the instance. |
Snapshots consume storage and need a cleanup policy. The example saves a snapshot every five steps and keeps only the latest ten. Delete all snapshots when a task ends unless the task is marked as resumable. A suggested audit-log retention period is at least 90 days, subject to applicable compliance requirements.
Sandbox design must also address escape attempts, resource exhaustion, and residual data. Conduct periodic penetration tests to verify that isolation boundaries remain effective. Record every command, file write, and network request in separate, append-only storage that processes inside the task cannot modify.
State Management for Long Contexts
Interaction histories can easily exceed the model’s context window during long-running tasks. Three common strategies are:
- Retain the task objective, constraints, and raw records from the most recent steps.
- Compress older history into summaries.
- Place critical instructions at the beginning of every request to prevent truncation.
Evaluate summary quality separately: losing important details during compression can directly cause errors in later steps.
3. Inference Trade-Offs with Extremely Long Contexts
Long inputs increase inference costs in two main ways: memory consumption and computation.
KV-Cache Memory
KV-cache memory grows approximately linearly with context length. Memory per token is:
KV-cache bytes per token =2 × number of layers × number of KV heads× head dimension × bytes per element
The factor of two accounts for both key and value caches. Total memory also depends on batch size and sequence length.
Consider a hypothetical configuration with 80 layers, eight KV heads, a head dimension of 128, and FP16 storage at two bytes per element:
2 × 80 × 8 × 128 × 2 = 327,680 bytes per token
That is approximately 320 KiB per token. At batch size one and a context length of one million tokens, the cache alone occupies approximately 327.7 GB, using decimal gigabytes. This exceeds the capacity of a single 80 GB GPU. Even counting only keys or only values would require approximately 164 GB.
Model weights and activations consume additional memory. Extremely long contexts therefore require multi-GPU partitioning, tiered caching, or compression.
Computation
During prefill, full-attention computation scales quadratically with sequence length. During decoding, each generated token requires reading the full KV cache, so memory traffic scales linearly with sequence length.
Sparse attention, sliding windows, and chunking strategies can change these relationships, but their effects on output quality must be validated.
Common Optimization Techniques
- PagedAttention. Inspired by operating-system virtual memory, paged memory management divides the KV cache into fixed-size blocks allocated on demand. This reduces fragmentation and can increase concurrent request capacity. Benefits depend on the request-length distribution; wider length variation generally makes fragmentation more pronounced.
- Kernel fusion and speculative decoding. Kernel fusion reduces intermediate writes to GPU memory and lowers memory-access overhead. Speculative decoding uses a smaller model to draft candidate tokens that a larger model verifies in parallel. Acceptance rate determines the benefit. When acceptance is low, the draft model’s additional computation can reduce overall speed.
Before deployment, run A/B load tests using the same request set. Compare time to first token, output tokens per second, and peak GPU memory usage.
Reporting Throughput Results
Claims such as “2–3× higher throughput” are useful only when accompanied by measurement conditions. The same optimization can produce substantially different gains under different workloads.
At a minimum, report:
- Model size and exact version.
- Input and output length distributions, ideally including medians and tail percentiles.
- Hardware models, device counts, and interconnect topology.
- Batch size and scheduling policy.
- Exact implementation version and configuration of the baseline.
For reproducibility, fix random seeds, warm up before timing, repeat each experiment at least three times, and report both the mean and variability.
4. Designing Managed Agent Services
Managed agent services provide execution environments, persistent state, and collaboration mechanisms as infrastructure for developers. Three areas require particular attention.
Checkpoints and Resumable Execution
Network interruptions, node failures, and environment errors can disrupt long-running tasks. The service should periodically save checkpoints containing:
- Task ID and checkpoint version.
- Current state-machine phase.
- A summary of the agent’s working state, typically without retaining full chain-of-thought.
- Tool-call history, including call IDs, argument hashes, returned results, and timestamps.
- Sandbox snapshot ID.
- Idempotency keys.
Checkpoints may contain user data, credential fragments, or business-sensitive information. Redact data before writing it, encrypt sensitive fields separately, and apply access controls and expiration policies. Store tool arguments as hashes rather than plaintext.
A recommended recovery model is at-least-once delivery with idempotent processing. Resume from the latest checkpoint. For incomplete tool calls, first query their status using the idempotency key. If a call has already taken effect, retrieve its result; otherwise, execute it again.
Side-effecting operations, such as file writes and requests to external systems, must support idempotency keys to prevent duplicate effects during replay.
Multi-Agent Communication
A coding agent and a review agent can collaborate asynchronously through a message queue. Use a consistent message format, such as:
{"msg_id": "7f3c2a10-9b1e-4d8a-a0c2-5e6f1d2b3c4d","trace_id": "task-20261124-0042","sender": "coder-agent","receiver": "review-agent","type": "review_request","seq": 3,"attempt": 1,"payload": {"diff_ref": "obj://bucket/diffs/0042-3.patch"}}
Here:
msg_idsupports deduplication.trace_idlinks events across the entire task.seqsupports message ordering for a given sender.attemptrecords retries.
Consumers should maintain a deduplication table of processed msg_id values, with retention longer than the maximum retry window.
On delivery failure, senders should retry with exponential backoff and random jitter:
delay = min(base_delay × 2^attempt, maximum_delay) + random_jitter
Set a retry limit. Messages that exceed it should move to a dead-letter queue for manual handling or a higher-level workflow.
Observability
Collect at least the following metrics:
- Token consumption per task.
- Tool-call success rate.
- Per-step latency distributions.
- Sandbox restart counts.
- Checkpoint recovery counts.
- Final task status.
Both logs and metrics should be correlatable by trace_id, making it possible to reconstruct a failed task from beginning to end.
5. Evaluating Long-Horizon Coding Tasks
Long-horizon coding tasks provide a direct view of agent capabilities. Evaluation should cover each stage, not just the final pass or fail result.
The following framework is a starting point. Calibrate thresholds to match your task difficulty.
| Stage | Metric | Suggested initial pass criterion | Common failure | Debugging action |
|---|---|---|---|---|
| Environment preparation | Dependency installation success rate | First-attempt success meets a predefined baseline | Dependency version conflicts | Pin versions and verify that a lockfile was generated. |
| Compilation and build | Build pass rate | Exit code is zero | Syntax errors or incorrect import paths | Preserve build logs and provide errors as input to the next iteration. |
| Functional validation | Test pass rate | All tests pass | Missed edge cases | Add edge-case tests and include them in training data. |
| Repair iterations | Average iteration count | Does not exceed a defined limit | Repeated edits to the same location | Detect repeated diffs and require a change in repair strategy. |
| Output quality | Lines of code and token count | Remains within a defined multiple of the reference implementation | Excessive defensive code or verbose comments | Add a length penalty to the reward function. |
| Operational safety | Unauthorized operation count and dangerous-command blocking rate | Zero unauthorized operations; all dangerous commands blocked | Privilege escalation, non-allowlisted connections, or deletion of critical files | Locate commands in audit logs, tighten allowlists, and rerun in isolation. |
Calibrate thresholds in three steps:
- Divide tasks into easy, medium, and hard groups, and calibrate each group separately.
- Use a percentile of historical successful runs, such as P80, as the initial threshold.
- Size human spot checks for a 95% confidence level and a margin of error of ±5 percentage points. Using the most conservative assumed pass rate of 0.5 requires approximately 385 samples per difficulty group:
1.96² × 0.5 × 0.5 ÷ 0.05² ≈ 384.16
Round up to 385.
6. Recommended Implementation Sequence
- Build sandboxing and audit logging first. Ensure every command and network request can be traced.
- Define hard reward constraints and soft objectives. Add human spot checks and monitor agreement between rewards and human ratings.
- Estimate compute requirements. Use the capacity calculations in Section 1, and separate rollout generation, inference, and training into distinct resource pools.
- Implement checkpoints and idempotency keys. Validate recovery by deliberately injecting timeouts, OOM events, and network interruptions.
