Model Selection for Coding Agents: Cost, Acceptance, and Failure Recovery
This article looks at how teams should choose models for coding agents by moving past benchmark scores and per-token prices to focus on what actually matters: proving the work is genuinely done. It frames the agent's task loop as authorization, execution, acceptance, failure recovery, and audit, then shows that task-level expected cost is driven far more by pass rate than by unit price, with a worked model and code to quantify it. It proposes routing tasks across four tiers using observable signals, details a three-layer acceptance gate and an acceptance-driven execution loop, and lays out failure recovery through sandboxed branching, structured failure feedback, budget guardrails, progressive delivery, and fast rollback. The conclusion: capability sets the ceiling, but the engineering system sets the floor.
Model Selection for Coding Agents: Cost, Acceptance, and Failure Recovery
Note: This article does not involve hands-on testing of any specific model. Everything here is based on public information, general engineering constraints, and the author’s judgment, and is intended to discuss how to put coding agents into practice.
1. Introduction: Models Start Competing for the “Deliverable Middle Ground”
A cloud vendor recently released a new reasoning model aimed at software engineering and multi-step tasks. The moment the news broke, the discussion quickly slid toward a few familiar questions: how much higher did it score, how much faster is it, and can it replace the current flagship. These questions aren’t wrong, but they dodge what actually matters: when a model can take on real work more frequently, who proves that it actually finished the job? And if it looks like it “succeeded” but the result is wrong, who is accountable?
My take is that the significance of this new model isn’t that it fills one more slot between the existing “high-frequency fast tier” and the “long-horizon deep tier.” What it really probes is the next curve in industry competition: no longer just comparing peak intelligence, but packing fairly strong reasoning into a workflow that can be executed repeatedly, verified against acceptance criteria, and run at a controllable cost. Judging by the public materials, it targets high-frequency production scenarios, was adapted from a long-horizon deep-tier model, and offers a unified window covering a fairly large context range. This positioning already tells us it aims at a link in software production where capability is deep enough yet also “cheap and frequent” enough.
This is attractive to coding agents, indie software developers, and in-house enterprise automation alike. At the same time, it pushes a long-overlooked problem to the front: if the acceptance system can’t keep up, cheaper automated execution can produce more expensive rework. Code is no longer a draft for humans to read. Once it is merged directly, deployed automatically, or used to change real system state unattended, every seemingly harmless difference can turn into a production incident, data corruption, or even a security breach.
I should state my position up front: a single model upgrade neither proves that general intelligence has arrived, nor exempts developers from responsibility for their systems’ side effects. What follows doesn’t care how much stronger some model got. It cares about one thing: after generation and execution, how the engineering system establishes verifiable trust in every step an agent takes.
2. Clarifying the Concepts: Generation, Agents, and the “Task Loop”
In everyday discussion, “AI that writes code” often gets lumped together, but from the standpoint of responsibility boundaries, they are completely different things.
| Concept | Core capability | Typical permission boundary | Main risk | Key control point |
|---|---|---|---|---|
| Generative AI (often grouped under AIGC) | Generates text, images, code, and other content | Outputs text; does not directly change the system | Inaccurate content, deviation from requirements | Human review of output |
| AI Agent | Under tool permissions, reads repos, calls APIs, runs commands, modifies system state | Can produce real side effects | Wrong edits, wrong deletions, privilege escalation, irreversible operations | Authorization, acceptance, rollback |
| AGI | General cross-domain understanding and autonomy | — | — | No accepted standard yet; out of scope for this article |
If someone searches “use AI to write code,” they get a snippet they can copy directly, wasting at most a few minutes reading it. But when you hand an agent a bug-fix task, it may decide on its own to change a dependency version, rewrite the build script, or run migration statements. The difference looks like “just a few more tools,” but in substance it determines three things:
- Is authorization needed? Is the artifact read-only, or does it have write access?
- Is acceptance needed? Does a human eyeball it, or does the system decide automatically?
- Is rollback needed? On error, must it be restored to the pre-change state?
From this we can distill the agent’s “task loop”: authorization → execution → acceptance → failure recovery → audit and archiving. How complete this loop is determines how much of a model’s “intelligence” can actually be converted into reliable output. The essence of coding-agent model selection is to pick, for each stage of the loop, a model whose capability matches the risk of the task.
3. Cost: Don’t Just Look at Unit Price, Calculate “Task-Level Expected Cost”
When selecting a model, developers tend to fixate on the per-token price. But in agent scenarios, unit price is only part of the cost. From dispatch to merge, the real spend on a task breaks into three layers.
1. Direct cost: per-round invocation and tool overhead
- Every round’s input includes the system prompt, tool definitions, task description, and all prior conversation and tool results from earlier rounds. Without a context compression or trimming mechanism, adding rounds makes cost grow roughly in proportion to the number of rounds.
- A large window lowers the risk of “context being truncated,” but if every round resends the entire history, the longer the context, the higher the input cost of each single call.
- Tool calls, code retrieval, and test execution all consume time and quota. Retrieval hit rate and whether the first-round localization is accurate directly determine how many rounds it takes.
2. Rework cost: failed retries and infinite loops
- A failed retry doesn’t just mean paying for one more call; it means one more round of tool execution and one more environment setup.
- Without a termination condition, the model may keep probing in a “modify → run → error → modify again” loop until it hits the budget cap.
3. Hidden cost: human fallback and incident price
- Artifacts that pass acceptance still need human review. If the model produces a large volume of patches that “look done but actually don’t pass,” reviewers burn a lot of attention on irrelevant diffs and over-engineering.
- Worse is discovering an error only after acceptance passes. At that point the rework cost already includes secondary defects introduced by the rework, plus the knock-on effects of merge, release, and rollback.
We can quantify this relationship with a simplified model. Let the per-round direct cost be C, the probability of passing acceptance on the first try in a single round be p, the maximum number of rounds be n, and human takeover after all rounds fail cost M. Then the expected cost is:
E = C × (1 + (1-p) + (1-p)^2 + ... + (1-p)^(n-1)) + (1-p)^n × M
Continuing with the task layering from the previous section, take n = 4, M = 200, and you get a few illustrative values:
| Tier / scenario | Per-round direct cost | Per-round pass rate | Expected rounds | Human takeover probability | Task-level expected cost |
|---|---|---|---|---|---|
| Deep tier | 1.0 (baseline) | 0.90 | 1.11 | 0.01% | ~1.1 |
| Deep tier | 1.0 (baseline) | 0.75 | 1.37 | 0.4% | ~2.2 |
| Fast tier (slightly more expensive overall) | 0.7 (30% cheaper) | 0.60 | 1.67 | 2.6% | ~6.3 |
| Fast tier (nearly free) | 0.1 (90% cheaper) | 0.80 | 1.25 | 0.16% | ~0.4 |
| Fast tier (nearly free) | 0.1 (90% cheaper) | 0.30 | 2.76 | 24% | ~48.3 |
These numbers make three points:
- Pass rate is a multiplier, not an addend. Saving 30% on unit price is undone the moment the pass rate drops from 0.90 to 0.60: the task-level expected cost actually climbs to roughly 5.7x.
- A big price cut can still be a net loss. Even if a single call is nearly free, when the pass rate drops to 0.30, most tasks still end in human takeover, and the expected cost is more than 40 times that of the deep tier.
- The premise is that “failure can be detected.” The table above assumes every failure gets caught in time by acceptance. If errors pass acceptance and flow into downstream stages, the cost can no longer be estimated with this formula.
In practice, you can embed this logic directly into a task scheduler with a small function:
from dataclasses import dataclass@dataclass(frozen=True)class Tier:unit_cost: float # Per-round direct cost, in units of the baseline tierpass_rate: float # Per-round pass rate, from offline eval or post-launch statsmax_attempts: int = 4human_cost: float = 200 # Fallback cost when all attempts fail, same unit as baselinedef expected_cost(tier: Tier) -> float:"""Compute the expected cost of a single task so hidden costs factor into the decision."""fail = 1.0expected = 0.0for _ in range(tier.max_attempts):expected += fail * tier.unit_cost # probability round k runs × cost per roundfail *= 1.0 - tier.pass_ratereturn expected + fail * tier.human_cost # human takeover after all attempts failif __name__ == "__main__":# Calibrate pass_rate and human_cost against real historical tasks before decidingprint(expected_cost(Tier(unit_cost=0.7, pass_rate=0.60))) # 6.3print(expected_cost(Tier(unit_cost=1.0, pass_rate=0.75))) # 2.18
This function can also be used in reverse: given a tier’s price, you can solve for the break-even pass rate and use it as the basis for “only using the low tier on tasks with a high pass rate.”
A more complete approach wires the cost breakdown into a “logging service + monitoring and alerting” setup: record per-task, per-round token consumption, tool calls, and wall-clock time keyed by task ID; aggregate pass rate and average rounds by task type; and set thresholds on task-cost P95, daily cumulative cost, and failure rate. Once cost is observable and attributable, model selection is no longer a matter of gut feeling. Basic capabilities common in the cloud—object storage, message queues, container platforms, and the like—can respectively handle retaining task artifacts, decoupling the task queue, and isolating the execution environment, providing the underlying support for this system.
4. Task Tiering: Match Different Complexity to Different Capability
The cost model answers “should we use it,” while task tiering answers “which tier.” I suggest dividing tasks roughly into four layers:
| Layer | Task characteristics | Recommended tier | Acceptance method | Autonomous retry allowed | Autonomy level |
|---|---|---|---|---|---|
| L1 Mechanical | Renaming, formatting, checklist-based bulk changes | High-frequency fast tier | Static checks + relevant tests | Yes (up to 2 times) | Fully automated |
| L2 Bug fix / local refactor | Clear reproduction and expected behavior | Balanced tier | New regression tests + all existing tests green | Yes (up to 4 times) | Automated, with human spot-checks |
| L3 Cross-module refactor | Affects multiple modules or public interfaces | Balanced/deep tier | Full tests + behavior metric comparison | Limited (with failure summary) | Plan first, then execute, human review |
| L4 High-risk / uncertain | Touches permissions, funds, data migration, etc. | Deep tier or no automation | Full tests + two-person review + canary | No | Human-agent co-review |
The key to tiering is that routing must rely on observable signals, not subjective feelings. Number of files changed, whether a public interface is touched, whether a reproducible case exists, failure history, and whether a path is high-risk can all be extracted automatically from the requirement description and repo metadata:
from enum import Enumclass Layer(Enum):L1 = "L1"L2 = "L2"L3 = "L3"L4 = "L4"def route_layer(files: int, touches_public_api: bool,has_repro_case: bool, sensitive: bool) -> Layer:"""Route tasks by objective features, avoiding subjective difficulty judgments."""if sensitive: # high-risk task: keep a human gate no matter how capablereturn Layer.L4if files > 8 or touches_public_api: # broad impact: propose a plan first, then executereturn Layer.L3if has_repro_case: # clear reproduction: run the bug-fix flowreturn Layer.L2return Layer.L1 # everything else is treated as mechanical change
Beyond routing, you also need budget guardrails:
- Set a per-task token cap, max rounds, wall-clock timeout, and max files changed.
- The moment one is triggered, stop execution immediately and hand off to a human.
Any round’s diff that greatly exceeds the expected scope (for example, adding files that weren’t requested) should likewise be flagged as an anomaly on the spot. Guardrails aren’t about limiting the model’s capability; they prevent it from burning cost and time in the wrong direction when no one is watching.
5. Acceptance: Turning “It’s Done” into an Executable Decision
In the agent paradigm, acceptance isn’t an optional add-on; it’s a core component of the system. The model generates candidate solutions; acceptance decides whether to accept them. Once acceptance is missing or exists in name only, the system degrades into an uncontrollable code-modifying machine.
1. Three-layer gates
| Layer | Content | Trigger timing | Handling on failure |
|---|---|---|---|
| Static acceptance | Compile, type check, static analysis, format check | After each change | Structured errors returned, auto-retry |
| Behavior acceptance | Unit tests, regression tests, new targeted cases, API contract validation | After static acceptance passes | Failed cases returned, auto-retry or escalate |
| Product acceptance | Diff review, metric comparison (performance, memory, coverage), human review | After behavior acceptance passes | Returned for changes or bounced to a human |
The three-layer design follows two principles:
- Cheap first, expensive later. Static checks usually take only seconds, so they belong at the front, blocking large volumes of low-quality patches before the costly steps.
- The earlier you catch it, the lower the price. The later a defect is intercepted, the higher its fix cost, which aligns with the software-engineering consensus that “defect cost rises as the phase advances.”
2. Let acceptance drive execution
A more mature approach is acceptance-driven execution, similar to the “red-green-refactor” loop in test-driven development, except each round of the loop is performed by an agent:
- Write the failing test first: The acceptance layer prepares tests that reproduce the problem and clearly express the expected behavior. At this point the tests must fail (red).
- Constrain the change scope: The task description spells out the directories that may be changed, the files and public interfaces that must not be touched, and any performance or compatibility metrics. These constrain both the model’s behavior and the later review.
- Let the agent iterate to green: The agent repeatedly modifies code in a sandbox until all acceptance passes.
- Acceptance decides: An independent acceptance layer (not the model’s own self-report) decides whether to accept, preventing “the model grading its own work.”
A minimal acceptance-driven loop looks like this:
from dataclasses import dataclass@dataclassclass Verdict:ok: boolsummary: str # Structured failure summary: failed cases, error locations, key logsfailed_checks: list # Names of gates that didn't pass, to route by failure typedef acceptance_driven(agent, workspace, task) -> Verdict:# 1) Acceptance layer writes tests first: they must all fail on the current implementation,# otherwise the cases can't expose the problemfailing = workspace.run_tests(task.acceptance_tests)assert failing and not failing.passed, "acceptance cases failed to reproduce the issue"# 2) Constrained iteration: the agent can only change files inside the workspace and allow-listfor _ in range(task.max_attempts):workspace.reset_to(task.baseline) # each round starts from a clean baselineagent.apply(task) # apply changes, no access to external interfacesresult = workspace.run_checks(task) # static + behavior acceptanceif result.ok:return resulttask = task.with_feedback(result) # inject structured failure info into next roundreturn Verdict(ok=False, summary="exceeded max attempts", failed_checks=["budget"])
3. Acceptance tests are written by people, not by the model itself
If the acceptance cases are also generated by the model, you get a closed loop of “setting the questions and answering them”: the model is likely to write assertions that its own implementation just happens to pass, or to miss edge cases. Acceptance cases should be written by developers or at least confirmed by a human, and reviewed separately from the changes the model submits. This may look like more upfront effort, but it actually moves the review cost forward to the cheapest possible position.
4. Expose “misjudgments”
The acceptance system itself can be wrong—cases that don’t cover an edge, assertions that are too weak, a flaky test environment. You can test it with three low-cost methods:
- Mutation testing: Make small changes to existing code (flip a comparison direction, drop a null check, and so on). If the relevant cases still all pass, an acceptance blind spot exists.
- Reinjecting historical defects: Reintroduce already-fixed historical defects as patches and see whether acceptance catches them.
- Post-mortem of failure samples: For any problem discovered only after it reached production, add an acceptance case.
6. Failure Recovery: Branching Execution, Rollback, and Escalation
In distributed systems, retry is the norm, but unconstrained retry only amplifies failures. Agent failures fall into roughly five categories, each needing a different recovery strategy:
| Failure type | Typical manifestation | Recovery strategy |
|---|---|---|
| Acceptance failure (functional) | Tests fail, behavior doesn’t match expectations | Inject failure summary, auto-retry; escalate after repeated failures |
| Acceptance failure (quality) | Over-engineering, unrelated changes, performance regression | Reject and roll back, reduce task granularity |
| Destructive failure | Deletes files, rewrites config, pollutes shared resources | Sandbox isolation + operation allow-list, immediate rollback |
| Runaway loop | Repeatedly modifies the same spot, round count spikes | Budget guardrail force-terminates, hand off to a human |
| Silent failure | Passes acceptance but the result is wrong | Progressive delivery + monitoring alerts + fast rollback |
The recovery mechanism can be summarized in four points:
Every attempt is a “short transaction.”
- The agent runs in an isolated sandbox or branch and cannot write directly to the main branch.
- Each attempt starts from a clean baseline; a failed workspace is discarded entirely, avoiding the “messier with every change” spiral.
- Workspace snapshots, execution logs, and failed cases are archived together for traceability.
Failure information must be returned in structured form.
- What comes back isn’t a bare “it failed,” but the failed case names, error locations, and key log snippets.
- Only then can the agent make a targeted change instead of blindly retrying.
- Repeated failure on the same case N times often means the task description itself is flawed; escalate to a human promptly rather than retrying endlessly.
Route by failure type and allow downgrading.
- Syntax or type errors can go to a faster tier to fix.
- Logic or algorithm problems should escalate to a stronger tier, not downgrade.
- The recovery strategy itself should be layered:
- Small, frequent steps: Commit small changes frequently and keep several green baselines.
- Feature flags: New, unverified behavior is off by default and can be switched off anytime.
- Progressive delivery: Canary first, observe, then roll out fully.
- Fast rollback: Keep the last verified version and switch back with one click on anomalies.
When everything fails, a human takes over instead of grinding on.
- The agent should hand off with “task context + attempted solutions + failure evidence” packaged together.
- When a human takes over, they see complete diagnostic material, not a half-finished codebase.
Illustrative code:
from dataclasses import dataclass@dataclassclass Outcome:ok: boolsummary: strattempts: intdef recover(agent, task, workspace, reviewer, max_attempts=4):for attempt in range(1, max_attempts + 1):workspace.reset() # start from baseline; discard everything on failuretry:agent.apply(task) # execute in sandbox, no access to external stateresult = workspace.accept(task) # decided by acceptance layer, not model self-reportexcept (TimeoutError, BudgetExceeded): # timeout or over budget: terminate immediatelyreturn Outcome(False, "execution timed out or exceeded budget", attempt)if result.ok:return Outcome(True, result.summary, attempt)# inject structured failure info to avoid blind retriestask = task.with_feedback(result.failed_checks, result.summary)if attempt >= 2 and same_failure(result, attempt): # same failure repeatedbreakreturn reviewer.take_over(task, evidence=workspace.archive()) # hand off to human with full evidence
Beyond this, the recovery system also needs observability as support. Logging every tool call and decision point via a logging service, and tracking success rate, average rounds, rollback count, and budget-trigger count via monitoring and alerting, is what turns “failure recovery” from a slogan into a measurable, optimizable capability.
7. Conclusion: Capability Sets the Ceiling, the Engineering System Sets the Floor
Back to the original question: the significance of a new model isn’t how much higher it scores, but how far it pushes the boundary of what “deliverable” means. The stronger the reasoning and the more frequent the execution, the more the engineering system must be able to absorb its side effects. For teams preparing to pay for or scale up coding agents, here is my advice:
- Calculate expected cost first, then look at unit price. Put pass rate, retry limits, and human fallback cost into the same formula. A cheap model with a low pass rate often turns out to be the most expensive.
- Route by task tier. Mechanical tasks can be confidently handed to the fast tier; high-risk tasks must keep a human gate, and routing should be based on objective signals.
- Acceptance comes before execution. Tests written by people, verdicts made by the system, and the three gates—static, behavior, product—escalating layer by layer, so that every “it’s done” has evidence behind it.
- Failure must be recoverable. Sandbox isolation, structured failure feedback, budget guardrails, progressive delivery, and fast rollback are all indispensable.
- Make cost, acceptance, and recovery one data loop. Only when logs, monitoring, and post-mortems are connected will model selection turn from a one-off “try it out” decision into a sustainably optimizable engineering capability.
I want to stress again: without hands-on testing, every conclusion here is just a hypothesis. Whether the new model is worth putting into production ultimately has to be validated by your own team with real tasks, real acceptance standards, and real budgets. And before that validation, fixing your acceptance and recovery systems first is always the safer choice.
