Post-Training and Engineering Practices for Long-Horizon AI Agents
This article examines why long-horizon agentic tasks have become a key evaluation focus for large language models, and details the engineering challenges and practical solutions involved in post-training such models. It covers infrastructure bottlenecks in reinforcement learning, reward design for verifiable outcomes, long-context inference optimization, building reproducible evaluation pipelines, and practical advice for code and interaction tasks. The content is aimed at engineers and researchers working on training and deploying capable, stable AI agents.
Why Long-Horizon Agentic Tasks Became the Evaluation Focus
Early code generation models were often evaluated on completing functions, explaining snippets, or answering single-turn questions. Real engineering work is different. Developers must locate bugs in a real repository, read across multiple modules, modify configuration, run tests, and iteratively adjust based on failure messages. Such tasks typically involve dozens of steps, and any single mistake can invalidate the final result. As a result, the evaluation focus has shifted from “whether a single output is correct” to “whether multi-step execution is stable, whether tools are invoked correctly, and whether the end-to-end goal is achieved under constraints.”
Long-horizon capability can be decomposed into three observable sub-capabilities. First, planning: breaking a goal into executable sub-tasks and maintaining execution order. Second, tool use: selecting the right command, parsing returned results, and handling exceptions. Third, state management: remembering completed steps, verified assumptions, and open questions throughout a long context. Weakness in any of these becomes amplified in a long chain.
Engineering Problems from Increased Post-Training Compute
After the base model is pre-trained, the post-training stage adapts it to specific task formats through supervised fine-tuning and reinforcement learning. When post-training compute increases significantly and must cover many downstream domains, the bottleneck is usually not the algorithm itself, but the infrastructure.
The problem can be understood across several layers of the technical stack:
- Reinforcement learning framework: needs to support large-scale asynchronous sampling, decoupled reward computation, and gradient synchronization. Otherwise, sampling or evaluation can drag down GPU utilization.
- Long-context inference: the key-value cache during sampling grows with context length. Page management, batching, and prefix reuse are needed to control memory and latency.
- Training efficiency: mixed precision, parallelism strategies, and checkpointing jointly determine how many effective samples a unit of compute produces.
- Sandbox infrastructure: agent training relies on isolated execution environments. The environment must reset quickly, have clear resource limits, and produce reproducible outputs.
- Scheduling system: task runtimes vary widely across domains. Scheduling must allocate by priority and resource requirements to avoid long tasks blocking the queue.
- Environment quality checks: training environments themselves may have defects—incorrect test cases, missing dependencies, or broken scoring scripts. A shared quality check mechanism can catch these before large-scale training.
The common goal of all these components is to convert every additional unit of compute into stable capability improvement, rather than amplifying training noise.
Reward Design in Reinforcement Learning
In code and agent tasks, rewards usually come from verifiable results—whether tests pass, file states match expectations, or command outputs satisfy assertions. Verifiable rewards provide clear signals, but their coverage is limited: they cannot easily capture code style, design rationale, or other subjective dimensions.
Several points should be kept in mind when designing rewards:
- Rewards must align with the final goal. If you reward “ran the test” without checking whether the test passed, the model will learn to game the count instead of fixing the bug.
- Avoid exploitable shortcuts. If the scoring script only checks whether a file exists, the model may generate an empty file and score points. The scoring logic should check behavior outcomes, not surface attributes.
- Use process rewards cautiously. For long-horizon tasks, you can add reward for intermediate steps, but their weight needs to be controlled. Otherwise the model optimizes intermediate metrics and neglects the final completion rate.
- Periodically review samples manually. Sampling-based review reveals discrepancies between reward scores and true quality, allowing scoring rules to be corrected in time.
Practical Points for Long-Context Inference
Long-context capability is valuable in agent scenarios. A complete codebase, runtime logs, and historical operation records can stay in the same session, reducing information loss. However, longer contexts increase inference cost and attention dilution.
Common engineering practices include:
- On-demand truncation: put only the files and logs relevant to the current step into the context, reducing irrelevant noise.
- Structured summarization: generate short status records for completed steps, preserving key decisions and unresolved issues.
- Chunked retrieval: build an index for very large codebases, first locate relevant files, then insert the corresponding snippets into the context.
- Length monitoring: record input and output lengths for each request, set alert thresholds, and avoid a single overly long task dragging down overall latency.
Note that the upper limit of the context window does not equal effective usable range. Beyond a certain length, the model’s utilization of earlier information may degrade noticeably. Therefore, evaluation should measure accuracy as a function of different context lengths, rather than only looking at the maximum window size.
Building a Reproducible Evaluation System
The most important thing to avoid when evaluating agent capabilities is non-reproducibility. A reliable evaluation pipeline usually includes:
- Task set: covering typical scenarios such as bug fixing, feature development, configuration changes, and test writing.
- Fixed environment: image versions, dependency packages, random seeds, and timeout settings must all be recorded.
- Scoring criteria: use test pass rates or state checks as the primary metric, and distinguish fully successful, partially completed, and failed outcomes.
- Failure attribution: categorize failures into planning, tool call, environment, and reasoning errors, so improvements can be targeted.
- Multiple sampling: run the same task multiple times and report the mean and variance, rather than relying on a single run.
Below is an illustrative evaluation loop to show the overall structure. The model calls and environment interfaces are placeholders; replace them with your own wrappers in actual use.
from dataclasses import dataclass@dataclassclass TaskResult:task_id: strpassed: boolfailure_type: str | None # planning / tool / env / reasoningdef run_episode(model, sandbox, task, max_steps=40):sandbox.reset(task.image, task.setup) # Reset environment before each runhistory = [task.prompt]for _ in range(max_steps): # Set a step limitaction = model.next_action(history)if action.type == "finish":breakobservation = sandbox.execute(action.command, timeout=60)history.append(observation)passed = task.check(sandbox) # Use state check as the pass criterionfailure = None if passed else classify_failure(history)return TaskResult(task.id, passed, failure)def evaluate(model, sandbox, tasks, repeats=3):results = []for task in tasks:for _ in range(repeats): # Multiple samplingresults.append(run_episode(model, sandbox, task))pass_rate = sum(r.passed for r in results) / len(results)return pass_rate, results
This structure emphasizes three things: resetting the environment before each run, setting step and timeout limits, and sampling the same task multiple times. The classify_failure function needs to be implemented with log rules or manual annotation. It is the most easily overlooked part of evaluation, yet it directly determines whether the improvement direction is accurate.
Practical Advice for Code and Interaction Tasks
For code generation, functional correctness is only the baseline; maintainability matters equally. Generated code should follow the project’s existing naming, directory structure, and testing conventions. If no explicit team convention exists, use the common format checkers of the corresponding language community, and require each change to come with corresponding tests.
For visually oriented tasks such as games and web pages, evaluation
