Post-Training Long-Horizon Coding Agents: Practical Lessons on Scaling Reinforcement Learning

    This article explains how post-training for long-horizon agents differs from training for single-turn question answering. It covers the engineering work needed to scale reinforcement learning, including rollout throughput, long-context inference cost, sandbox design, and environment quality checks. It also describes how to evaluate terminal and engineering agents, how to weigh inference speed against quality, and where teams building agent capabilities can start.

    1. Background: New Requirements for Models in Agent Tasks

    Early language models mainly handled single-turn question answering, and they were judged by whether the answer was correct. As models began to take on long-horizon tasks such as code modification, environment setup, and data analysis, accuracy on individual responses no longer fully described their capability. An agent has to plan steps, call tools, observe results, and correct its course over many turns. An error at any step can invalidate every step that follows.

    For this reason, the goal of post-training shifts from “answering questions correctly” to “completing tasks.” Reinforcement learning is one of the main ways to make this shift. It uses the task outcome directly as the reward signal and does not rely on manually labeled reference answers for each example. That makes it well suited to tasks with clear goals that can be verified automatically.

    2. Engineering Challenges When Scaling Post-Training Compute

    Adding compute to post-training does not automatically improve model capability. Large amounts of added compute without matching engineering support can be wasted on idle scheduling, environment failures, or noisy data. Several areas need attention.

    2.1 Throughput and Stability of the RL Framework

    Reinforcement learning training involves two types of workloads: generating trajectories (rollouts) and updating parameters. Generation is mainly limited by inference latency, while updates are mainly limited by memory and communication bandwidth. When the two are mismatched, GPU utilization drops noticeably. A common approach is to decouple generation from training, collect trajectories asynchronously, and limit how stale the data can be. Outdated data is either discarded or corrected.

    Illustrative code:

    1. def collect_rollouts(policy, env_pool, batch_size, max_staleness):
    2. trajectories = []
    3. while len(trajectories) < batch_size:
    4. env = env_pool.acquire() # Take one isolated environment from the pool
    5. traj = run_episode(policy, env) # Interact with the environment until the task ends or times out
    6. env_pool.release(env) # Return the environment to the pool and reset its state
    7. if policy.version - traj.policy_version <= max_staleness:
    8. trajectories.append(traj) # Discard trajectories that are too stale
    9. return trajectories

    2.2 Controlling the Cost of Long-Context Inference

    The context of an agent task keeps growing with each step, and a single trajectory can contain many tool outputs. Both attention computation and KV cache memory grow with length, which directly reduces the number of trajectories that can be processed per second. Three common methods help:

    • Truncate, summarize, or compress tool outputs in a structured way, keeping only the information relevant to later decisions;
    • Use prefix caching to reuse the shared context across multiple samples of the same task;
    • Group requests into buckets by sequence length to reduce the computation wasted on padding.

    2.3 Sandbox Infrastructure

    Programming and terminal tasks require actually executing code. A sandbox should meet three conditions: its environment can be reset, its resources can be limited, and its behavior can be audited. Each sandbox should limit CPU, memory, disk, and network egress. The file system should be fully cleaned after each task so that residue from one trajectory does not affect the next sample. This infrastructure can be built on general container and isolation technologies. The main engineering work lies in quota management and lifecycle control.

    2.4 Scheduling and Environment Quality Checks

    When hundreds of downstream domains take part in training at the same time, the quality of the environments determines whether the reward signal is reliable. A common problem is misjudgment: the task was actually completed, but the acceptance script fails because of a timeout or a missing dependency. This noise teaches the model incorrect behavior patterns. Teams should therefore set up a shared environment health-check process. It should include dependency checks, deterministic validation of acceptance scripts, and consistency statistics across repeated runs of the same task.

    3. Evaluation Design: Measuring Terminal and Engineering Agents

    Evaluation serves two purposes. It guides training, and it provides evidence of what the model can do. The following principles apply to evaluation design.

    3.1 Task Realism and Resource Constraints

    Completing tasks in a real terminal with limited resources is closer to practical needs than answering questions in an idealized setting. Evaluation tasks should state inputs, goals, and available resources clearly. Each task should have its own acceptance test. Acceptance tests should check the final state, such as file contents, process results, and program output, rather than whether the model produced a particular piece of text.

    3.2 Multi-step Execution and Tool Use

    Long-horizon evaluation should be broken down into observable metrics:

    • Task pass rate: whether the final state meets all acceptance conditions;
    • Step efficiency: the number of interaction turns needed to complete the task;
    • Tool call accuracy: whether the arguments are valid and the call order is reasonable;
    • Failure type distribution: timeouts, syntax errors, accidental file deletion, getting stuck in loops, and similar issues.

    Illustrative scoring logic:

    1. def score_task(result, tests):
    2. if result.timed_out:
    3. return {"passed": False, "reason": "timeout"}
    4. passed = all(test.run(result.final_state) for test in tests)
    5. return {
    6. "passed": passed,
    7. "steps": result.num_turns,
    8. "reason": "ok" if passed else "acceptance_failed",
    9. }

    3.3 Preventing Overfitting and Data Contamination

    If training tasks closely resemble evaluation tasks, scores will be higher than the model’s true capability. A recommended practice is to keep an independent evaluation set and replace some of its tasks on a regular schedule. Teams should also check whether the training corpus contains original evaluation tasks or their answers. For tasks built from public code repositories, split the data by version or time so that evaluation content does not enter the training data.

    3.4 Interpreting Metrics

    A single overall score can be misleading. When two models have similar pass rates, compare their results across difficulty levels and analyze how their failure causes differ. If a model is stable on simple tasks but drops noticeably on multi-file modification tasks, its long-horizon planning still needs work. The overall score alone would not reveal this.

    4. Trade-offs Between Speed and Quality

    When capability is comparable, inference speed directly affects the interaction experience and running cost of an agent. Common ways to speed up inference include the following:

    1. Inference service optimization: batching, continuous batching, and operator fusion improve throughput, mainly in concurrent scenarios;
    2. Speculative decoding: a small model drafts candidate tokens, and a large model verifies them in parallel. This lowers latency per request when the quality loss is acceptable;
    3. Quantization: lowering the numerical precision of weights or activations reduces memory usage and bandwidth pressure. Quality changes must be verified on the specific task;
    4. Distillation: a small model learns the output distribution of a large model. This suits latency-sensitive scenarios.

    Choices can be organized by task type. Interactive coding assistance focuses on response latency. Offline batch tasks focus on completion rate per unit cost. Critical decision tasks focus on final correctness. Using different model versions or inference configurations for each tier is usually more economical than using one configuration for everything.

    5. Practical Recommendations

    Teams that want to build agent capabilities in-house can proceed in the following order:

    1. Build an evaluation set first. Without stable evaluation, it is hard to judge whether any change is an improvement;
    2. Set up a least-privilege sandbox that limits network access and file write paths;
    3. Record complete logs for every trajectory to support postmortem analysis of failures;
    4. Monitor token consumption and time spent per task, and treat cost as a core metric;
    5. Require manual confirmation for high-risk operations such as deletion, sending data externally, and changing permissions.

    Safety is the baseline for deploying agents. A model may misread instructions, and it may be misled by text in its environment. For this reason, the execution layer should operate independently of the model’s judgment. Dangerous commands should be controlled through an allowlist or policy validation, not only through prompt-based constraints.

    6. Conclusion

    Gains in agent capability come from training, engineering, and evaluation working together. Scaling reinforcement learning compute is only a starting point. Whether that compute turns into stable gains depends on environment quality, inference efficiency, and the credibility of evaluation. When planning, teams should design these three parts as one system.