Training and Evaluating Long-Horizon AI Agents
This article explains why long-horizon capability has become a core metric for AI agents and how to measure it. It covers the infrastructure challenges of reinforcement learning post-training, sandbox environment design, scoring rules for coding agents, and how to interpret benchmark results and report uncertainty. It ends with a checklist for deployment.
1. Why Long-Horizon Capability Has Become a Core Metric
Single-turn question answering is relatively simple to evaluate: given an input, check whether the output is correct. AI agents work differently. An agent must read a code repository, plan steps, call tools, observe execution results, and adjust its course based on feedback. An early wrong judgment can compound through the execution chain and eventually cause the task to fail.
Long-horizon capability can therefore be broken down into three sub-capabilities that can be measured separately:
- Multi-step planning: Decompose a goal into executable subtasks, and keep their order and dependencies correct.
- Tool use: Select the right tool, organize parameters according to the interface specification, and parse return values correctly.
- State maintenance: As the context grows longer, retain key constraints and intermediate conclusions, avoiding forgotten constraints and self-contradiction.
These three sub-capabilities depend on one another. Even precise tool calls cannot help if the plan is wrong. Even a sound plan will drift off target midway if state maintenance fails. Training and evaluation should therefore cover all three together, rather than checking only whether the final answer is correct.
2. Engineering Challenges in Scaling Post-Training Compute
The more reinforcement learning (RL) compute invested in post-training, the more important it is to ensure each unit of compute produces a stable return. In practice, problems usually stem from infrastructure rather than the algorithm’s formulation. The following five areas most often become bottlenecks.
2.1 Throughput and Stability of the RL Framework
RL training has two parts: generating trajectories (rollouts) and updating parameters. Long-horizon tasks produce very long trajectories, and generation takes far longer than for short tasks. This mismatches the load on the sampling side and the training side. Common practices include:
- Scheduling by trajectory length buckets, so short tasks do not wait for long ones.
- Allowing some degree of asynchronous updates while limiting the gap between policy versions, to prevent stale samples from contaminating gradients.
- Setting timeouts and maximum step limits for failed trajectories, so that a single abnormal task cannot consume all resources.
2.2 Cost of Long-Context Inference
Long contexts significantly increase GPU memory and compute overhead during inference. The KV cache grows linearly with context length, while the cost of attention computation grows faster. If training pays the full cost for only a few extremely long samples, overall efficiency suffers. Engineering teams typically adopt the following strategies:
- Sample very long examples in segments, keeping the full context only at key steps.
- Summarize or truncate historical tool outputs, preserving the key structured fields.
- Allocate batch size dynamically according to context length to avoid memory fragmentation.
2.3 Sandbox Environment Infrastructure
Coding agents need to run commands, modify files, and run tests in an isolated environment. A sandbox must meet three requirements: isolation, reproducibility, and controllable resource limits. The following illustrative task configuration shows how environment constraints can be made explicit:
task = {"id": "fix-build-001","goal": "Fix the dependency version conflict in the build script so that all unit tests pass","environment": {"workdir": "/workspace/project","timeout_seconds": 1800,"cpu_cores": 2,"memory_mb": 4096,"network": "disabled",},"checks": [{"type": "command_exit_code", "cmd": "run_tests", "expect": 0, "critical": True},{"type": "file_unchanged", "path": "tests/", "critical": True},{"type": "file_exists", "path": "build/report.txt", "critical": False},],}
Network access is disabled by default. This prevents agents from “cheating” by using external resources, and it keeps results comparable across repeated runs of the same task.
2.4 Scheduling and Resource Isolation
Large-scale training runs hundreds of tasks from different downstream domains at the same time, so resource contention is intense. The scheduler must account for priority, quotas, fault recovery, and data locality together. One practical principle is to schedule reproducible environment builds separately from the actual training tasks. Environment images are built ahead of time and cached, and training tasks only launch and run them. This reduces cold-start overhead and makes problems easier to locate.
2.5 Environment Quality Checks
The environment itself can be flawed. Incorrectly written test cases, unstable dependency sources, and unfixed random seeds can all distort the reward signal. Before training, the environment should therefore be checked, including:
- Running a reference solution to confirm that the task can actually be passed.
- Running each task several times and removing tasks with unstable results (high-variance tasks).
- Checking for exploitable shortcuts, such as directly modifying test files so they always pass.
This step looks tedious, but it directly determines the quality of the RL signal.
3. Evaluation Design: Measuring Coding Agents
The goal of evaluation is to answer a specific question: under conditions close to real work, can the model reliably complete tasks? The sections below cover evaluation structure, scoring rules, and how to interpret results.
3.1 Evaluation Structure for Terminal Tasks
The advantage of terminal tasks is that results can be judged by a machine. Each task includes a goal description, environment constraints, and a set of checks. The checks should cover both functional correctness and control of side effects. For example, the agent should be required both to pass the tests and to avoid modifying unrelated files.
3.2 Scoring Rules
Scoring by the simple count of passed checks can hide critical failures. For example, an agent may fix eight features but break one security-related check, and its average score would still be high. A better approach is to treat critical checks as gating conditions:
def score_episode(results):"""results: A list of check result dictionaries, each containing the passed and critical fields."""if not results:return 0.0if any(r["critical"] and not r["passed"] for r in results):return 0.0passed = sum(1 for r in results if r["passed"])return passed / len(results)
Gated scoring makes evaluation results more conservative, but it is closer to the reliability requirements of real-world use.
3.3 Recording Multi-Step Execution and Tool Calls
Evaluation should record process metrics as well as the final result. These include the number of steps, the number of tool calls, the number of error retries, and whether each call’s parameters were valid. These metrics help distinguish two kinds of problems: insufficient capability and redundant strategy. For example, a model may reach the correct result after many unnecessary steps. This is also a problem in cost-sensitive settings.
3.4 End-to-End Problem Solving
End-to-end tasks require completing everything from understanding requirements to delivering results. During evaluation, avoid giving excessive hints. Otherwise, the measurement reflects the ability to use hints rather than the ability to solve problems independently. Also, run each task multiple times and report the average and the range of variation, not only the best single result.
4. Interpreting Evaluation Results
4.1 Internal and Public Benchmarks
Internal benchmarks can be designed around business scenarios, but they may overlap with training data. Public benchmarks make cross-model comparison easier, but they carry the risk of targeted optimization. When comparing results, state the test conditions, including sampling temperature, maximum steps, the tool set, and the number of repetitions.
4.2 Reporting Uncertainty
Agent tasks are highly random, and the variance of a single run can be large. A sound way to report results is to give the mean and standard deviation across multiple runs, or confidence intervals. If the gap between two versions is smaller than the range of variation, neither version should be declared stronger.
4.3 Checking the Context Behind Numbers
Statements such as “close to a certain closed-source model” or “higher than the previous version” are meaningful only when the test conditions match. Before drawing conclusions, confirm three things: whether the evaluation set is the same, whether the scoring rules are the same, and whether the number of runs is the same.
5. Trade-offs Between Inference Speed and Quality
Offering several inference tiers for the same model is a common product design. Faster tiers typically gain throughput through higher concurrency, more aggressive batching, or lower scheduling overhead. A claim such as “same capability, faster” must be verified with the same evaluation suite. In deployment, test each tier separately for task success rate, latency distribution, and cost. This confirms that the speed gain does not come at the cost of hidden quality loss.
6. Deployment Checklist
Before putting a long-horizon agent into real use, check each item in the following list:
- Is the task environment reproducible, with clearly defined network and resource limits?
- Are critical checks set as gates, and are there any exploitable shortcuts?
- Is evaluation run multiple times, with variation ranges reported?
- In long-context scenarios, are memory usage and latency within acceptable ranges?
- Have speed optimizations passed regression tests for quality consistency?
These items may seem minor, but they prevent most cases where metrics look good yet the system is unusable in practice.
