AI-Generated Code Quality: What to Check Before It Reaches Production
By Alvi Lika, Founder, Soatech
· · 9 min read
A practical release review for AI-assisted features: permissions tested with two accounts, model output treated as a proposal, deliberate retries and a small evidence record.
A proposal generator can look finished while saving a draft against the wrong customer account. A payment flow can pass every demo and still create two invoices when the same request arrives twice. Neither problem shows up in a screenshot, and both belong in the release review.
Whether the code came from an assistant or from a person typing, the useful question is the same: what happens when the request, the model or an external service behaves differently from the happy path? AI assistance changes how quickly code appears, and so how much unreviewed code can pile up. It does not change what "ready for real customers" means.
There is published evidence that the review step matters. In Veracode's 2025 GenAI Code Security Report, which covered 80 coding tasks across more than 100 models, generated code introduced an OWASP Top 10 vulnerability in 45% of cases. Larger models did not perform significantly better than smaller ones. That is a benchmark of isolated tasks, not a measurement of any particular codebase, but it is a fair reason not to treat "it runs" as "it is safe".
What follows is a review you can run on a single feature. The two code examples are simplified, and both pass the tests shown on Node.js 24 using its built-in test runner and TypeScript type stripping.
Start with the action you cannot afford to get wrong
For a feature that turns a client brief into a proposal, the expensive failures might be sending a document with the wrong price, showing one customer another customer's history, or treating a draft as an accepted agreement.
Write those failures down before you read individual files. They tell you where to spend review time. A polished loading state matters; an authorization boundary matters more.
Then give each important action an acceptance condition you can test. "The proposal page works" is hard to test. "A member of account A cannot fetch, edit or send account B's proposal, even with its ID" is not.
Test permissions with a second account
A successful test as the owner proves little about isolation. Create two test accounts with different permissions in a staging environment. Try the same operation from both, through the routes the application actually uses.
Check reads as well as writes. A list page may filter correctly while an export, a search endpoint, a file download or a background job does not. In a framework like Next.js, Server Actions and Route Handlers are public endpoints, and the official guidance is to check authorization close to the data rather than relying on a redirect.
If you use PostgreSQL row-level security, verify which role runs each query. Table owners normally bypass policies, and so do superusers and roles with BYPASSRLS (PostgreSQL docs). Enabling RLS is part of the design. It does not prove that every code path goes through it. The Supabase RLS article has a complete two-account script.
Record which roles and paths you tested. That record is more useful to the next reviewer than a statement that "the database is secure".
Treat model output as a proposal, not an instruction
Suppose a model returns a customer, a currency, a delivery date and some line items. Constraining the response with a JSON schema is worth doing, but valid JSON only tells you the response can be parsed. It does not tell you the values are acceptable:
- Does the referenced customer belong to the current account?
- Is the currency one you support?
- Can the date be in the past?
- Do the line items add up to the total?
- Is the model allowed to change a price a person has already approved?
Keep those rules in application code, where they are enforced every time, rather than in the prompt, where they are only requested:
// draft-check.ts (simplified)
type LineItem = { description: string; amountCents: number };
type ProposedDraft = {
customerId: string;
currency: string;
deliveryDate: string; // ISO date, e.g. "2026-12-01"
lineItems: LineItem[];
totalCents: number;
};
type Context = {
accountCustomerIds: Set<string>; // customers that belong to the current account
supportedCurrencies: Set<string>;
approvedTotalCents?: number; // set once a person has approved a price
today: string; // injected so the check is testable
};
export type Verdict =
| { status: "ready_for_review"; draft: ProposedDraft }
| { status: "needs_attention"; issues: string[] };
export function checkDraft(draft: ProposedDraft, ctx: Context): Verdict {
const issues: string[] = [];
if (!ctx.accountCustomerIds.has(draft.customerId)) issues.push("customer does not belong to this account");
if (!ctx.supportedCurrencies.has(draft.currency)) issues.push(`unsupported currency: ${draft.currency}`);
if (draft.deliveryDate < ctx.today) issues.push("delivery date is in the past");
if (draft.lineItems.length === 0) issues.push("no line items");
if (draft.lineItems.some((i) => !Number.isInteger(i.amountCents) || i.amountCents < 0)) {
issues.push("line item amounts must be non-negative whole cents");
}
const sum = draft.lineItems.reduce((total, i) => total + i.amountCents, 0);
if (sum !== draft.totalCents) issues.push(`total ${draft.totalCents} does not equal line items ${sum}`);
if (ctx.approvedTotalCents !== undefined && draft.totalCents !== ctx.approvedTotalCents) {
issues.push("total differs from the price a person already approved");
}
return issues.length === 0 ? { status: "ready_for_review", draft } : { status: "needs_attention", issues };
}
Note the two outcomes. Even a draft that passes every check goes to ready_for_review, not straight to the customer. A draft that fails goes to a person with the reasons attached. It is never quietly "fixed" by inventing a missing value.
The tests read like the acceptance conditions above:
// draft-check.test.ts (run with: node --test)
import { test } from "node:test";
import assert from "node:assert/strict";
import { checkDraft } from "./draft-check.ts";
const ctx = { accountCustomerIds: new Set(["cus_a1"]), supportedCurrencies: new Set(["EUR"]), today: "2026-11-07" };
const good = {
customerId: "cus_a1", currency: "EUR", deliveryDate: "2026-12-01",
lineItems: [{ description: "Discovery", amountCents: 150000 }], totalCents: 150000,
};
test("valid JSON with another account's customer is held", () => {
assert.equal(checkDraft({ ...good, customerId: "cus_b9" }, ctx).status, "needs_attention");
});
test("the model cannot change a price a person already approved", () => {
const changed = { ...good, totalCents: 160000, lineItems: [{ description: "Discovery", amountCents: 160000 }] };
assert.equal(checkDraft(changed, { ...ctx, approvedTotalCents: 150000 }).status, "needs_attention");
});
For a document workflow, keep three states apart: extracted information, an editable draft and an approved document. Generating text should never quietly grant permission to send it or to collect payment. Soatech's own product, Wintura, is built this way (the stages and the code behind each). Commercial conflicts such as a deadline that cannot be met are stored as advisories for a person to resolve, and on its automated outbound path, generated documents that fail the quality gate are held for review rather than sent.
Make retries a deliberate behaviour
External services time out. Users press a button twice. Background jobs and webhooks are delivered again. Stripe, for example, documents that an endpoint "might occasionally receive the same event more than once".
For each action with an external effect, decide what a repeat means. A second request to generate a draft might be harmless. A second request to create an invoice or charge a card is not. The pattern is to claim a key before performing the effect, and to pass the same key to the provider where it supports one. Stripe's API v1 accepts an idempotency key on every POST.
// once.ts (simplified): run an external effect at most once per key.
// In production, claim() is an INSERT into a table with a unique constraint on the key.
export interface OnceStore {
claim(key: string): Promise<boolean>; // false if the key was already claimed
saveResult(key: string, result: unknown): Promise<void>;
getResult(key: string): Promise<unknown>;
}
export async function runOnce<T>(store: OnceStore, key: string, effect: () => Promise<T>) {
if (!(await store.claim(key))) {
return { duplicate: true as const, result: (await store.getResult(key)) as T | undefined };
}
const result = await effect();
await store.saveResult(key, result);
return { duplicate: false as const, result };
}
And the test that matters, two simultaneous requests with the same key:
test("a double-clicked 'create invoice' produces one invoice", async () => {
const store = memoryStore(); // in-memory OnceStore used only by the test
let invoicesCreated = 0;
const createInvoice = async () => { invoicesCreated++; return { id: "inv_1" }; };
await Promise.all([
runOnce(store, "proposal_42:invoice", createInvoice),
runOnce(store, "proposal_42:invoice", createInvoice),
]);
assert.equal(invoicesCreated, 1);
});
The in-memory store passes this test only because its check-and-set happens in one synchronous step. A real implementation must get the same guarantee from the database's unique constraint, not from a "select, then insert" pair that two requests can interleave. The sketch also leaves out failure handling. If the effect throws after the key is claimed, you need to decide whether the key is released, retried or marked failed. That decision belongs in the review.
A generic catch that returns "Something went wrong" is not a recovery plan. The user needs to know whether the action failed, is still running, or completed despite the missing response.
Review the tests themselves
When the same assistant writes the implementation and its tests, the tests tend to describe what the code does rather than what it should do. If a discount function applies the discount twice, a test generated from that function will expect the doubled discount, and it will pass.
Write, or at least review, tests from the acceptance conditions rather than from the implementation. The tests above were written that way: each name is a sentence a product owner would agree with before seeing any code.
Keep the evidence small enough to read
Before release, put together a short record:
- The acceptance conditions, and the roles and paths tested for permissions.
- A few representative model inputs, the expected behaviour and any observed failures.
- What happens on retry and on a duplicate event.
- Environment configuration and the rollback procedure.
- The logs or alerts an operator would use to diagnose a failed request.
It does not need to be long. It should let another engineer see what was checked and what is still uncertain.
Scope the review to what the feature can do
A feature whose output always goes to a person for approval carries different risks from one that can send agreements or move money on its own. Review the authority the feature actually has, rather than treating every "AI app" as one category. The same applies to the tools that wrote it. The Cursor security review checklist covers the editor and agent side.
If your feature is close to launch but the remaining work is unclear, a written diagnosis is a sensible next step. The review scope is agreed before any access is requested.
Close to launch and unsure what is still missing?
Working on a feature this article touches? A 30-minute call is the quickest way to scope it.
Discuss your project