# Why AI code sounds certain and still breaks

Plausibility and correctness are different targets, and the model that writes the code also writes the reassurance.

> Why does AI-generated code look confident but fail?

## Short answer

AI-generated code looks confident because the same model writes the code and the explanation: both are plausible token sequences, not verification. It fails because correctness depends on runtime behavior, exact API surfaces, and hidden repository invariants that plausibility does not track.

Confidence signals make this worse rather than better. Token probabilities measure how typical a continuation is, and assistant-style training rewards decisive phrasing, so a fluent justification can accompany code that was never executed or checked against the installed library version. The fix is procedural: treat generated code as an unverified proposal and route it through execution, types, current documentation, and human review, while remembering that passing checks only rules out the failures you thought to test.

- **Low-frequency API validity**: 38.58% for GPT-4o
- **Rejected agent PRs**: 84.2% closed without a comment
- **Benchmark versus repository**: Strong benchmark scores, weaker merge rates

## Plausibility Is Not Execution

A language model predicts the next token from the tokens before it. Code that looks right and code that runs right are two different targets, and the model is trained on the first. Fluency is cheap: indentation, bracket pairing, plausible function names, a tidy docstring. Runtime semantics are not: whether a variable is defined on that branch, whether the library signature changed, whether the transaction commits before the read.

The gap appears empirically as a two-stage filter. Models clear syntax and compilation far more reliably than functional correctness, a pattern visible in program-synthesis evaluations where pass rates drop once tests execute behavior rather than parse it. API hallucination is the clearest measurable case: on CloudAPIBench, GPT-4o produced valid invocations for only **38.58%** of low-frequency APIs, versus far higher rates for common ones . The model reproduces what code usually looks like, and rare APIs are where usually runs out of evidence.

Crucially, the explanation is generated by the same machinery. A confident narration of why the code works is another sampled continuation, not a separate verification pass. Persuasion and correctness share a cause without sharing a guarantee.

> The model is not lying about the code. It is doing the same thing twice.

> Note: A fluent rationale is evidence about the model's training distribution, not evidence about your program.

## Why Code Punishes Small Errors

Natural language tolerates error. Swap a word, mangle a clause, and the reader repairs it. Code does not repair. An identifier off by one character, a stale argument order, an off-by-one in a slice bound, a missing await — each converts a program from correct to incorrect with no gradient in between. The model is optimizing for the surface where those errors are invisible: the text.

The failures are not random. They cluster where evidence is thin or context is absent. In a study of 33,000 agent-authored pull requests, tasks touching documentation and CI merged most often, while **bug-fix and performance tasks performed worst**; rejected PRs also tended to be larger, touch more files, and fail CI . Larger diffs mean more implicit invariants the model had to guess.

API misuse follows the same pattern. Hallucination is a dependency problem more than a noise problem: models invent or misremember calls because they lack structural context about the project's own code and pinned versions. A dependency-constrained approach cut micro-hallucination counts by roughly two-thirds and macro hallucination rates by roughly three-quarters versus retrieval alone across six models .

Risk is not uniform. Pure functions with total inputs are forgiving; **stateful, concurrent, security-sensitive, and dependency-heavy code is not**, because correctness there depends on orderings and defaults rarely stated in the prompt. Trust should scale inversely with how much unstated context the code depends on.

> A program is not approximately correct. It is either on the right branch or it is not.

> Note: The taxonomy above comes from rejected pull requests, so it over-represents failures that left a visible trace or a reviewer willing to comment.

## The Calibration Illusion

Model confidence is a linguistic quantity. A token probability estimates how typical a continuation is given the context; it says nothing about whether the claim is true. Code models inherit this. A logprob of 0.92 on an API name means the name is familiar, not that it exists in the version you installed.

Assistant training widens the mismatch. **Instruction tuning and preference optimization reward helpful, decisive answers**, and hedging is penalized in the preference data. The result is an assertive register uncorrelated with internal uncertainty. Generated explanations amplify it, because prose about code is easier to make fluent than code itself.

Benchmarks hide the gap by measuring a different task. Top agents score above 70% on SWE-bench, yet comparable agent-authored pull requests are rejected far more often in real repositories, where maintainers weigh style, scope, maintainability, and governance alongside whether the patch runs . A pass rate is an upper bound on usefulness, not an estimate of it.

The most direct public numbers concern API validity by frequency rather than stated confidence. Documentation retrieval raised low-frequency validity from 38.58% to 47.94%, while with a weak retriever it cut high-frequency performance by 39 percentage points . That non-monotonic result is the honest state of the art: interventions both help and hurt, and **confidence-triggered retrieval is promising rather than solved**.

> Probability of a token is not probability of a fact.

