Why AI-Generated Code Fails in Production: Building an Evidence Loop
AI can generate code at scale, but trust cannot come from the model's self-reported capability. This article explains how an evidence loop—anchored by end-to-end tests as a hard-to-game scoring standard, property-based tests for edge cases, and rule files plus hooks that turn past mistakes into enforced constraints—makes it possible for one engineer to reliably orchestrate dozens of parallel AI coding tasks. It also covers the two most common failure modes, flaky and slow tests, and a four-step rollout path from zero to scalable parallelism.
1. Where the Problem Starts: Why AI Output “Looks Right and Runs Wrong”
When a team building AI-assisted coding tools disclosed that roughly 90% of its internal code is written and cross-reviewed by AI, the question outsiders cared about most was not “can it write code” but “why would you trust it.” The answer is not romantic: trust does not come from the model’s self-declared capability, but from a repeatable, executable evidence system.
The bottleneck in traditional manual review is attention. When an engineer reads AI output line by line, their cognitive bandwidth covers only one or two parallel tasks, and review quality degrades quickly as the number of lines of code grows. When every change can be verified by automated evidence, however, the object of review shifts from “code text” to “passed/failed facts,” and one person can simultaneously orchestrate dozens of parallel tasks. This is the leverage effect of the evidence loop.
It is worth emphasizing that AI’s typical failure modes in coding differ from those of humans. It rarely writes code with syntax errors, but it often writes code that is “internally consistent yet does not match real constraints”: inconsistent field naming, careless handling of boundary conditions, and complete ignorance of existing implicit conventions. Such defects cannot be caught by code style checks; they can only be exposed by behavior-level verification.
2. The Core Scoring Standard: Why End-to-End Tests Are the Hardest to Game
Among the various forms of testing, if resources allow investment in only one, the highest priority is end-to-end (E2E) testing. There are three reasons.
First, it simulates the real user path. The test script advances according to the actual sequence of user operations: adding a product to the cart, going to checkout, submitting the order, and landing on the payment result page. A contract mismatch at any link in the entire chain causes failure, making it hard for AI to slip through by “just making a function return the expected value.”
Second, its verdict is binary. A feature either works end to end or it does not; there is no gray area of “partially correct.” By contrast, a unit test timeout often only throws a message like “waited more than 30 seconds,” which neither indicates where it got stuck nor distinguishes whether the environment was not ready, a selector failed, or an API returned an error.
Third, its diagnostic information density is high. A mature E2E framework preserves screenshots, DOM snapshots, and full execution traces on failure, and can directly point out “the checkout button is disabled because the inventory validation API returned an empty value.” For AI, this kind of information is an actionable fix instruction rather than a vague clue requiring a second round of reasoning.
A minimal executable example:
Scenario: A new user completes a full orderPreconditions: Test account logged in, cart is emptySteps:1. Search for a product and add it to the cart2. Go to the checkout page, assert the order amount equals the product unit price3. Submit the order, assert the payment success page appearsAssertion: Order status is paid, and inventory is decremented onceFailure evidence: Save screenshot + key API responses + execution trace
To make this mechanism truly work, AI needs to be granted environment access close to the real one: driving web pages in a browser extension, driving apps in a mobile emulator, driving clients in a desktop environment, or spinning up backend services and dependent middleware locally on demand. The greater the permissions, the more isolation boundaries are needed: use independent test tenants, disposable datasets, and restricted credential scopes to avoid validation behavior polluting real data.
An asset more upstream than test scripts is the feature map. It lists, in structured documentation, the operation paths of real users, key shortcuts, the expected behavior of each node, and the side effects that must not occur. This document plays two roles at once: the AI’s construction spec and the source of the scoring standard. Write the document clearly, and the AI’s rework rate drops significantly.
3. Complementary Tactics: Property-Based Tests Catch the Edge Cases “Nobody Thought Of”
E2E tests cover the main trunk, but outside the trunk there are plenty of extreme inputs that both humans and AI tend to overlook. The idea of property-based testing is this: instead of enumerating specific cases, declare an invariant that must always hold, then have the tool automatically generate massive random inputs and do its best to break the program.
Common invariants include:
- After serialization and then deserialization, the object must be equivalent to the original value;
- The account balance must never be negative under any sequence of inputs;
- The same data migration or cleaning logic must produce identical results whether run once or twice (idempotence);
- The optimized implementation must produce output identical to the original implementation for the same inputs (refactoring equivalence);
- Under any legal input, the combination of pagination parameters must not produce duplicate or missing records.
Pseudocode example:
property: balance after transfers of any amount sequence >= 0for 1000 random input sets:generate a random initial balance and transfer listperform the transfersassert balance >= 0if failed: automatically shrink to the minimal reproducible case and output it
The value of property-based testing lies in its lack of subjective bias. When humans write test cases, they unconsciously design around the models they already know, whereas random generators hit the combinations that “were never thought of.” In legacy system refactoring scenarios, the original spec documents are often already out of sync with the production implementation, and an equivalence property like “the old and new implementations produce identical output” is more reliable than any written spec.
4. Turning Experience into Guardrails: Rule Files and Hooks
AI keeps falling into the same pit over and over. When an error recurs, the right approach is not a manual reminder every time, but to solidify the constraint into the engineering structure:
- Write explicit prohibitions in the project’s rule description file, for example “never output users’ phone numbers, ID numbers, or raw tokens in any log or error message”;
- Set up hooks before commit and before execution to automatically run format checks, static scans, and sensitive-information detection, blocking the process when a violation is hit;
- Convert the retrospective conclusion of each production incident into a new automated check, so the guardrails thicken as the project evolves.
The essence of this step is to migrate “human memory” into “machine-enforced constraints,” so that increased parallelism does not come at the cost of quality.
5. Two Common Ways This Dies: Flakiness and Slowness
This system has two typical failure paths that must be avoided at the design stage.
The first is flaky tests. If test cases randomly fail due to timing, port contention, shared data, or jitter in external dependencies, AI quickly learns a shortcut: retry repeatedly until it happens to pass, instead of fixing the real defect. This pollutes both the quality signal and iteration efficiency. Countermeasures include: isolating test data per case with automatic generation and reclamation, using controllable test doubles for external dependencies, fixing random seeds, and putting flaky cases in a quarantine zone with a deadline for cleanup.
The second is tests that are too slow. Once the feedback cycle stretches to tens of minutes, the frequency of AI’s batch investigations drops sharply, and the cost of locating problems rises dramatically. Countermeasures include: layered execution (fast cases run on every change, the full chain runs before merge), parallel sharding, rerunning only the affected scope, and decoupling environment preparation from test execution.
A practical rule of thumb: only when feedback time is kept within a few minutes does AI’s autonomous fixing make economic sense; once it exceeds that, the proportion of human intervention quickly climbs back up, and parallel scheduling collapses accordingly.
6. Implementation Roadmap: From Zero to Scalable Parallelism
A four-step rollout is recommended:
- Pick one core user path, and fill in E2E cases plus failure evidence capture;
- Write the feature map, documenting operation paths, expected behavior, and forbidden side effects as AI input;
- Add property-based tests for core data structures and key algorithms, prioritizing amounts, inventory, permissions, and idempotence;
- Build a guardrail and metrics mechanism that tracks pass rate, average feedback time, the proportion of flaky cases, and the recurrence count of the same type of defect.
Among the metrics, “recurrence count of the same type of defect” is especially worth watching. It directly reflects whether experience has been successfully solidified into automated constraints; and if an improvement in pass rate comes with an increase in the number of retries, it means the AI is learning to circumvent rather than to fix.
7. Conclusion
The reliability of AI-written code has never been a promise made unilaterally by the model; it is a proof given by the engineering system. Using E2E tests as a scoring standard that is hard to game, property-based tests to fill the blind spots of human cognition, rule files and hooks to solidify lessons into enforced constraints, and strictly controlling test stability and feedback latency—these four things together form the prerequisite for “one person commanding dozens of parallel agents.” In a cloud environment equipped with general-purpose container platforms, log services, and monitoring and alerting capabilities, these guardrails can be further standardized, making quality evidence reusable, auditable infrastructure rather than a one-off project investment.
