Cost-Effective Reinforcement Learning for Long-Horizon Agents
Training long-horizon coding and terminal agents efficiently requires more than larger models or clusters. This article explains how to balance task success, cost, and transfer through difficulty-matched environments, careful handling of long and stale trajectories, consistent log-probability computation, and a shared training and evaluation harness. It also outlines budget-aware training, common evaluation pitfalls, and a practical implementation sequence for teams with limited compute.
Long-horizon coding and terminal tasks differ from short question-answering tasks. A model must often execute a sequence of actions: read constraints, modify files, run commands, respond to errors, and continue until the task is complete or its budget is exhausted. Each action changes the state that subsequent decisions depend on, while rewards often arrive only at the end.
Applying methods designed for short-form alignment directly to these tasks can waste compute in two ways. Sampling may concentrate on tasks that are too easy or too difficult, producing little useful gradient signal. Alternatively, long trajectories may remain in use after the policy has changed, distorting updates when old samples are treated as experience from the current policy.
Cost-effectiveness is not primarily about making the model larger. It is about ensuring that compute produces learnable signals and that deployment costs per task are explainable and reproducible.
1. Define the Frontier You Want to Optimize
Evaluating a long-horizon agent requires at least three dimensions.
Task success rate. Measure success under a fixed execution harness, step or time limit, and retry policy. Averages across multiple independent runs are more informative than a single impressive result. Different harnesses define completion, tool permissions, and environment resets differently, so their scores are not directly comparable.
Cost per task. Costs include generated tokens, tool calls, failed retries, and human review. In long trajectories, low-value exploration in later stages can consume a large share of the total expense. Reporting only the best score at the highest inference budget, without average cost, does not establish whether an approach can scale.
Transfer. Improvements in terminal operations should be tested again on adjacent tasks such as software repair and regression verification. Gains limited to one task set may reflect overfitting to prompts or hidden environment details rather than more reliable decision-making.
Plot success rate against cost to identify the Pareto frontier: reduce cost without lowering success, or maximize success within a fixed cost ceiling. Training objectives should support this frontier rather than a single leaderboard position.
2. Where Efficiency Comes From on a Limited Cluster
Full-parameter training does not automatically require an enormous cluster. For large language models, long-trajectory sampling, advantage estimation, and communication can dominate runtime. Simply adding more accelerators is not the answer.
Efficiency typically depends on three design choices, rather than a particular hardware vendor or base model.
Select environments that provide useful signals. Tasks should fall within a range where the current policy sometimes succeeds and sometimes fails. Consistently solved tasks offer little gradient signal; consistently failed tasks may provide mostly noise. Difficulty should rise as the policy improves, rather than starting exclusively with the hardest repository-level tasks.
Account for the actual shape of trajectories. They are long, some portions become stale, and rollout computation often uses lower numerical precision than the primary training computation. Ignoring these properties can produce a declining training loss without better evaluation results.
Use the same coding harness for training and evaluation. Differences in tool response formats, timeouts, or working directories can teach the model a harness-specific dialect that fails in another execution environment.
Modules weakly related to language-based decision-making, such as vision encoders or retrieval indexes, can be frozen to save memory and step time. Whether to freeze them should be established through ablation studies, not assumed to be a free optimization. If auxiliary heads, such as multi-token prediction heads, contribute to the language distribution, explicitly define whether they are updated to avoid a mismatch between the training objective and the distribution used during inference.
3. How to Select Agent Environments
Reliable signals matter more than task volume. Build the environment pool around the following criteria rather than collecting every available coding task indiscriminately.
Difficulty Matching
Run small probes with the current policy and estimate pass rates. Downweight or remove tasks with very low or very high pass rates from the current training round, and give more sampling weight to tasks with intermediate pass rates.
Probing also costs compute. Use a shorter step limit for initial screening, then run full trajectories on borderline tasks.
Verifiable Outcomes
Terminal and coding tasks should ideally support automatic checks: passing tests, matching reference outputs, or satisfying constraints on state changes. Open-ended requests to “make this better” lack stable rewards and are unsuitable as the main early-stage training signal.
Independence and Resetability
Start every episode from a clean workspace so that files left by previous tasks cannot contaminate rewards. Parallel environments should not share mutable caches.
A Stable Action Space
Keep schemas for commands, patches, and file operations consistent. Frequently changing tool definitions effectively changes the action space during training, making old data difficult to reuse.
Protection Against Reward Gaming
Checkers should prevent strategies such as deleting tests, hard-coding outputs, or modifying only the scoring script. Treat these attempts as failures and record them; otherwise, reinforcement learning will amplify the shortcuts.
A curriculum can progress through single-file edits, coordinated multi-file changes, diagnosis from long logs, and tasks requiring multiple rounds of tool-based verification. Within each level, sample according to probed pass rates. Retain a small amount of replay from earlier levels to reduce catastrophic forgetting.
4. Long Trajectories, Stale Samples, and Low-Precision Replay
Credit assignment is a central challenge in long-horizon episodes. When rewards are sparse and appear only at the end, returns should be attributed meaningfully to important decisions rather than spread uniformly across every conversational step.
Common approaches include per-step discounting, shortening the span over which advantages are assigned in failed trajectories, and downweighting clearly unproductive repeated commands. Choose the coefficients on a validation set rather than copying defaults from short-dialogue tasks.
After a policy update, previously collected trajectories are off-policy relative to the current policy. The main safeguards are to:
- Use importance ratios or clipping to limit the size of individual updates.
- Discard segments with excessively large ratios.
- Limit how many times the same batch is reused.
Longer trajectories accumulate more distribution shift, so staleness thresholds should be stricter than those used for short text.
For throughput, rollout systems often use lower precision or more aggressive decoding settings. If the training system recomputes log probabilities at higher precision, the mismatch can bias importance-ratio estimates.
Keep the numerical computation paths for sampling and recomputation consistent, record log probabilities at each step, and monitor the mean and variance of the ratios. A sudden increase in variance often indicates that precision, temperature, or stopping conditions differ from those used during data collection.
Batch size must also be considered alongside trajectory length. A few exceptionally long failed trajectories can dominate the gradient. Set a per-trajectory token cap, truncate trajectories that exceed it, and mark them as incomplete so that uncontrolled exploration does not overwhelm an entire update.
Maintain enough successful and failed trajectories for comparison. Otherwise, advantage estimation can become biased toward superficial patterns associated with only one outcome class.
5. Share the Execution Harness Across Training and Evaluation
The harness is the agent’s actual action interface. Treat it as part of the product rather than a temporary script.
A unified episode protocol. Use the same structure for system instructions, user tasks, tool responses, error types, and termination reasons. Keep training and evaluation log fields consistent so that failures can be replayed.
Unified resource boundaries. Align working directories, network permissions, per-command timeouts, total step limits, and output limits. If training permits unlimited retries but evaluation caps the number of steps, the model learns to rely on a budget that does not exist at evaluation time.
A unified checker. Place unit tests, diff checks, and static constraints inside the harness, and use the same implementation to assign rewards. Avoid creating a separate, approximately equivalent checker in the training script.
Observability. Record the tool name, elapsed time, return code, token count, and whether a budget limit was reached at every step. These fields support both debugging and retrospective cost estimates.
Object storage is suitable for trajectories and checkpoints. Logs, monitoring, and alerts can reveal whether failures are concentrated around particular command types. Container platforms can isolate each episode’s filesystem and prevent cross-episode contamination.
Episode constraints can be expressed in configuration without tying them to a particular cloud provider’s API:
max_steps: 80command_timeout_s: 30max_output_chars: 8000reward: tests_passedon_timeout: terminate_failprecision_logprobs: record_at_sample_time
Archive the harness version with each checkpoint. Otherwise, changes in scores for the same weights cannot be attributed confidently to the model or the environment.
6. Put Cost into Training, Not Just Reporting
Optimizing only pass rate encourages longer reasoning and more tool calls. If the business pays for generated tokens and tool usage, reflect those budgets in rewards or constraints.
Practical approaches include:
- Prefer shorter successful paths among trajectories with comparable success rates.
- Assign an explicit failure outcome to episodes that exhaust their budget without completing the task.
- Report both average and high-percentile costs so that unusually long tasks remain visible.
Keep internal inference costs separate from externally billed prices. For external comparisons, specify whether cost is measured in cluster runtime, per-token charges, or per-tool-call charges. Claims such as “tens of times cheaper” are not meaningful without a stated accounting basis.
At deployment, the same harness can support tiered budgets: give simple tasks a smaller budget, then increase the step limit after failure. This can lower average cost without paying for the highest inference budget on every task.
Evaluate the tiering policy itself on a fixed task set to ensure that it does not merely optimize performance on easy tasks.
7. Common Sources of Evaluation Distortion
Data Leakage
If task descriptions, tests, or repair patches appear in pretraining data or a prompt-retrieval corpus, pass rates may be inflated. Keep task statements separate from reference solutions and spot-check whether the model reproduces hidden tests directly.
Harness Mismatch
Official benchmark results and results from a custom harness should not be presented as if they came from the same experimental setup. State the step limit, temperature, whether multiple samples are allowed, and the checker version.
Variance
Long-horizon tasks have high variance, and even five runs may be insufficient. Report averages and variability, and avoid overinterpreting small differences.
Selective Reporting
Showing only the subsets with the largest gains over the base model can conceal overall performance. The main results should cover all predefined tasks. Put subset analyses afterward and explain the selection rules.
8. A Practical Implementation Sequence
Fix the harness and checker before focusing on algorithms. Use small-scale probes to map the pass-rate distribution and remove tasks that offer little learning signal.
Next, run short-horizon ablations on clipping, trajectory-length caps, and consistency in log-probability recording. Once validation success improves without uncontrolled cost growth, extend training and increase curriculum difficulty.
At every stage, retain replayable trajectory samples. Use failure categories—not just the loss curve—to decide what to change next.
When compute is limited, prioritize three investments: difficulty-matched environments, safeguards for stale and low-precision trajectories, and a shared training and evaluation harness. These determine whether gradients are informative, results are comparable, and deployment costs are manageable.
Model size and cluster size are multipliers. Multiplying ineffective sampling still produces waste.