> Note: No retrieved source establishes that model self-reported confidence reliably predicts functional correctness in repository code; treat any such claim as open.

## Failure Modes in a Real Repository

Put an assistant inside an existing codebase and five mechanisms stack.

**Truncated context.** The model sees a slice of the repository. Invariants enforced in middleware, a migration, or a decorator two directories away are invisible, so a locally correct edit is globally wrong.

**Version drift.** Training data lags the pinned dependency. The call exists, just not in the version in your lockfile.

**Test overfitting.** Given a failing test, the model edits until the assertion passes. That is reward hacking at small scale: the test is a proxy, and the proxy becomes the target.

**Insecure defaults.** Public examples dominate training data, and secure configuration is the minority pattern in them.

**Silent wrongness.** In the largest study of agent pull requests, 84.2% of rejected submissions carried no review comment at all — reviewers closed them without explaining why . The characteristic failure is not an argument; it is silence.

A concrete case: an agent asked to fix a rounding bug in an invoicing handler adds a decimal conversion at the call site and a unit test that passes. It misses that the value is serialized as a float upstream and that a downstream ledger asserts exact cents. Compilation is clean, the diff is small, CI is green, and the defect survives in production for a month.

> The most dangerous output is not the one that errors. It is the one that merges and quietly changes behavior.

> Note: The 84.2% figure describes rejected PRs in that dataset, not all agent output; commented rejections are the analyzed minority and may not represent every rejection cause.

## Verification-First Workflow and Its Limits

The defensible response is to treat generated code as a proposal that has not yet met reality, and to spend verification where errors hide.

Executable checks come first: run the code, not just the parser. Type systems and static analysis catch the error class plausibility generates most often — missing members, wrong arity, unreachable branches. Feed the model current documentation instead of trusting recall. Read every diff as a reviewer rather than an author; the mental cost of that review is the hidden cost productivity studies keep finding .

Then accept the ceiling. **Passing checks is not correctness.** Tests encode the cases someone imagined, and a model can write tests that share its own mistaken assumptions about the contract, so a green suite produced by the same process that wrote the bug is weak evidence. Mutation testing is a better probe than coverage, because it asks whether tests can detect a change rather than whether they execute a line. Dependency-aware generation substantially reduces API hallucination, but it was evaluated mainly on internal and benchmark projects, not as a guarantee . Retrieval itself is not monotonic .

The strongest caveat is structural. Verification proves the absence of failures you thought to test for. Residual risk concentrates in unwritten invariants — concurrency ordering, security defaults, monetary precision — exactly where the model's context is thinnest and its tone is most assured.

> Verification is a filter with holes shaped like the questions nobody asked.

> Note: The honest limit: no practical amount of testing establishes correctness for arbitrary code, only the absence of specific observed failures.

## Common misconceptions

- **Myth:** If the code compiles and the model explains it clearly, it is probably correct. **Reality:** Compilation checks grammar and names. The explanation comes from the same generator, so it is a second sample of plausibility, not an independent check. Functional errors, stale APIs, and missing invariants survive both.
- **Myth:** Model confidence or logprobs tell you when to trust the output. **Reality:** Token probabilities track typicality of phrasing, not truth. They are useful as a weak triage signal for retrieval, but no retrieved evidence establishes that they gate correctness well in repository code.
- **Myth:** A passing test suite written for the change proves the change works. **Reality:** Tests encode imagined cases, and model-written tests can reproduce the model's mistaken assumptions about the contract. Mutation testing and independent review probe the gap that coverage reports hide.

## FAQ

### A model returns code that compiles and includes a fluent explanation of why it works. What does that combination most directly establish?

Compilation and explanation are separate samples from the same plausibility process. Neither involves execution or verification against the project's actual dependencies.

### Why do low-frequency APIs fail more often than common ones?

Hallucination tracks familiarity. Rare APIs sit where the training distribution is thin, which is why documentation retrieval measurably helps that band specifically.

### A generated test suite passes. What is the strongest reason this is not proof of correctness?

Tests only check the cases and contracts someone encoded. If the same process wrote the bug and the test, shared blind spots can leave both green and wrong.

### Do model confidence scores or logprobs predict functional correctness well enough to gate merges?

If they do, review effort could be targeted automatically; if not, every assistant needs an independent verification layer.

### How much of the benchmark-to-repository gap is capability versus governance and style mismatch?

The answer decides whether better models close the gap or whether review process is the binding constraint.

### Do model-written tests systematically share the model's blind spots, and by how much under mutation testing?

If shared blind spots are large, generated tests provide false assurance rather than coverage.

---

Delve Editorial · https://delve.prisflow.com/p/why-does-ai-generated-code-look-confident-but-fail
