Engineering Practices for Long-Horizon AI Agents Based on Post-Training Scaling

    As large language model applications shift from single-turn Q&A to continuous task completion via AI agents, post-training scaling, particularly reinforcement learning (RL), has become crucial. This article explores engineering practices for building long-horizon agents, covering reward design, environment construction, scalable training infrastructure, evaluation methodologies, inference cost optimization, and deployment architectures. It provides actionable recommendations for teams looking to build, evaluate, and scale agent systems in real-world environments.

    1. Background: From Answering Questions to Continuous Task Completion

    Early large language model applications primarily focused on single-turn Q&A. A user asks a question, the model generates text, and the interaction ends. With the maturation of tool calling, code execution, and multi-step planning capabilities, application paradigms have shifted toward AI agents. Agents need to read files, run commands, check results, correct errors, and advance a goal over hours or even days.

    This transformation imposes new requirements on models. Models must maintain goal consistency in long contexts, correctly call tools, recover from failures, and complete tasks in resource-constrained environments. Simply scaling up pre-training is no longer sufficient to meet all these requirements simultaneously. Consequently, the industry is placing greater emphasis on the post-training phase, including supervised fine-tuning (SFT) and reinforcement learning (RL), to shape model behaviors.

    For engineering teams, the key question is how to invest post-training compute into environments where the model can genuinely work continuously, rather than just polishing static Q&A data.

    2. Why Post-Training Compute Has Become a Key Variable

    Pre-training learns general language patterns from massive text. Post-training uses more targeted data and feedback signals to teach the model decision-making processes for specific tasks. When the marginal returns of pre-training diminish, the return on investment (ROI) of post-training is often higher.

    Reinforcement learning plays a core role in this phase. Its basic workflow is as follows:

    1. The model generates an action sequence within an environment;
    2. The environment provides a reward based on the outcome, such as whether tests pass or goals are achieved;
    3. The training algorithm updates model parameters based on the reward;
    4. Repeat the process above to cover more tasks and domains.

    To scale this workflow to hundreds of downstream domains, teams must solve three types of problems: whether reward signals are reliable, whether environments are diverse and reproducible, and whether training throughput is sufficient.

    3. Engineering Challenges in Multi-Domain Reinforcement Learning

    3.1 Reward Design

    Verifiable rewards are the most stable type of signal. Code tasks can be judged by unit tests, math problems by comparing against standard answers, and structured data extraction by field matching. These rewards are objective but have limited coverage.

    For open-ended tasks, such as writing analytical reports or designing 3D models, rewards often require a combination of rule checks, reference answer comparisons, and model reviews. Reviewer models themselves can have biases, so it is necessary to periodically sample for manual verification and monitor whether the score distribution drifts.

    3.2 Environment Construction

    Training environments should closely mimic real working conditions. A usable environment typically includes the following elements:

    • Initial state: File structure, dependency versions, data snapshots;
    • Available tools: Command line, browser, calculator, specialized software APIs;
    • Resource limits: Runtime, memory, disk, and network quotas;
    • Termination conditions: Goal achieved, timeout, or consecutive failures.

    Below is a simplified environment description example illustrating the structure of the configuration:

    1. task_env = {
    2. "task_id": "repo-fix-0412",
    3. "image": "python-3.11-slim",
    4. "setup": ["pip install -r requirements.txt"],
    5. "workspace": "/data/snapshots/repo-fix-0412",
    6. "tools": ["shell", "file_editor", "test_runner"],
    7. "limits": {"cpu": 2, "memory_gb": 4, "timeout_s": 900},
    8. "reward": {"type": "unit_test", "suite": "tests/regression"},
    9. }

    This structured description facilitates batch environment generation and makes it easier to audit whether environments have issues like answer leakage or incomplete tests.

    4. Infrastructure Supporting Large-Scale Joint Training

    4.1 Decoupling Training and Sampling

    RL training is typically divided into two parts: sampling, which generates trajectories, and training, which updates parameters. Sampling is sensitive to latency and throughput, while training is sensitive to memory and communication. By decoupling them, both can be scaled independently, preventing one from idling while the other queues.

    A common practice is to set up independent sampling clusters and training clusters, passing trajectory data through asynchronous queues. Stale data is either importance-weighted or discarded directly to control training instability caused by policy drift.

    4.2 Long-Context Inference Optimization

    The context of agent tasks grows with each step. If the full context is recalculated at every step, costs escalate rapidly. Common optimization techniques include:

    • KV cache reuse: Preserve the key-value states of preceding steps and only compute the new portions;
    • Chunked prefill: Split ultra-long inputs to reduce peak memory usage per computation;
    • Context compression: Summarize or truncate tool outputs to retain key information;
    • Prefix sharing: Multiple parallel trajectories share the same system prompts and history.

    These methods must remain consistent on both the training and inference sides; otherwise, inconsistencies will arise between training-time and deployment-time behavior.

    4.3 Sandbox Isolation

    Agents execute arbitrary commands, making sandboxing the foundation of security and stability. Sandbox design should meet the following requirements:

    • Process and filesystem isolation to prevent affecting the host machine;
    • Network whitelisting to allow access only to necessary dependency sources;
    • Resource quotas to prevent a single task from exhausting cluster resources;
    • Fast reset to allow clean environment recovery between tasks.

    Sandbox startup speed directly impacts training efficiency. Teams typically pre-build base images and cache dependencies to compress startup time to an acceptable range.

    4.4 Scheduling System

    Large-scale training simultaneously runs tens of thousands of tasks with highly variable durations—some finishing in seconds, others taking hours. The scheduling system needs to handle the following issues:

    • Priority: Ensure critical training tasks receive resources;
    • Preemption and recovery: Pause low-priority tasks during resource constraints and recover from checkpoints;
    • Heterogeneous resources: Assign different specifications of compute nodes based on task type;
    • Fairness: Prevent any single data domain from monopolizing the cluster long-term.

    4.5 Environment Quality Checks

    Environment quality directly determines the reliability of training signals. If test cases are too lenient, models may learn opportunistic behaviors rather than actually solving problems. Therefore, environments usually undergo automated checks before going live, including:

    • Deduplication: Detecting tasks highly similar to existing environments;
    • Solvability verification: Using reference solutions to confirm the task can actually be completed;
    • Reward leakage detection: Checking if standard answers are exposed in the environment;
    • Opportunistic behavior identification: Monitoring if models gain rewards by modifying tests, deleting assertions, etc.

    5. Evaluation: How to Measure Long-Horizon Coding and Agent Capabilities

    5.1 Design Principles for Evaluation Tasks

    Good evaluation tasks should be realistic, constrained, and reproducible. “Realistic” means tasks come from actual work scenarios; “constrained” means models must complete tasks under time, tool, and resource limitations; “reproducible” means the same task yields consistent results when run at different times.

    5.2 Limitations of Single Metrics

    Many teams focus only on a single leaderboard score. This approach has two problems. First, imbalance: a model might perform outstandingly on one benchmark but lag significantly on other types of tasks. Second, benchmark overfitting: when training data heavily overlaps with evaluation data, scores appear artificially inflated.

    A more robust approach is to establish a multi-dimensional evaluation matrix covering different languages, task lengths, and domains, and to separately report pass rates, average step counts, and failure reason distributions.

    5.3 The Problem of Verbose Outputs

    Agents tend to produce verbose intermediate outputs during long tasks. This increases context length, slows inference, and obscures critical information. During evaluation, the following metrics can be recorded simultaneously:

    • Useful step ratio: The proportion of steps that drive task progress to total steps;
    • Cost per success: The average tokens and time consumed per successful task;
    • Repeat operation rate: The frequency at which the same command or file is repeatedly modified.

    Below is a simplified evaluation summary example:

    1. def summarize(results):
    2. total = len(results)
    3. passed = [r for r in results if r["passed"]]
    4. pass_rate = len(passed) / total
    5. cost_per_success = (
    6. sum(r["tokens"] for r in results) / max(len(passed), 1)
    7. )
    8. useful_ratio = sum(r["useful_steps"] for r in results) / sum(
    9. r["total_steps"] for r in results
    10. )
    11. return {
    12. "pass_rate": round(pass_rate, 3),
    13. "cost_per_success": round(cost_per_success),
    14. "useful_step_ratio": round(useful_ratio, 3),
    15. }

    These metrics collectively describe the model’s capability boundaries and efficiency; looking solely at the pass rate fails to reflect the full picture.

    6. Inference Speed Tiers and Cost Considerations

    The same model often provides multiple service tiers. Standard tiers focus on cost, while high-speed tiers prioritize response time. They may have identical model capabilities, with differences primarily stemming from how inference resources are allocated.

    When selecting a service tier, consider the following dimensions:

    • First token latency: Interactive scenarios are most sensitive to this metric;
    • Output throughput: Batch generation and long-document scenarios prioritize this metric;
    • Cache hit rate: When agents repeatedly use the same prefix, caching can significantly reduce input costs;
    • Cost per unit task: Comprehensively calculates input, output, and retry overhead.

    Cost estimation should be based on real traffic. Teams can first replay historical tasks to calculate average input length, output length, and cache hit rate, then plug these into different tier pricing models to compare the trade-off between total cost and response time.

    7. Hosting Models for Long-Running Agents

    When tasks need to run for hours or continuously, agents require external runtime support. Common hosting architectures include the following components:

    • State storage: Persists task progress, context summaries, and tool call records;
    • Checkpoint mechanism: Periodically saves state for recovery after failures;
    • Watchdog: Monitors task heartbeats and automatically restarts if a task stalls;
    • Coordinator: Assigns subtasks and aggregates results from multiple agents;
    • Quota and audit: Records resource consumption and critical operations for traceability.

    During multi-agent collaboration, the coordinator must prevent two agents from modifying the same resource simultaneously. A common practice is to set locks or version numbers for each resource and check for conflicts before committing.

    Below is a simplified diagram of a task state machine:

    1. from enum import Enum
    2. class TaskState(Enum):
    3. PENDING = "pending"
    4. RUNNING = "running"
    5. CHECKPOINTED = "checkpointed"
    6. FAILED = "failed"
    7. DONE = "done"
    8. TRANSITIONS = {
    9. TaskState.PENDING: {TaskState.RUNNING},
    10. TaskState.RUNNING: {TaskState.CHECKPOINTED, TaskState.FAILED, TaskState.DONE},
    11. TaskState.CHECKPOINTED: {TaskState.RUNNING, TaskState.FAILED},
    12. TaskState.FAILED: {TaskState.PENDING},
    13. TaskState.DONE: set(),
    14. }
    15. def advance(current, target):
    16. if target not in TRANSITIONS[current]:
    17. raise ValueError(f"illegal transition: {current.value} -> {target.value}")
    18. return target

    The state machine explicitly lists valid transitions, preventing tasks from entering inconsistent states under abnormal conditions.

    8. Implementation Recommendations

    When introducing long-horizon agents or evaluating related model capabilities, teams can follow this sequence:

    1. Define business scenarios: List specific tasks the agent needs to complete and define success criteria;
    2. Build evaluation sets: Cover normal tasks, edge cases, and failure scenarios, and update regularly;
    3. Design sandboxes and permissions: Configure tools and network access based on the principle of least privilege;
    4. Establish a cost model: Use real task replays to estimate total costs across different service tiers;
    5. Deploy monitoring: Track pass rates, useful step ratios, abnormal termination rates, and cost variations;
    6. Iterate environments: Add tasks based on failure cases and correct overly lenient tests.

    Overall, improvements in model capabilities must advance in tandem with infrastructure, evaluation systems, and operating costs. Improving a single-point metric is insufficient to prove system viability. Only by consistently completing tasks under real workloads can a solution be considered truly reliable.