Long-Horizon Coding Agents: Evaluation, Training, and Production Engineering

    This article breaks down the key components of long-horizon coding agents from an engineering perspective. It covers the capability stack (planning, tool use, state management, error recovery), how to design a trustworthy evaluation framework, the trade-offs in post-training with reinforcement learning, inference-side concerns such as context length and prefix caching, and the design requirements for managed long-running execution environments. Code examples are included for evaluation reporting, cost estimation, and checkpointed execution with approval gates.

    Introduction

    LLM applications are shifting from single-turn question answering to long-running, multi-step autonomous work. In the past, a model that produced a code snippet or a summary could be considered done. Today, we expect models to read a codebase, run commands, inspect error output, edit files, and verify repeatedly until the goal is met. Systems like this are commonly called agents.

    This article dissects these systems from an engineering perspective, covering capability composition, evaluation methodology, training-inference trade-offs, and runtime environment requirements, with the goal of giving readers a reusable analytical framework.

    1. The Capability Stack for Long-Horizon Tasks

    A long-horizon task is composed of multiple capabilities; single-generation quality is only one part. It can be broken down into four layers:

    1. Task planning: Decompose the overall goal into verifiable subtasks and determine execution order.
    2. Tool use: Select the right tool, construct correct parameters, and parse the returned results.
    3. State management: Across many turns, remember completed steps, known constraints, and past failures.
    4. Error recovery: When an error occurs, locate the cause and adjust the strategy instead of repeating the same operation.

    State management is the most commonly underestimated. Context windows are finite, and if key early information is not preserved through summarization or external storage, later decisions will drift from the original goal. A common engineering practice is to write the task plan, completed steps, and pending verification items into a dedicated state file rather than relying entirely on conversation history.

    2. Designing an Evaluation Framework

    A single pass rate cannot reflect long-horizon capability. A credible evaluation should cover at least the following dimensions:

    • Pass rate: Whether the final result meets the acceptance criteria.
    • Steps and latency: The number of interaction rounds and actual wall-clock time consumed.
    • Cost: Token consumption for input, output, and cache.
    • Stability: Variance in results when the same task runs multiple times.
    • Category bias: Score differences across task categories, used to identify uneven capabilities.

    The evaluation environment should be as close to real conditions as possible, including resource limits (memory, CPU, timeouts), real dependencies, and a reproducible initial state. If the initial state is inconsistent, the same model’s score can vary significantly.

    Below is a simplified example of evaluation result aggregation:

    1. from dataclasses import dataclass, field
    2. @dataclass
    3. class TaskResult:
    4. task_id: str
    5. category: str
    6. passed: bool
    7. steps: int
    8. wall_seconds: float
    9. input_tokens: int
    10. output_tokens: int
    11. cached_tokens: int = 0
    12. @dataclass
    13. class EvalReport:
    14. results: list[TaskResult] = field(default_factory=list)
    15. def pass_rate(self) -> float:
    16. if not self.results:
    17. return 0.0
    18. return sum(r.passed for r in self.results) / len(self.results)
    19. def median_steps(self) -> float:
    20. steps = sorted(r.steps for r in self.results)
    21. if not steps:
    22. return 0.0
    23. mid = len(steps) // 2
    24. return steps[mid] if len(steps) % 2 else (steps[mid - 1] + steps[mid]) / 2
    25. def pass_rate_by_category(self) -> dict[str, float]:
    26. groups: dict[str, list[bool]] = {}
    27. for r in self.results:
    28. groups.setdefault(r.category, []).append(r.passed)
    29. return {k: sum(v) / len(v) for k, v in groups.items()}

    Sample size must always be reported alongside results. With 100 tasks, for example, the standard error around a 65% pass rate is roughly 5 percentage points, so two models differing by only 1 point are nearly indistinguishable at that sample size. In addition, per-category summaries expose capability gaps better than an overall score — a model might excel at code generation tasks while clearly lagging on multi-file refactoring.

    3. Training: Scaling Post-Training and Reinforcement Learning

    Introducing reinforcement learning in the post-training stage is a common path to improving agent capability. The key is whether the reward signal is verifiable. For coding tasks, whether unit tests pass can serve as the reward; for tool-operation tasks, validation of the final system state can serve as the reward.

    As training expands from a few domains to a large number of downstream scenarios, the difficulty shifts from algorithms to engineering and data quality, mainly in three areas.

    Environment quality. Every training environment needs checks: Is the task description clear? Are the tests reliable? Is the initial state reproducible? If an environment contains shortcuts that can be exploited, the model may learn to “game” it — for example, modifying the tests themselves instead of fixing the code. This phenomenon is commonly called reward hacking.

    Reward design. Using only the final outcome as the reward makes the signal too sparse, leaving early decisions in long tasks without feedback. Adding process metrics can alleviate sparsity, but process metrics themselves can also be gamed. A sound approach is to keep process rewards aligned with final verification and audit them regularly.

    Training infrastructure. Long-sequence rollouts demand high throughput. Common engineering measures include asynchronous sampling, fast sandbox startup, priority-based task scheduling, and automatic isolation and logging of failed environments.

    Environment quality checks can be formalized as a fixed checklist: Do tests cover critical paths? Can randomness cause false judgments? Is resource usage within expectations? Can the environment run end-to-end without human intervention?

    4. Inference: Context, Caching, and Speed

    Context Length

    Longer context accommodates more code and history, but it brings two problems: inference cost grows with input length, and the model’s attention to information in the middle may degrade. In practice, systems typically combine retrieval, chunking, and summarization. For example, only file fragments relevant to the current step go into the context, while completed subtasks are compressed into brief conclusions.

    Prefix Caching

    Multi-turn agents repeatedly send the same system prompt and history prefix. If the serving side supports prefix caching, the cached portion of the input is usually much cheaper than the uncached portion. To improve the hit rate:

    • Keep the system prompt and tool definitions stable; do not insert timestamps or random fields that change on every request at the beginning.
    • Organize history in an append-only manner; avoid modifying existing content in the middle.
    • Use a fixed chunking scheme for long files so repeated requests can hit the cache.

    Speed and Cost

    Faster inference tiers usually come at a higher unit price or greater resource usage. The choice should depend on the task’s latency sensitivity. Interactive coding assistance values response speed, while overnight batch refactoring jobs value total cost.

    The cost of a single task can be estimated with the following formula:

    Cost = cached input volume × cached input price + uncached input volume × uncached input price + output volume × output price

    1. def estimate_cost(
    2. cached_in: int,
    3. miss_in: int,
    4. out: int,
    5. price_cached: float,
    6. price_miss: float,
    7. price_out: float,
    8. ) -> float:
    9. """All prices are per token; use values from your own billing or the official pricing page."""
    10. return cached_in * price_cached + miss_in * price_miss + out * price_out

    In multi-turn agents, each turn’s input contains all previous turns, so the cache hit rate often dominates total cost. When tracking costs, it is advisable to record the cache hit ratio per task category to surface problems in prefix design.

    5. Design Requirements for Managed Long-Running Environments

    Long-running agents need a stable execution framework. It must not only execute the operations the model outputs but also guarantee isolation, recoverability, and auditability. Core requirements include:

    • Sandbox isolation: Restrict filesystem access scope, enforce a network allowlist, and configure CPU, memory, and execution timeouts per task.
    • Checkpoints: Persist state after each completed step so that an interrupted process can resume from the most recent checkpoint instead of starting over.
    • Idempotency: Re-executing the same step should produce the same result. Operations such as deployments or notifications should first check whether they have already been completed.
    • Scheduling and orchestration: Support task queues, priorities, and dependencies among multiple agents.
    • Observability: Log every tool call’s parameters, return values, and latency for auditing and troubleshooting.
    • Human intervention: For high-risk operations such as deleting data, modifying permissions, or sending outbound messages, set pause points that wait for human confirmation.

    The following example shows execution logic with checkpoints and an approval gate:

    1. import json
    2. import pathlib
    3. def run_agent(task_id: str, steps: list[dict], state_dir: str = "./ckpt") -> dict:
    4. path = pathlib.Path(state_dir) / f"{task_id}.json"
    5. path.parent.mkdir(parents=True, exist_ok=True)
    6. state = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {"done": [], "log": []}
    7. for step in steps:
    8. name = step["name"]
    9. if name in state["done"]:
    10. continue # Idempotent: completed steps are not re-executed
    11. if step.get("risky") and not step.get("approved", False):
    12. state["log"].append({"step": name, "status": "awaiting_approval"})
    13. break # Pause when a high-risk step has not been approved
    14. result = step["run"]()
    15. state["log"].append({"step": name, "status": "ok", "result": str(result)[:500]})
    16. state["done"].append(name)
    17. path.write_text(json.dumps(state, ensure_ascii=False, indent=2), encoding="utf-8")
    18. return state

    In the example, the run field represents the actual execution function for that step. A real system also needs timeout control, error classification, and retry policies, distinguishing retryable errors from those requiring human handling.