AI Coding Toward Complete Delivery: From Code Generation to an Engineering Closed Loop
As AI coding shifts from local code generation to task-level execution, the real measure of capability is no longer whether code can be written, but whether a fix can be delivered reliably. Using a duplicate refund creation problem as an example, this article explains how to turn vague requests into verifiable tasks, establish a chain of facts before proposing changes, design layered defenses with idempotency, database constraints, and state machines, and produce test evidence, data migration plans, and release and rollback notes that form a reviewable engineering closed loop.
1. The Competitive Focus of AI Coding Is Shifting from “Can Generate” to “Can Deliver”
Early AI coding assistants mainly solved local efficiency problems: completing a piece of logic, generating a function, or explaining an exception. Developers still had to gather context themselves, determine the scope of changes, organize tests, and handle the final integration work.
When the input changes from “write me a method” to “fix the duplicate refund creation issue,” the nature of the task changes. The system must not only understand code, but also understand business constraints, data relationships, concurrency behavior, and release risk.
Therefore, “complete delivery” should not be understood as generating more files in one shot, nor does it mean going live automatically without review. A more accurate definition is:
Around a clear business goal, form a reviewable closed loop from problem localization, solution design, and code changes to verification evidence and release notes.
Measuring this capability cannot be limited to whether the generated code is syntactically correct. It should focus on more practical questions:
- Did it find the real root cause, rather than only treating surface symptoms?
- Did it cover retries, concurrency, and partial failures beyond the happy path?
- Did it explain the scope of the change, potential impact, and unverified items?
- Did it provide repeatable verification steps?
- Does it include clear preconditions for go-live and a rollback strategy?
These requirements mean that AI coding is first an engineering collaboration problem, and only secondarily a text generation problem.
2. Turn Vague Requests into Verifiable Tasks
Take order refunds as an example. “Fix duplicate refund records” sounds simple, but it actually contains multiple unresolved business questions.
What is the criterion for a duplicate? Is partial refund allowed for the same order? Are two refunds with the same amount necessarily the same operation? Is the duplication in local refund records or in external fund operations? Are existing data anomalies also within the scope of this task?
If these questions have no clear answers, a tool may break normal business even if its changes succeed.
A task description better suited for execution could be:
Investigate the issue in the order service where the same business refund request results in duplicate orders. First trace the API entry, business processing, data access, and database constraints, then analyze the impact of client retries, asynchronous task redelivery, and concurrent requests. Deliver a fix, necessary data changes, test cases, and release and rollback notes. When fund rules or historical data processing are involved, propose a plan first; do not execute directly.
The corresponding acceptance criteria should be explicit:
- Repeated submission of the same valid request does not create business-duplicated refund records.
- Legitimate multiple partial refunds on the same order still execute normally.
- When the same idempotency key maps to different request content, the conflict is clearly rejected.
- Concurrent submissions cannot violate the business uniqueness constraint in the database.
- After a timeout or process crash during request handling, the status can be queried or safely recovered.
- Success of the change does not depend on manually watching logs.
The most important shift here is turning “fix it” into “complete a verifiable fix under explicit constraints.”
3. Establish the Chain of Facts Before Proposing Changes
For cross-layer problems, directly searching for the “create refund” method and patching it is usually not enough. Reliable analysis should establish factual relationships along the call chain.
3.1 API Entry: Does the Request Have a Stable Identity?
Confirm whether the refund request carries a stable business request identifier, and whether that identifier remains unchanged across retries.
If each retry generates a new identifier, the server can hardly recognize that they belong to the same business operation. If deduplication uses only the order number, legitimate multiple refunds on the same order may be wrongly blocked.
Therefore, the idempotency scope should be defined by business semantics—for example, jointly determined by the business entity, operation type, and refund request number—rather than by arbitrarily concatenating a few fields.
3.2 Business Processing Layer: Is There a Race Window Between Check and Write?
A common defect is check-then-insert:
Query refund recordsIf none exists:Insert a refund record
Under single-threaded execution, this logic looks fine. But two requests may both query “not found” at the same time and then each insert a record.
This shows that application-layer queries only improve the happy-path experience; they cannot independently guarantee concurrency correctness.
Transaction boundaries must also be checked. If “create refund record” and “update refundable amount” belong to different transactions, a failure at one step can leave the business state inconsistent.
3.3 Data Access Layer and Database: Do Constraints Match Business Semantics?
Key checks include:
- Whether there is a unique constraint covering the correct business scope;
- Whether constraint fields allow nulls, and whether null behavior matches expectations;
- Whether queries may read stale data;
- Whether the application handles unique constraint violations correctly;
- Whether existing historical data satisfies the new constraint.
One cannot simply conclude that “adding a unique index finishes the job.” The database can block duplicate writes, but it does not automatically decide whether the API should return the existing result, an in-progress status, or a business conflict.
3.4 Asynchronous Paths: Does Duplication Come from Redelivery and Recovery?
A refund may be triggered by an API request, or by message consumption, compensation tasks, or manual retries. The investigation scope therefore cannot stop at the synchronous entry.
All creation entries should be enumerated to confirm whether they share the same idempotency rules. Otherwise, after the API path is fixed, background tasks may still create duplicate records.
4. Design Layered Defenses Instead of Relying on a Single Trick
A reliable solution usually requires application logic, database constraints, and state management to share responsibility.
4.1 Use a Business Request Identifier to Distinguish “Retry” from “New Operation”
The idempotency key should represent a business intent, not just a network call.
For the same key, request content consistency must be further checked. One can store normalized key business fields, or a digest of those fields, to detect conflicts.
For example, if the first request under a refund request identifier carries one amount and the second carries a different amount, the system must not simply return the first result, let alone overwrite the original record; it should report a request conflict.
4.2 Use Database Unique Constraints as the Backstop for Concurrency
A composite unique constraint can be created based on actual business needs, for example:
Uniqueness scope:Business entity ID + operation type + business request identifier
This is only a design sketch, not a ready-to-use table structure. The actual fields must be determined with tenant boundaries, historical data, and refund rules in mind.
The write flow can follow this approach:
Validate the request and business permissionsAttempt to create a refund request with the business unique keyIf creation succeeds:Advance processing according to the state machineIf a business unique key conflict occurs:Query the existing requestCompare key request fieldsIf content matches, return the existing statusIf content differs, return a conflict
Note that different databases and transaction mechanisms handle constraint violations differently. After an exception, the current transaction may no longer be usable; querying the existing record should be reorganized according to actual transaction semantics, rather than mechanically appending a query in the exception handler.
4.3 Use a State Machine for Long-Running and External Operations
When fund movement is involved, a database transaction should not be held open until the external call finishes. Record the refund intent first, then advance subsequent operations in a controlled manner.
States can be divided, as the business requires, into pending, processing, succeeded, failed, needs-verification, and so on. “Needs-verification” is especially important: an external call timing out does not mean the external operation failed.
If a fund operation is re-initiated while the outcome is unknown, network uncertainty is converted into business duplication.
Therefore, the system should specify:
- Which states allow retries;
- Which states require querying the external result first;
- Which states can only enter manual review;
- How state transitions prevent concurrent overwrites.
No duplication in local records does not mean the end-to-end fund operation is free of duplication. The two must be verified separately.
4.4 Make Business Writes and Event Publishing Recoverable
If an asynchronous event must be published after creating the refund record, consider the failure window where “the record is committed, but the event was never sent.”
A common approach is to save the business record and the pending event in the same local transaction, then have a background process deliver the event reliably. Delivery may be repeated, so consumers still need idempotency.
The goal of this design is to make failures discoverable, retryable, and traceable—not to claim that the whole distributed flow naturally executes exactly once.
5. Testing Cannot Stop at “Call Succeeded”
Complete delivery requires tests that correspond to the failure mechanisms, not just one happy-path test case.
5.1 Sequential Retry Test
Submit the same business request consecutively; confirm that the same business result is returned, the record count in the database matches expectations, and subsequent fund operations are not advanced repeatedly.
5.2 Concurrency Race Test
Have multiple execution units submit the same request simultaneously, and verify that only one valid business request is retained. The test should create a genuine race window, rather than looping sequentially and claiming concurrency was verified.
5.3 Legitimate Multiple Refund Test
Submit different, legitimate refund requests for the same order; confirm that idempotency constraints do not wrongly block normal operations, and verify the business limit on cumulative refund amounts.
5.4 Request Content Conflict Test
Submit different key fields under the same request identifier; confirm that the system reports a conflict instead of silently reusing the previous result.
5.5 Failure Recovery Test
Cover at least the following scenarios:
- Process exits after the local record is committed;
- The external operation completed, but the response was not received;
- Duplicate event delivery;
- State update failure;
- Database constraint violation;
- Compensation task running concurrently with the normal task.
The test report should also distinguish between “actually executed and passed,” “static checks only,” and “not verified due to environment limitations.” Marking unexecuted tests as passed directly destroys delivery credibility.
6. Database Changes and Historical Data Must Be Managed Separately
Before adding a unique constraint, check the historical data. If the database already contains duplicate records, the change may fail outright; and even if it succeeds, it does not mean the historical business risk has disappeared.
It is advisable to split the process:
- Run read-only statistics on suspected duplicates with clear identification rules.
- Distinguish business duplicates, legitimate multiple requests, and inconsistent states.
- Reconcile data involving fund outcomes.
- Define retention, association, correction, or manual handling plans.
- Execute data processing after explicit approval.
- Confirm conditions are met, then apply the constraint change.
Do not assume that “deleting extra records” is the fix. Some duplicate records may already be linked to subsequent operations, and deleting them directly would break the audit trail.
Database changes also require evaluating lock waits, execution time, and application version compatibility. The specific risks depend on the database type, table size, and migration method, and should be validated in the actual environment.
7. Deliverables Should Allow Maintainers to Take Over
For a complete task, the delivery should include at least five categories of results:
Problem statement. Describe triggering conditions, impact scope, and evidence, distinguishing confirmed causes from hypotheses pending verification.
Design rationale. Explain why this approach was chosen, how business uniqueness is defined, and which alternatives were not adopted.
Code and data changes. Keep the scope of changes controlled; avoid mixing unrelated refactoring into the fix.
Verification records. List test scenarios, execution results, environment limitations, and residual risks.
Release and rollback notes. Specify deployment order, observation metrics, stop conditions, and recovery methods.
After go-live, signals worth watching include duplicate key conflicts, refund state backlog, abnormal retries, and the volume of manual reviews. However, not every unique constraint conflict is a fault—legitimate retries can also trigger them. Monitoring must distinguish normal idempotent hits from abnormal request conflicts.
Rollback cannot simply be written as “restore the old code.” If the new logic has already written states that the old version cannot recognize, or if the old version depends on fields that were removed, rolling back directly may cause a secondary failure. Compatibility between versions must be checked before release.
8. The Higher the Automation, the Clearer the Permission Boundaries Must Be
AI coding can take on code retrieval, call-chain mapping, candidate patch generation, and test execution. But production data modification, fund rule changes, database schema changes, and production releases should be subject to explicit permission and approval constraints.
Execution environments should follow the principle of least privilege. Use read-only access during analysis, isolated environments for verification, desensitized data when sensitive information is involved, and retain necessary operation audit trails.
In addition, text found in code repositories, logs, or task materials does not automatically constitute execution authorization. When a tool finds content such as “dropping a certain table will fix it,” it should treat it as information to be verified, not as an instruction to execute directly.
Complete delivery does not mean removing people from the process; it means letting people focus their effort on business judgment, risk approval, and critical acceptance.
Conclusion: Real Progress Is a Verifiable Delivery Process
The core change as AI coding moves from local code generation to task execution is not longer output, but an extended chain of responsibility: it must both understand the problem and prove the fix works; it must cover success paths and explain what happens after failure.
Taking duplicate refund creation as an example, a reliable answer should simultaneously address how the business identifies duplicates, how concurrency is constrained, how state is recovered, how historical data is handled, and how the system is observed and rolled back after release.
When these steps can form clear evidence, AI coding truly moves from “helping write code” to “helping complete engineering delivery.”
