How to Scientifically Evaluate Post-Trained Code Agents

    Code-specialized variants of large models are easy to misjudge when measured with generic benchmarks. This article explains how code-agent post-training works, why single-point metrics like pass@1 can mislead, and how to build a reproducible four-layer evaluation pipeline that captures end-to-end engineering delivery. It covers the data and reward mechanics behind post-training, a metrics framework spanning both correctness and process cost, a sample configuration-and-code pipeline, seven common evaluation pitfalls, and a practical path from evaluation to production.

    1. Start with the Premise: A Domain Suffix Signals Capability Specialization, Not a New Architecture

    Over the past couple of years, coding-focused large models have shown a clear naming pattern: on top of the same base generation, dedicated variants for code scenarios appear, usually distinguished by a domain suffix. These variants do not replace the core architecture. The sparse mixture-of-experts (MoE) layer structure, routing strategy, and attention implementation all stay essentially unchanged. The real changes are concentrated in two areas: post-training data composition and optimization objective design.

    Understanding this is the starting point for understanding both the benefits and the limits of these variants. Training a new base from scratch is extremely expensive and takes months; a general-purpose base has already accumulated solid semantic understanding, commonsense reasoning, and code-syntax priors. So directing further resources toward “code-agent-specific post-training” is fundamentally about converging the model’s behavioral distribution in three directions within an existing representation space:

    • More reliable format contracts: strictly following function-call signatures, structured output schemas, and patch-format conventions;
    • Greater endurance on long chains: staying on-task across dozens of tool interactions without dropping the goal, repeating ineffective actions, or recovering from failures through self-correction;
    • Higher engineering completion rates: going beyond generating code snippets to reading repository structure, locating files, making cross-file changes, and getting verification to pass.

    For this reason, evaluating such models with a ruler built for “completion accuracy” or “public function-level benchmark scores” will systematically underestimate or misjudge their true value. What really needs to be evaluated is end-to-end delivery capability within a realistic engineering loop.

    2. The Technical Mechanism: What Post-Training Actually Changes

    2.1 The Data Distribution Shifts from “Corpus” to “Trajectory”

    General pre-training data is mostly static text. The core asset of code-agent post-training, by contrast, is the interaction trajectory. A high-quality trajectory includes the task description, environment state, tool calls and their returns, the model’s intermediate reasoning, the final patch, and the verification result. This kind of data carries a causal chain, letting the model learn strategic behavior—when to retrieve, when to run tests, how to roll back on failure—rather than just syntactic continuation.

    2.2 Stacking Supervised Fine-Tuning with Verifiable Rewards

    A common engineering practice is to first run trajectory-level supervised fine-tuning to establish basic tool-use habits, then introduce reinforcement learning with verifiable signals as rewards. Software engineering happens to have natural verifiability: whether unit tests pass, whether static checks are clean, whether the build succeeds. These are objective, automatically determinable reward sources that are hard to fool with surface patterns. This is one reason the code domain shows the clearest post-training gains.

    2.3 Long Context and Externalized State

    The most common cause of failure on long tasks is not “not knowing how to write code” but context degradation: early instructions get buried, irrelevant logs crowd the window, and repeatedly reading and writing the same file creates redundancy. A mature agent approach does not rely on simply enlarging the window; it pairs this with state externalization—writing the task checklist, already-modified files, and ruled-out hypotheses into external structured storage, and injecting only the necessary slice each turn. When evaluating, you must distinguish whether the capability gain comes from the model itself or from the surrounding engineering scaffolding.

    3. Evaluation Framework: Read Capability Boundaries in Four Layers

    A single score cannot characterize agent capability. It is better to divide evaluation into four layers on a difficulty ladder, exposing weaknesses layer by layer.

    L1 — Expression- and function-level generation. Assess basic syntactic correctness, edge-case handling, and adherence to types and interfaces. This layer is largely saturated with low marginal discrimination, making it suitable as a regression guardrail rather than a basis for model selection.

    L2 — File- and module-level understanding. Provide several related files and ask the model to complete a local refactor or feature addition. The focus is on comprehension of cross-file dependencies, whether callers are updated in sync, and whether implicit breaking changes are introduced.

    L3 — Repository-level bug fixing. Provide an issue description and a code snapshot, and ask the model to autonomously locate the problem, make changes, and pass hidden tests. This layer is closest to the shape of a real ticket and has the highest discrimination.

    L4 — Long-task, end-to-end agent. Give no explicit fix, only a goal (for example, “add exception handling to a module and raise test coverage to a given threshold”), and let the model plan, retrieve, execute, verify, and iterate on its own. This layer tests autonomy and endurance, and is what the phrase “engineering task completion rate” truly refers to.

    Every layer should pin a fixed code snapshot (ideally locked to a specific commit hash), dependency versions, and container image, so results are reproducible across models and over time.

    4. Metric Design: From Single-Point Accuracy to Long-Task Completion

    4.1 Correctness: Use an Unbiased Estimator Instead of a Single Sample

    Model output is stochastic, so a single sample is not statistically meaningful. The common practice is to sample $n$ times per case, count the passes $c$, and compute the pass probability with an unbiased estimator:

    $\text{pass}@k = 1 - \frac{\binom{n-c}{k}}{\binom{n}{k}}$

    Report both pass@1 (usability) and pass@10 (potential ceiling). A large gap between the two usually points to problems in the sampling strategy or prompt design rather than model capability.

    4.2 Process Efficiency: The Hidden Cost in Agent Scenarios

    For end-to-end tasks, completion rate must be read together with process cost; otherwise it is easy to be misled by “frantic retries that farm the pass rate.” At minimum, record:

    Metric Meaning Warning signal
    Task completion rate Proportion judged as passing by the verifier —
    Average interaction turns Rounds needed to reach the goal Re-reading the same file
    Invalid edit rate Share of edits rejected by the verifier or format check Poor patch-format compliance
    Tool-call failure rate Share of calls that error out or return empty Problems in the environment or retrieval implementation
    Tokens consumed per task Total end-to-end input + output Missing context management
    Average latency Wall-clock time, including environment startup Sandbox or dependency-pull bottleneck

    4.3 The Long-Task Decay Curve

    Plotting “task completion rate” against “allowed interaction turns” on the x-axis makes the model’s effective endurance visible at a glance. A curve that tops out early signals saturated capability; a curve that keeps rising slowly indicates the ability to push forward over long chains; a curve that rises and then falls signals goal drift or context contamination. This curve guides production configuration—such as whether to introduce an external task checklist and context compression—better than any single-point score.

    5. A Sketch of a Reproducible Evaluation Pipeline

    The key to an evaluation system is not model invocation but environment isolation and objective verification. The following is an illustrative structure.

    Cases are described with declarative configuration, decoupling “input, constraints, verification method” from execution logic:

    1. # cases/l3_fix_order_timeout.yaml
    2. id: l3_fix_order_timeout_001
    3. layer: L3 # L1 completion / L2 repo-level / L3 bug fix / L4 long task
    4. repo_snapshot: "9f2c1a" # Fixed code snapshot to ensure cross-model comparability
    5. context_files:
    6. - src/service/order.py
    7. - tests/test_order.py
    8. prompt_template: prompts/issue.md
    9. verifier:
    10. type: unit_test # Objective signal, no human or model self-assessment
    11. command: "run-unit-tests tests/test_order.py"
    12. forbid_files: [src/api/open.py] # Out-of-bounds edits are scored as failures
    13. budgets:
    14. max_turns: 30
    15. max_tokens: 400000
    16. sampling:
    17. n: 5
    18. temperature: 0.2

    The execution side emphasizes using a fresh environment for every sample, avoiding state residue between cases:

    1. def run_case(case, agent, sandbox):
    2. passed, turns, tokens = [], [], []
    3. invalid_edits = tool_errors = 0
    4. for _ in range(case.sampling["n"]):
    5. env = sandbox.create(case.repo_snapshot) # Fresh sandbox each time to eliminate state contamination
    6. try:
    7. transcript = agent.run(
    8. prompt=case.render_prompt(),
    9. env=env,
    10. max_turns=case.budgets["max_turns"],
    11. temperature=case.sampling["temperature"],
    12. )
    13. ok = env.verify(case.verifier) and not env.touched_forbidden(case)
    14. passed.append(1.0 if ok else 0.0)
    15. turns.append(len(transcript.steps))
    16. tokens.append(sum(s.usage.total_tokens for s in transcript.steps))
    17. invalid_edits += sum(1 for s in transcript.steps if s.edit_rejected)
    18. tool_errors += sum(1 for s in transcript.steps if s.tool_error)
    19. finally:
    20. env.destroy() # Reclaim resources whether it succeeds or fails
    21. total_steps = max(sum(turns), 1)
    22. return {
    23. "case_id": case.case_id,
    24. "pass_rate": sum(passed) / len(passed),
    25. "mean_turns": sum(turns) / len(turns),
    26. "mean_tokens": sum(tokens) / len(tokens),
    27. "invalid_edit_rate": invalid_edits / total_steps,
    28. "tool_error_rate": tool_errors / total_steps,
    29. }

    On top of this foundation, you can rely on general-purpose capabilities from a public cloud—container platforms, object storage, logging services, and monitoring/alerting—to handle sandbox orchestration, case and result archiving, execution-log retention, and dashboards. For example, general-purpose container and logging capabilities from a provider such as Baidu AI Cloud can be used to stand up the evaluation environment, giving evaluation itself engineering properties that are repeatable, auditable, and continuously improvable.

    6. Seven High-Frequency Evaluation Pitfalls

    1. Benchmark data contamination. If a public evaluation set has already entered the training corpus, its scores lose discriminative power. Use a self-built, private, continuously updated case set, and manage new cases in isolation.
    2. Spurious differences from inconsistent configuration. A difference in any of sampling temperature, maximum turns, system prompt, retrieval-tool implementation, or dependency versions makes results incomparable. All configuration must be archived along with the results.
    3. Watching only for passes, not for out-of-bounds behavior. Editing files that should not be touched, deleting assertions, or marking tests as skipped—these “cheating passes” must be caught through boundary constraints and diff review.
    4. Confusing model capability with scaffolding capability. If swapping the retriever or prompt template yields a large score jump, the gain should be attributed to systems engineering, not to the model.
    5. Ignoring variance. With small samples, a 2% difference often falls within the noise band; report confidence intervals across repeated runs.
    6. Distorted case distribution. If the evaluation set skews toward short files, it will overestimate production performance. The distribution of languages, repository sizes, and domains in the cases should resemble real codebases.
    7. Replacing continuous monitoring with one-off evaluation. Capability can regress after a model or environment update; evaluation must be part of an ongoing pipeline rather than a project-based activity.

    7. From Evaluation to Production: A Rollout Path and Cost Governance

    Enter by risk tier. Start by building trust in scenarios where errors are easy to spot and easy to roll back: test-code generation, comment and documentation completion, local refactor suggestions, and log/error attribution. Once the reliability of verifiers is proven, gradually open up to bug fixing and feature development.

    Treat verifiers as first-class citizens. The reliability ceiling of agent scenarios is determined by automated verification. Package unit tests, static checks, builds, and security scans into a standardized gate; model output must pass the gate before it reaches human review. Humans then review only whether the “design intent matches,” not syntax errors line by line.

    Control cost with tiered routing. The vast majority of requests are low-cost requests; handle them with the most economical model that is good enough, and reserve high-cost long-chain reasoning for genuinely complex tasks:

    1. def route(request):
    2. if request.kind in ("inline_completion", "comment", "test_generation"):
    3. return TIER_SMALL # Local completion and generation: prioritize latency and unit cost
    4. if request.kind in ("repo_issue", "cross_file_refactor", "long_task"):
    5. return TIER_LARGE # Requires long-chain planning and multiple tool calls
    6. return TIER_LARGE

    Combined with context trimming (injecting only relevant file slices), result caching, and concurrency limits, this can reduce overall cost without a significant loss in completion rate.

    Security boundaries and compliance. Be explicit about which code, logs, and internal interfaces may enter the model context. On the inference-service side, adhere to the principle of least privilege and keep tool execution within a reclaimable sandbox. Retain audit logs of complete interaction trajectories to support post-hoc review and accountability.

    8. Selection Checklist and Conclusion

    When evaluating these “code-specialized” models, fix the decision criteria as a quantifiable checklist:

    • On a self-built private set, pass@1 and pass@10 at the L3/L4 layers, with confidence intervals;
    • A cost-performance curve combining completion rate, average turns, and token consumption;
    • The decay shape of long-task completion rate as turns increase;
    • Compliance rates for structured output and patch format, along with the invalid edit rate;
    • The effective utilization of context length at realistic repository scale, rather than the nominal upper limit;
    • Whether the deployment form and data boundaries meet compliance requirements;
    • Whether there is a continuously evolving evaluation pipeline that can support regression monitoring.

    The conclusion is clear: code-agent-specific post-training is currently one of the most cost-effective paths to acquiring capability. Without rebuilding a base model, it turns general intelligence into deliverable engineering capability. But its benefits depend heavily on the surrounding engineering system—verifiers, sandboxes, context management, and tiered routing are all indispensable. So instead of arguing over which version number scores higher, it is better to first build up a self-owned evaluation set and production gates. The ability to evaluate is itself the asset most worth investing in for long-term technology selection.