Post-Training Efficiency Guide for Long-Horizon Coding Agents
Long-horizon coding agents now operate for hours, executing complex sequences of tool calls, file edits, and test runs. For most teams operating on limited GPU clusters, Reinforcement Learning (RL) post-training requires ensuring every sample provides reliable gradients rather than burning compute on trial and error. This guide explores transferable engineering principles for post-training long-horizon agents, including environment filtering, RL algorithm design for long and stale trajectories, and the necessity of shared training and evaluation frameworks to achieve an optimal balance between performance and cost.
Long-horizon agents have evolved from fixing local bugs to engaging in hours-long terminal operations and programming collaboration. A single trajectory often involves over a hundred tool calls, including reading code, editing files, running tests, and iterating based on failures. If RL treats such a complete attempt as a single sample, any distortion in the pipeline wastes hours of GPU time. While frontier teams can absorb trial-and-error costs with massive clusters, most teams must institutionalize “reliable gradients per sample” on a scale of around 100 GPUs.
This article does not discuss specific models or benchmark rankings. Instead, it focuses on transferable engineering principles for post-training: how to filter environments, design algorithms for long, stale, and low-precision sampling, and ensure optimization, training, and evaluation share the same agent runtime framework. The goal is to approach the Pareto frontier of performance versus single-task cost, rather than chasing incomparable scores through unlimited inference compute.
Why Standard Post-Training Recipes Fail
In short Q&A scenarios, a sample is often a single generation with dense or well-defined reward boundaries. Long-horizon programming is different.
First, credit assignment length is extreme. Final test pass/fail may depend on a flawed retrieval or destructive edit dozens of steps earlier. If advantage estimation only looks at the outcome, reasonable intermediate steps are drowned out by the same reward signal, leading to overly conservative policies or shortcut-taking.
Second, sampling is highly heterogeneous. Easy tasks finish in minutes, while hard tasks exhaust time budgets and fail. Mixing batches with many zero-reward timeout trajectories causes gradient variance to dominate updates, drastically reducing the proportion of effective samples.
Third, trajectories become “stale” during training. Agent policies, tool responses, and context lengths evolve. Using long trajectories sampled by older policies for importance sampling causes weights to explode or collapse. Low-precision inference boosts throughput but amplifies instability if log probabilities, rewards, and value estimates lack precision consistency.
Fourth, slight differences between training and evaluation environments make scores uninterpretable. Timeouts, retries, file permissions, test isolation, and access to reference patches alter pass rates. Claiming “same task improvement” while changing runtime frameworks is meaningless.
Therefore, on a 100-GPU cluster, the key is not just “running full-parameter updates,” but ensuring every unit of GPU time corresponds to verifiable learning signals.
Filter Environments Before Discussing Algorithms
Environment quality determines the reward signal-to-noise ratio. It is recommended to categorize candidate tasks into three tiers and only feed the middle tier into main training.
- Too easy: The base model can already complete them reliably. They occupy sampling time and yield little policy improvement. Suitable for regression sets, not as a primary gradient source.
- Moderate: The success rate of multiple independent attempts is significantly non-zero but not near saturation. These tasks best distinguish between “attempting” and “converging to the correct patch.”
- Too hard or undecidable: Vague specs, unstable tests, reliance on external networks, or non-reproducible data. Failures cannot be attributed and should be removed or rewritten into automatically decidable subtasks.
When filtering, record at least: independent attempt count, pass rate, average wall-clock time, tool call rounds, and failure types (compilation, testing, timeout, environment corruption). Difficulty is a statistical metric under a fixed runtime framework, not a manual label. Curriculum learning can progress via pass-rate buckets, but avoid suddenly introducing tasks with vastly different distributions in the same update batch, as this destabilizes the value function.
Rewards should be sparse and auditable: primarily hidden tests or independent verification commands, supplemented by minimal process constraints (e.g., no deleting tests, no rewriting judgment scripts, workspace must be rollback-able). Overly strong process rewards lead the model to optimize “looking busy” tool calls rather than correct outcomes.
RL Recipes for Long Trajectories
Full-parameter updates are feasible but must account for the bias and variance introduced by long trajectories. Prioritize the following constraints before considering more complex algorithm variants.
- Decouple sampling and learning. Batch-generate trajectories using the current policy, saving final states, log probabilities, tool observations, and rewards to disk. The learning phase only consumes validated trajectories. This allows failed tasks to be retried or discarded without feeding half-finished trajectories to the optimizer.
- Control staleness. Record the policy version at sampling time for each trajectory. Downweight or discard if the version gap exceeds a threshold. Importance ratios should be clipped, and the clip ratio monitored; excessive clipping indicates the policy has drifted from the sampling distribution. In such cases, reduce the step size or shorten the sampling-update interval rather than relaxing the clipping.
- Segmental credit assignment. Set a few checkpoints on observable events like test failures, compilation errors, or critical file rewrites, and apply group normalization combined with outcome rewards. Normalization should occur within multiple attempts of the same task to prevent varying task durations from skewing the advantage scale.
- Consistent precision strategy. Inference can use lower precision for throughput, but log probabilities written for training must match the learning phase’s computational conventions, or explicitly record the upper bound of quantization error. Do not mix “sampling with one numerical path, replaying with another” without correction.
- Conservative updates. Apply KL or ratio penalties to the reference policy to limit single-step changes. In long-horizon tasks, an aggressive update can simultaneously break multiple tool-usage habits, and rollback costs are higher than in short-text scenarios.
- Budget as part of the action space. Max rounds, per-round timeouts, and total wall-clock time should be written into the task definition. The model should learn to stop and deliver within budget, rather than defaulting to exhausting the limit.
Below is illustrative logic for trajectory filtering, expressing only the judgment order without corresponding to any specific framework interface:
accept(trajectory):if not finished or env_corrupted: return rejectif policy_version_gap > gap_limit: return rejectif abs(log(importance_ratio)) > clip_limit: downweightif reward not in {0, 1} and not audited: return rejectreturn accept with group-normalized advantage
On the optimizer side, monitor three types of curves separately: environment pass rate, gradient norm and clip ratio, and GPU-hours per task. Looking only at pass rate masks “getting lucky via longer sampling”; looking only at loss masks reward hacking.
Training and Evaluation Must Share a Runtime Framework
A significant portion of a long-horizon agent’s score is actually a score of its runtime framework. The framework handles repository isolation, command whitelists, filesystem snapshots, test execution, timeouts and retries, observation truncation, and whether internal logs are exposed to the model. If training uses lenient retries while evaluation uses strict single attempts, the two are incomparable.
In practice, it is recommended to fix a framework contract:
- Each task gets an independent working directory, destroyed upon completion. No cross-task residue is allowed.
- Toolsets, permissions, and network policies must be consistent between training and evaluation. If training requires extra diagnostic tools, the evaluation report must list them separately.
- Observation truncation rules must be public and fixed to prevent the model from relying on answers accidentally exposed in ultra-long contexts.
- Pass/fail is determined by the framework executing verification commands, not by the model’s self-reporting.
- Reported metrics should at least include: pass@1, average attempt count, average wall-clock time, average tokens or average GPU-hours. Cost accounting must use the same standard—for instance, self-hosted inference should only count direct compute and storage, or be uniformly converted to a public, verifiable pricing method. Do not plot results from different inference intensities on the same graph without explanation.
When migrating to software engineering tasks, keep the framework unchanged and only swap the task distribution. If pass rate improvements fluctuate wildly with framework toggles, fix the framework first instead of adding more training steps.
Cluster Side: Treat Invalid GPU-Hours as Bugs
A 100-GPU scale relies on scheduling, not scale, to mask waste. Set up a separate queue for long tasks: short trajectories return quickly, long trajectories are allowed to complete asynchronously, but the learning step must wait until the “valid samples in this batch” reach a minimum count. Time out tasks promptly, killing processes and reclaiming containers or sandboxes. Save checkpoints by policy version to ensure any inflection point on the curve can be reproduced.
Logs must at least answer: why was this trajectory discarded, which verification command did the reward come from, and what was the policy version at the time. Without these three, the recipe cannot be handed off, nor can one determine whether data, algorithm, or framework is driving the results.
Modules unrelated to current language decisions (e.g., visual encoding, retrieval indices) can be frozen, focusing updates on the language parameters that actually generate actions. This is a compute allocation principle, not a commitment to a specific model architecture; freezing should be based on ablation studies to avoid unjustifiably expanding trainable parameters.
How to Judge If You Are on the Pareto Frontier
Do not define success by a single highest score. Under the same runtime framework and budget accounting, look at pass rate and single-task cost simultaneously. If the pass rate rises but average wall-clock time doubles, you are merely shifting compute from training to inference. If costs drop but only on tasks seen during training, verify on held-out tasks.
An actionable acceptance sequence is: first, purify tasks and rewards until failures are attributable; second, lock down the runtime framework and establish a baseline cost; third, introduce version clipping, group advantage, and conservative updates; finally, scale up task size or trainable parameters. Reverse this order, and extra compute will only amplify noise.
The essence of post-training long-horizon agents is quality control over “scarce, delayed, high-variance feedback.” The environment provides the signal, the recipe ensures the signal is not destroyed by algorithms under long trajectories and low precision, and the shared framework guarantees training improvements are recognized by evaluation. Achieving these three points allows a limited cluster to form a reproducible performance-cost trade-off, without turning every failed programming attempt into an untraceable loss of GPU-hours.
