Long-Horizon Coding Agents: Reinforcement Learning Practice Under Limited Compute

    Long-horizon coding agents turn model outputs into sequences of decisions that operate terminals, read project files, edit code, and verify results. This article explains why limited-compute reinforcement learning should optimize success rate, cost, and reliability together, and how to improve the training signal per unit of resources through task design, rewards, asynchronous execution, numerical stability, and a shared agent runtime for training and evaluation.

    1. Why Long-Horizon Agent Training Cannot Be Judged by Model Scale Alone

    Coding agents are moving from one-shot code generation toward execution systems that can operate a terminal, read project files, modify programs, and verify results over time. A complete task may include locating the problem, checking dependencies, editing code, running tests, and repairing failures across multiple rounds. The model output is no longer the final deliverable. It is the decision sequence that drives the workflow.

    This change alters the cost structure of reinforcement learning. For short-answer tasks, one sample usually requires only a limited amount of generated text. For a long-horizon coding task, a training trajectory also includes tool execution, environment wait time, log reading, and state updates. If a task runs for hours, a single success or failure label can already consume a large amount of inference and environment resources.

    Under limited compute, the core question is therefore not how to generate as many trajectories as possible. It is:

    How can each unit of resources produce more trustworthy, useful training signal for policy updates?

    The source material discusses reinforcement learning for large-parameter models using dozens of accelerators over a training cycle of several days, and reports improvements in the relationship between task success rate and cost. Those results depend on specific hardware, model structure, task distribution, runtime framework, and cost accounting. They should not be treated as a general, directly reproducible promise. What is more transferable is the method behind them: jointly optimizing data, algorithms, and the execution system to raise resource efficiency in long-horizon training.

    2. Set the Right Objective: Optimize Success Rate, Cost, and Reliability Together

    2.1 A single-attempt success rate does not represent full capability

    Single-attempt success rate is the share of tasks an agent completes when it tries each task once. It reflects the effectiveness of the first execution, but it does not show how much the model spent to get there.

    Two agents can have similar success rates while following very different paths. One may finish a fix after a small number of tool calls. Another may repeatedly read files and run irrelevant tests, yet still succeed. In a real development workflow, their usage cost and response experience are not the same.

    Evaluation should therefore include at least:

    • Single-attempt task success rate
    • Average and high-percentile task duration
    • Volume of input, output, and repeated context processed
    • Number of tool calls and the share of failed calls
    • Environment exception rate
    • Average cost per task
    • Aggregate cost normalized by successful tasks

    If a benchmark set completes a number of task attempts, total cost is C, and the number of successful tasks is S, then C / S estimates the cost per successful task on that set. This metric includes consumption from failed attempts, so it is closer to real operating burden than a cost calculated only on successful trajectories.

    2.2 Cost accounting must be explicit

    Actual cost can come from model inference, environment compute, storage, networking, and idle resources. Amortized hardware cost for a self-hosted model is not the same accounting basis as call cost estimated from public service prices.

    Any cost comparison should state whether it includes training expense, environment overhead, and failed retries, and how factors such as context reuse and batching are counted. A claim that cost fell by some multiple, without a shared accounting basis, cannot support a rigorous technical decision.

    2.3 Use the Pareto frontier to understand the direction of optimization

    If one configuration has a success rate no lower than another and a cost no higher, it dominates on those two dimensions. Points that cannot be dominated by any other configuration form the Pareto frontier.

    In practice, compare the curves formed by different sampling budgets, execution time limits, and inference configurations, rather than selecting only the single highest score. A valuable improvement raises capability at the same cost, or reduces resource use at similar capability.

    3. Stage 1: Build Task Environments with Moderate Difficulty and Reliable Feedback

    3.1 Training tasks need distinguishable outcomes

    If tasks are too easy, the model almost always succeeds, and new trajectories add little learning signal. If tasks are too hard, samples may all fail, so different decision paths cannot be distinguished effectively.

    A more reasonable approach is to run a small pilot, observe completion rate, execution time, and failure types, then group tasks by difficulty and resource consumption. Training tasks can cover different abilities, such as understanding a codebase, cross-file edits, fault localization, adding tests, and environment troubleshooting, instead of optimizing around only one repair pattern.

    Difficulty groups should not become a rigid fixed rule. As policy capability improves, task value should be reassessed so the model does not remain indefinitely on tasks it has already mastered.

    3.2 Environment exceptions and policy failures must be separated

    A failed dependency download, a crashed test infrastructure, or insufficient disk space does not mean the agent cannot complete the task. If these exceptions are recorded directly as negative rewards, the training signal is contaminated.

    Task state should at least distinguish normal success, normal failure, budget exhaustion, infrastructure exceptions, and uncertain verification results. Whether environment exceptions are retried, and whether the related trajectories enter training, should be decided by rules set in advance, not adjusted after seeing the results.

    3.3 Reproducibility is a prerequisite for trustworthy rewards

    Each task should have a fixed initial project state, dependency constraints, and verification method. Task environments should run in isolation and retain key logs, file changes, and execution results.

    Writable state should not be shared across tasks. Files or configuration left by a previous task can change the difficulty of later tasks. This kind of hidden state leakage damages both training quality and evaluation credibility.

    4. Stage 2: Point Rewards at Real Delivery, Not Surface Actions

    4.1 Use the final verifiable result as the primary signal

    The most important outcome of a coding task is whether the change meets the requirements, not whether the model performed many actions. Rewards should primarily depend on functional verification, regression checks, and constraint satisfaction.

    A task should not be marked successful merely because code was modified, a command returned success, or the agent claimed completion. Behaviors such as deleting tests, bypassing checks, or hard-coding answers should also be identified, so the policy cannot obtain reward by breaking the verification mechanism.

    4.2 Use process rewards carefully

    Terminal feedback on long tasks is sparse, so process information can be used in moderation to help training, for example whether required checks were completed or whether a prohibited action was triggered. Process rewards are only proxy objectives. Poorly designed, they push the model to optimize the metric rather than solve the problem.

    Rewarding the number of test runs, for example, can cause repeated test execution. Rewarding the number of files changed can cause irrelevant edits. The test of a process reward is whether it consistently promotes a correct final delivery, not whether it is easy to compute.

    4.3 Cost constraints must not override correctness

    Success feedback, resource consumption, and violation penalties can be combined into a training objective, but the weights should be chosen through independent evaluation. If penalties on time or generation length are too strong, the model may give up early or skip necessary verification.

    A safer order is to establish reliable completion first, then gradually improve execution efficiency, while continuing to check for regressions such as missed tests or hasty submission.

    5. Stage 3: Use an Asynchronous Pipeline to Reduce Idle Time from Long Trajectories

    5.1 Synchronous waiting is easily slowed by a few long tasks

    In synchronous sampling, a batch usually waits until every task finishes. Long-horizon tasks vary widely in duration, so a few complex tasks can leave resources for already finished tasks idle.

    Decoupling sampling from training lets task executors keep producing trajectories while the trainer reads completed samples from a buffer and updates. This can reduce overall waiting, but the supply and demand among inference, environment execution, and training must be monitored so one stage does not become the bottleneck.

    5.2 Asynchronous execution creates policy staleness

    By the time a long task finishes, the trainer may have updated through several versions. The trajectory was generated by an old policy, while the update targets a new policy, and their probability distributions may differ substantially.

    Trajectories should therefore record policy version, generation time, action probabilities, and task state, and sample staleness should be monitored. Depending on the algorithm, version span can be limited, sampling throughput adjusted, or overly old data handled.

    Importance weighting and probability-ratio constraints can control distribution shift, but long trajectories still require attention to variance and numerical stability. These methods should not be treated as a remedy that works for arbitrarily stale data.

    5.3 Separate environment waiting from model compute

    While tests or compilation run, a task does not necessarily need to keep occupying a model inference slot. Executors should support suspending and resuming tasks so inference resources can serve other tasks that are ready.

    This requires explicit task state, including the current step, tool results, working-directory changes, and context version. Timeouts, cancellation, and resource reclamation are also required so suspended tasks do not accumulate without limit.

    6. Stage 4: Control Training Risk from Long Sequences and Low Precision

    6.1 Do not let long trajectories dominate the gradient by default

    Trajectory length can differ greatly across tasks. If losses at all generated positions are summed directly, long trajectories can receive a larger implicit weight and bias the model toward verbose behavior.

    Training needs to make clear which positions enter the loss, whether tool-returned text is correctly masked, whether the loss is normalized by generated position or by trajectory, and how truncated trajectories are handled. Different normalization choices create different preferences and should be selected by evaluation, not intuition.

    6.2 Low-precision optimization needs numerical monitoring

    Low-precision computation can reduce memory use and raise throughput, but probability ratios, advantage estimates, and accumulation over long sequences in reinforcement learning can amplify numerical error.

    Gradient norms, abnormal probability ratios, policy entropy, sudden loss changes, and non-finite values should be monitored continuously. Where needed, sensitive computations should use higher precision, together with validated gradient clipping and update constraints.

    6.3 Whether full-parameter updates pay off depends on overall return

    Full-parameter training gives the policy more room to change, but it also increases gradient, optimizer-state, and communication overhead. For sparsely activated models, using only part of the parameters at each generated position does not mean training state occupies memory in the same proportion.

    Under limited resources, full-parameter updates, partial-parameter updates, and parameter-efficient adaptation should be compared together, with attention to final success rate, training stability, and resource cost, not only to the count of trainable parameters.

    7. Stage 5: Use One Agent Runtime for Training and Evaluation

    The runtime between the model and its tools determines what the agent can see, what it can execute, and how it recovers after failure. It includes tool descriptions, result formats, context management, timeout rules, and stop conditions.

    If training allows a longer execution time while evaluation stops early, or if training automatically provides a test summary while evaluation returns only the full log, the conditions facing the model have changed. Results then become hard to attribute.

    Training and evaluation should use the same interaction protocol as far as possible, while data sets remain strictly isolated. The following should be fixed in particular:

    • Tool permissions and input/output formats
    • File-reading and log-truncation rules
    • Task time limits and call budgets
    • Error returns and recovery mechanisms
    • Submission format and termination criteria

    Long-horizon tasks also need a concise, reliable state summary, such as verified facts, current changes, failure causes, and remaining work. A summary cannot replace raw logs, and unverified speculation must not be written as fact. Original records should remain traceable so the model or an evaluator can inspect them when needed.

    8. From Small-Scale Validation to Stable Training

    A practical order is:

    First, establish a baseline with no additional training. Measure success rate, duration, cost, and exception rate, and confirm that the tasks and verification environment are reliable.

    Second, run small-scale training and change only a few key factors. Check whether the reward is effective, whether sampling is stable, and whether success rate shows a repeatable improvement.

    Third, run ablations. Separately examine the effects of task selection, asynchronous sampling, reward design, and context management, so the entire gain is not attributed to one stage.

    Fourth, evaluate transfer on an isolated task set. Besides the overall mean, report performance by task category, variation across repeated runs, and long-tail failures.

    Fifth, run deployment safety checks. Terminal execution should follow least privilege, restrict network access, sensitive file reads, and destructive operations, and require human confirmation or an independent policy check for high-risk actions.

    9. Conclusion: Under Limited Compute, Closed-Loop Efficiency Is the Point

    Reinforcement learning for long-horizon coding agents is, at its core, joint optimization of data, algorithms, and the execution system. Larger models and more hardware can raise the ceiling, but they do not automatically solve environment noise, reward bias, sample staleness, or inconsistent evaluation.

    For teams with limited resources, the first investments should be reliable tasks, trustworthy feedback, a unified runtime, and an observable training process. On that foundation, asynchronous scheduling, update stability, and task budgets can then be optimized.

    What is worth pursuing is not an isolated high score. It is completing more tasks, under explicit evaluation and cost accounting, with fewer resources, a lower exception rate, and a more predictable process.