How Post-Training Reinforcement Learning Powers Long-Horizon AI Agents
Over the past few years, the gains in large-model capability have shifted away from scaling pre-training toward post-training, especially reinforcement learning (RL). This article explains why that shift is happening and what it takes to operationalize it: how to extend RL to hundreds of domains when there is no ready-made judge program, the infrastructure needed for large-scale joint training (decoupled RL frameworks, trustworthy and reproducible sandboxes, long-context inference, and scheduling), how to evaluate long-horizon agent behavior rather than single-turn answers, when to choose a standard versus a high-speed model variant, how token-based pricing amplifies costs in agent scenarios, and how to treat the agent Harness as production infrastructure. It closes with a step-by-step path for developers and enterprise teams to bring these systems into production.
Introduction: The Center of Gravity Is Shifting from Pre-Training to Post-Training
For the past few years, gains in large-model capability came mostly from scaling parameter and data volume during pre-training. But that path is showing diminishing returns: high-quality corpus growth is clearly lagging behind compute investment, and pure next-token prediction struggles to directly optimize goals like “was the task actually completed.”
As a result, a common industry trend is to pour more compute into the post-training stage, especially reinforcement learning. The reasoning is straightforward: pre-training optimizes “fitting the text distribution,” whereas reinforcement learning can directly optimize a terminal metric such as “task completion rate.” When a model has to run commands in a terminal, fix errors across multiple rounds of tool calls, and keep a consistent goal over a long-horizon task, the density and quality of feedback signals matter more than raw corpus size.
The capability upgrades in a new generation of model families generally follow this logic: parameter counts stay at the trillions scale, but post-training compute rises significantly, and the coverage of reinforcement learning expands from a few tasks that are easy to verify automatically (math, code) to hundreds of downstream domains. This article walks through that route, covering its technical substance, infrastructure dependencies, and engineering priorities for deployment.
1. Scaling Reinforcement Learning to Hundreds of Domains: What Makes It Hard
The classic dilemma of reinforcement learning is: where does the reward come from? In board games, win/loss is a naturally sparse reward; for math and code problems, answer comparison and unit tests are likewise naturally verifiable. But when you expand into domains like financial research, 3D content creation, or cross-system operations troubleshooting, there is no longer a ready-made referee program for judging “how well it was done.”
In practice, teams usually adopt a layered strategy:
- Prioritize tasks that can be verified automatically. Any scenario where you can write a deterministic checker should be reshaped into verifiable rewards: it has inputs, outputs, and an executable validation script. Code fixes, data-pipeline construction, structured report generation, and configuration-correctness checks all fall into this category.
- For tasks that cannot be verified automatically, build a composite score that combines rules and models. The rule-based part handles hard constraints (format compliance, field completeness, prohibited items), while the model-based part handles soft quality (whether the argument is on topic, whether conclusions are grounded).
- Validate the quality of the environment itself. This is the most easily overlooked part. If a sandbox image is corrupted, dependencies are missing, or the test script itself has a bug, the model gets penalized for “failing a task it could have completed,” and the training signal becomes noise.
A typical environment-quality-check platform is responsible for: pre-validating task solvability (run the task a few times with a strong model; if the pass rate is extremely low, the task itself is probably flawed), verifying the correctness of test scripts, checking consistency of dependency images, and detecting dataset contamination (so the evaluation set does not leak into the training set and inflate metrics). This platform can consume a considerable amount of compute, but it sets the upper bound on the signal-to-noise ratio of reinforcement learning.
2. Infrastructure for Large-Scale Joint Training
When reinforcement learning covers hundreds of domains, each requiring its own sandbox environment, the infrastructure quickly becomes the bottleneck. Several areas usually need systematic reengineering.
2.1 The RL Framework: Decoupling Inference from Training
Reinforcement learning training is a loop of “generate — score — update.” The generation stage (rollout) needs a full inference engine, while the update stage needs a training engine. Running these serially in a naive way leaves GPUs largely idle. Key designs in mature frameworks include:
- The compute ratio between the inference side and the training side is adjustable, allowing the two to be co-located or deployed separately;
- Weight synchronization uses efficient broadcast or shard transfer, avoiding a full weight copy at every training step;
- Support for partial trajectory reuse: when weights have already updated mid-way through a long-horizon task, keep the completed prefix instead of discarding everything and rerunning;
- Truncation and credit assignment for very long trajectories, so that a delayed reward does not end up too far away and kill the gradient.
A simplified asynchronous rollout loop looks roughly like this:
async def rl_step(policy, task_queue, reward_fn, max_steps=200):pending = [policy.rollout(t) for t in task_queue]while pending:done, pending = await wait_any(pending)for traj in done:traj.reward = reward_fn(traj) # Environment-side scoringif not traj.finished and traj.steps < max_steps:pending.append(policy.continue_from(traj)) # Partial continuationpolicy.update(reward_normalize(done)) # Async update on the training side
2.2 Sandbox Infrastructure: Making Every Execution Trustworthy and Reproducible
An agent training environment is essentially a “resettable, single-use computer.” The core requirements:
- Strong isolation: file-system, process, and network isolation are all mandatory; running arbitrary code must not affect the host or neighboring tasks;
- Minimal networking: deny outbound access by default, allow by task-specific whitelist, and avoid reaching uncontrollable external resources during training;
- Snapshot and rollback: restore from a fixed image at the start of each task and destroy it at the end, preventing residual state from biasing rewards;
- Observability: fully record commands, stdout/stderr, exit codes, and resource consumption as the basis for reward decisions and post-hoc attribution.
An example structure for a task definition (YAML):
task_id: data_pipeline_fix_014image: sandbox/runtime-py310:2026-08network_policy: deny_alltimeout_seconds: 900initial_state: repo@commit:9f2c1a # Fixed baseline to ensure reproducibilityverification:- cmd: "pytest -q tests/pipeline" # All tests must passexpect_exit: 0- cmd: "python scripts/check_schema.py"expect_exit: 0reward:type: verifiableweights: { tests_pass: 0.8, lint_clean: 0.1, minimal_diff: 0.1 }
2.3 Long-Context Inference: The Main Source of Cost
There is no doubt about the value of million-token context windows: an entire codebase, a full earnings report, or a complete set of 3D scene descriptions can enter the model’s view at once. But the cost of long context is concentrated in the KV cache: memory usage grows linearly with sequence length, and time-to-first-token rises accordingly. Common optimizations include paged cache management, prefix reuse (the same system prompt and codebase prefix are computed only once), on-demand compression with sliding-window eviction, and turning very long documents into retrievable, load-on-demand content rather than injecting everything at once.
Engineering advice: don’t stuff everything into the context by default. Retrieval-based on-demand loading is cheaper in most scenarios than a “full long-context” approach, and it is also easier to pinpoint problems.
2.4 Training Efficiency and Scheduling
Joint training across hundreds of domains means highly heterogeneous task shapes: some are second-level code executions, while others require tens of minutes of long-horizon reasoning. The scheduler needs to support priorities, preemption and re-entry, heterogeneous resource pools (different memory and compute ratios), and task-level failure retries with timeout isolation. It also needs to establish isolated quotas for three load types — “training / evaluation / environment construction” — so that evaluation tasks do not preempt training resources and cause scheduling jitter.
3. How to Evaluate Long-Horizon Agent Capabilities
Traditional evaluation measures correctness on single-turn Q&A, but agent capability must be measured in long-horizon, multi-step, real environments with side effects. Publicly reported terminal-agent evaluations have converged on a common paradigm: give the model a complex task inside a resource-constrained real terminal, let it decompose, execute, and verify on its own, and finally judge the result with test scripts. The pass rates of leading models on these evaluations currently cluster roughly in the sixty-to-seventy percent range, with gaps between them often in the single-digit percentage points.
When reading these metrics, it’s better to look at four dimensions rather than a single score:
- Pass rate (pass@1 and pass@k): pass@1 reflects the real experience, while pass@k reflects the capability ceiling;
- Cost-normalized pass rate: the total tokens and sandbox time spent completing the same task can differ by several times, so comparing scores alone hides the economics;
- Error recovery rate: whether the model can self-diagnose and retry when it hits build failures, dependency conflicts, or failing tests is the dividing line of long-horizon capability;
- Wasted-loop rate: the proportion of repeated failed actions or repeated tweaks to the same line of code directly reflects the “long-winded but not progressing” problem.
For your own business scenarios, a more reliable approach is to build an internal domain evaluation set: sample 100–300 tasks from real tickets, real data, and real codebases, freeze the environment and judging scripts, and form a sustainable regression baseline. Public leaderboards are only good for initial screening, not for selection decisions.
4. Choosing Between the “Standard” and “High-Speed” Variants of the Same Model
Leading vendors typically ship two delivery forms from the same model: one that pursues the strongest intelligence, and one that raises output speed to roughly 2–3x at the same capability level. These high-speed versions are usually not newly trained models, but are produced by trading compute redundancy for lower latency through speculative decoding, more aggressive parallelism and batching strategies, and better quantization and kernel implementations.
Selection principles:
- Prioritize the high-speed version for interactive scenarios: IDE completion, conversational Q&A, code explanation — here users perceive time-to-first-token and per-token speed, and doubling speed often improves the experience more than a slight capability drop hurts it;
- Prioritize the standard version for high-value, one-shot tasks: financial research conclusions, complex refactoring, cross-repository changes — where the cost per task is acceptable and quality comes first;
- Hybrid routing: split traffic by task type at the gateway layer, sending simple requests to a high-throughput path and complex requests to a high-quality path. This is currently the best cost-performance architecture.
5. How Token-Based Pricing Amplifies Costs in Agent Scenarios
The pricing structure of mainstream APIs usually has three tiers: cached input, uncached input, and output. The price gaps among them can be large — cached input is often only a small fraction of uncached input, while output is typically several times the input price. This structure has a huge impact on agent scenarios, because the defining characteristic of an agent is that input is far larger than output: every round re-submits the system prompt, tool definitions, history trajectory, and file contents, while the actual output is often just a few hundred tokens of actions.
A cost-governance checklist:
- Stable prefixes: put the system prompt, tool definitions, and long documents at the very front of the prompt and keep them byte-for-byte stable, to maximize cache hit rate;
- Avoid meaningless timestamps or random IDs that break the prefix: a common mistake is inserting the current time at the start of the prompt, which invalidates caching of the entire prefix;
- Trajectory compression and summarization: in long-horizon tasks, periodically produce a structured summary of the history, keeping only decisions and results and discarding verbose intermediate output;
- Tool output trimming: file-read and log-query tools should support range limits and key-line extraction, and unlimited returns should be prohibited;
- Timeout and budget circuit breakers: set token and time limits per task, and terminate on breach while emitting diagnostic information, to avoid wasted loops that keep burning money;
- The boundary between self-hosted and managed: stable inference workloads can run on your own compute, while elastic peaks and long-horizon managed tasks are better suited to general-purpose cloud capabilities.
6. Treating the Harness as Infrastructure: Managed Agent Services
A direction worth watching is that vendors are beginning to offer the Harness that supports long-running agents as a managed service, so enterprises can run 7×24 long-horizon tasks without building it themselves, and support multi-agent collaboration.
The Harness refers to the entire “execution shell” outside the model, which determines how much of the model’s capability can actually be realized. A production-grade Harness includes at least:
- Tool-invocation layer: unified tool registration, parameter validation, permission tiering, and audit logging;
- Context-management layer: automatic compression, retrieval backfill, and cross-session memory;
- State-persistence layer: task state, intermediate artifacts, and checkpoint positions must be written to disk so the process can resume from a checkpoint after a crash;
- Error-recovery layer: distinguishing retryable errors from terminal ones, and implementing exponential backoff and fallback paths;
- Multi-agent orchestration layer: task decomposition, role assignment, result aggregation, and conflict resolution;
- Observability layer: end-to-end tracing, token and cost accounting, and anomaly alerting.
In multi-agent collaboration, two failure modes deserve special caution: first, context contamination, where one agent’s erroneous conclusion gets treated as fact by downstream agents and keeps propagating; second, diffuse responsibility, where each agent thinks it has completed its local goal while the overall task fails. Mitigation approaches include setting up a dedicated verification agent (responsible only for checking, not producing), placing human or rule-based gating at key checkpoints, and requiring every handoff to carry an explicit list of assumptions and evidence references.
7. A Practical Path for Implementation
For developers and enterprise teams, the recommended sequence is:
- Define the scenario and the judging criteria. Write a clear, executable definition of “task success” before choosing a model. Scenarios without a judging script are not suitable for directly entering an automated pipeline.
- Build the sandbox and evaluation environment. A containerized isolated runtime, a fixed baseline image, and reproducible verification scripts are the foundation for all subsequent work.
- Run small-scale parallel validation. Run 2–3 candidate models on the same evaluation set, and record four metrics: pass rate, total tokens, sandbox time, and number of human interventions.
- Connect to general-purpose cloud capabilities. Elastic compute can host the sandbox pool via a container platform; intermediate artifacts and trajectory data can be written to object storage; the execution chain can be made traceable with logging services and monitoring/alerting; asynchronous long tasks can be decoupled with message queues; and a call gateway can handle routing, rate limiting, and cost accounting in one place. Baidu AI Cloud offers corresponding capabilities in each of these general categories, and enterprises can combine and select them according to business scale.
- Set up a dual dashboard for cost and quality. Only by putting each task’s cost, success rate, and human-intervention rate in the same view can you uncover the hidden losses of “it runs, but it isn’t worth it.”
- Watch open weights and data boundaries. When a vendor promises to open complete model weights, enterprises gain the option of private deployment and deep fine-tuning, but they must also assess compute costs, security and compliance, and version-maintenance burden in parallel.
Conclusion
The substance of this round of capability upgrades is not a leap in parameter scale, but a shift in training methodology: from “feeding more text” to “practicing repeatedly in verifiable environments.” This means the key judgment in technology selection changes accordingly — no longer looking only at a single-point score, but at whether the model, execution environment, cost structure, and observability system can form a sustainably running whole. Getting these four things solid — the evaluation set, the sandbox, the Harness, and the cost dashboard — brings more reliable engineering returns than chasing any single leaderboard.
