Scaling Post-Training: Long-Context and Agent Engineering in Practice

    This article covers the engineering work behind scaling post-training for large language models. It describes four key infrastructure layers: reinforcement learning training frameworks, long-context inference, sandbox environments, and scheduling with environment quality checks. It also explains how to evaluate long-horizon agents using intermediate metrics, and it offers practical advice on reproducibility and common pitfalls.

    1. Background: Why Post-Training Scaling Has Become Critical

    Pretraining determines a model’s knowledge base, while post-training determines how the model acts on specific tasks. As compute investment grows, the post-training stage has become much more important. There are three main reasons.

    First, downstream tasks now cover a wider range. Code, data analysis, financial research, and 3D content generation each have their own toolchains and output formats, and a single data mix struggles to serve all of them.

    Second, tasks have become longer. Early models mainly handled single-turn question answering. Today’s agents must plan continuously, call tools, read feedback, and revise their plans. A single task may involve dozens or even hundreds of steps. Errors accumulate across steps, so per-step accuracy does not reflect overall success rate.

    Third, reinforcement learning gains depend on engineering quality. With the same compute, low training throughput, unstable environments, or noisy reward signals can significantly reduce the actual gains. Post-training scaling is therefore fundamentally a systems engineering problem.

    2. Four Key Layers of Post-Training Infrastructure

    2.1 Reinforcement Learning Training Frameworks

    Reinforcement learning training typically involves three roles. The policy model generates actions, the value or reward module scores them, and the sampling system interacts with the environment to produce trajectories. The framework design must address the following issues:

    • Switching between generation and training resources. Inference-style sampling and gradient updates place different demands on memory and compute. A common approach is to decouple the two and pass trajectory data through asynchronous queues, so the training side does not wait for the sampling side.
    • Policy version consistency. If the policy parameters used for sampling lag too far behind the training side, bias is introduced. Each trajectory should record its policy version number, and a maximum staleness threshold should be set.
    • Reward signal design. For code tasks, the unit test pass rate can serve as a verifiable reward. For open-ended tasks, rule-based checks can be combined with a human-calibrated scoring model. Rewards should be as verifiable as possible to limit the model’s ability to exploit scoring loopholes.

    2.2 Long-Context Inference

    Long contexts create both memory pressure and latency problems. Attention computation cost grows with sequence length, and the memory used by the key-value (KV) cache also grows linearly. On both the training and inference sides, common engineering methods include:

    • Chunked prefill, which splits very long inputs into segments to reduce peak memory per computation;
    • KV cache quantization and paged management, which reduce cache fragmentation and improve utilization under concurrent requests;
    • Prefix caching, which reuses already computed cache when multiple requests share the same system prompt or document prefix.

    Testing long-context capability also requires dedicated design. Simple “needle in a haystack” tests only check information retrieval. They cannot show whether a model can reason over a long document or integrate information across passages. A more reliable approach is to build questions that require information from several positions to answer, and then measure how accuracy decays across different length ranges.

    2.3 Sandbox and Environment Infrastructure

    Agent training requires a large number of isolated execution environments. Each environment usually includes a file system, processes, network policies, and dependency libraries. Sandbox design must meet three requirements:

    1. Isolation: tasks must not interfere with each other, and a failed task must not contaminate the state of later tasks;
    2. Resettability: the environment can be quickly restored to a known initial state before each task starts;
    3. Resource limits: caps on CPU, memory, execution time, and network access prevent a single task from slowing down the entire cluster.

    These environments typically run on a container platform. Object storage holds task snapshots, and logging services and monitoring alerts detect problems such as abnormal exits and timeout backlogs.

    2.4 Scheduling and Environment Quality Checks

    When training across hundreds of downstream domains at once, the scheduler must balance sample production speed across tasks so that no single domain occupies resources for long periods. The scheduling can follow these principles:

    • Allocate sample quotas dynamically based on each domain’s learning curve, and reduce sampling ratios for domains that have already converged;
    • Set minimum quotas for long-tail tasks to prevent capability regression in those domains;
    • Track environment failures separately from model failures. If an environment itself is faulty, counting its failures as model failures distorts the reward signal.

    Environment quality checks are easy to overlook. Before training, each environment should undergo a smoke test to confirm that the task description, initial files, and test scripts do not contradict each other. During training, tasks with unusually high or unusually low pass rates should be sampled regularly to determine whether the cause is an environment defect or a real difference in capability.

    3. Evaluating Long-Horizon Agent Capabilities

    3.1 Principles for Terminal Task Evaluation

    Terminal tasks require an agent to reach a goal in a restricted command-line environment. Examples include locating and fixing a build error, configuring a service, or writing a script and verifying its result. When evaluating these tasks, follow these principles:

    • Every task should have a clear success criterion, preferably judged by an executable test script rather than manual scoring;
    • Tasks should run under resource constraints, such as limits on execution time, memory, and accessible paths, to approximate a real production environment;
    • When reporting results, give success rate, average steps, and timeout rate together, so that no single metric is viewed in isolation.

    3.2 Evaluating Multi-Step Execution and Tool Use

    For long-horizon tasks, the final success rate is a composite result. It must be broken down into intermediate metrics to locate problems:

    • Tool selection accuracy: whether the model chose the correct tool;
    • Parameter validity rate: whether call parameters conform to the interface definition;
    • Error recovery rate: whether the model can diagnose and retry correctly after a tool returns an error;
    • Plan consistency: whether later steps drift from the original goal.

    Internal benchmarks usually cover multiple engineering domains and report these metrics separately for each domain. If success is low in a particular category, check tool calls and error recovery in that category first.

    3.3 Example Evaluation Pipeline

    The following is a simplified sketch of an evaluation framework that illustrates the structure. The functions are placeholders. In practice, replace them with your team’s own environment interfaces.

    1. from dataclasses import dataclass
    2. @dataclass
    3. class TaskResult:
    4. task_id: str
    5. success: bool
    6. steps: int
    7. timed_out: bool
    8. tool_errors: int
    9. recovered_errors: int
    10. def run_agent_in_sandbox(model, task, timeout_s: int, max_steps: int) -> TaskResult:
    11. """Run the agent in an isolated environment and return a structured result (illustrative implementation)."""
    12. ...
    13. def summarize(results: list[TaskResult]) -> dict:
    14. total = len(results)
    15. if total == 0:
    16. return {}
    17. success_rate = sum(r.success for r in results) / total
    18. timeout_rate = sum(r.timed_out for r in results) / total
    19. avg_steps = sum(r.steps for r in results) / total
    20. errors = sum(r.tool_errors for r in results)
    21. recovered = sum(r.recovered_errors for r in results)
    22. recovery_rate = recovered / errors if errors else 0.0
    23. return {
    24. "success_rate": round(success_rate, 4),
    25. "timeout_rate": round(timeout_rate, 4),
    26. "avg_steps": round(avg_steps, 2),
    27. "error_recovery_rate": round(recovery_rate, 4),
    28. }
    29. def evaluate(model, tasks, timeout_s=600, max_steps=100):
    30. results = []
    31. for task in tasks:
    32. result = run_agent_in_sandbox(model, task, timeout_s, max_steps)
    33. results.append(result)
    34. return summarize(results)

    The key point of this code is that it structures the result of each task and then aggregates the results into metrics across several dimensions. This makes every evaluation reproducible, and the metrics can cross-check each other. For example, a drop in success rate combined with a rise in timeout rate usually indicates a problem with the model’s planning efficiency. A drop in success rate together with a drop in error recovery rate more likely points to insufficient ability to process tool feedback.

    4. Layered Practices for Code Tasks

    Code tasks vary widely in difficulty, so training and evaluation data should be designed in layers by task scale.

    4.1 Localized Fixes

    The task is to locate and fix a defect in an existing codebase. This tests the ability to read code, understand context, and make minimal changes. Evaluation should check two things: whether the fix passes the existing tests, and whether it introduced unrelated changes. Minimizing changes is an important part of engineering quality and should not be overlooked.

    4.2 Building Projects from Scratch

    The task is to build a complete small project from a requirements specification, including directory structure, dependency configuration, core modules, and tests. This tests planning ability and global consistency. Common problems include inconsistent interface definitions, dependency version conflicts, and tests that drift away from the implementation. Evaluation can score in stages: whether the project starts, whether core functions work, and whether the tests cover the main paths.

    4.3 Visual and Interactive Tasks

    Tasks involving game interfaces, web pages, and 3D scenes require attention to visual and interaction quality in addition to functional correctness. Evaluation of these tasks can combine two methods:

    • Programmatic checks, such as whether a page renders, whether controls respond, and whether key elements appear in specified positions;
    • Visual review, such as scoring the consistency of color, layout, and motion against a predefined style guide.

    For tasks that call specialized tools, define usage conventions in advance and pre-install the required dependencies in the sandbox. This keeps the model from failing repeatedly during training because of missing environment components.

    5. Practical Recommendations and Common Pitfalls

    In real projects, the following points deserve priority:

    1. Build a trustworthy evaluation set before assessing training gains. If the evaluation set contains incorrect samples, every later conclusion will be distorted.
    2. Record environment failures and model failures separately, and audit failure samples regularly.
    3. Test long-context capability by segment rather than relying only on overall accuracy.
    4. Strictly lock the versions of the environments used for training and evaluation. Otherwise, differences between two results cannot be explained.
    5. Record the data mix, policy version, reward configuration, and environment image hash for each experiment to keep results traceable.

    Common pitfalls include using a single benchmark to represent all capabilities, treating leaderboard scores as direct proxies for production performance, and ignoring inference cost while focusing only on training metrics. In