Writing

Every Line the AI Wrote Was Correct. It Still Failed Review: Transactions Don't Queue, and Where the Lock Goes

2026-11-20

12 mins to read

Share article

The thesis in one sentence: AI-written code usually survives a line-by-line read and fails the question "what if two requests arrive at once?" Using a batch of AI-generated admin write endpoints as the example, this post covers three things from the reviewer's seat: why a transaction does not stop concurrent requests from breaking a limit, why adding a lock can still leave you reading stale data, and why saving a whole list can delete something a colleague just added. Business names and code have been neutralized; only the pseudocode needed to make the point remains.

1. Would this pass your review?

The requirement is simple: a merchant maintains a set of quick replies, capped at 80. The AI's endpoint for adding one looks like this:

@Transactional
public void addQuickReply(long shopId, String content) {
    int count = replyMapper.countByShop(shopId);   // count first
    if (count >= 80) {
        throw new BusinessException("Limit reached");
    }
    replyMapper.insert(shopId, content);           // then insert
}

It has a transaction, a limit check, a clear error message and comments. Read line by line, there is nothing to object to, and it will pass self-testing every time: click 81 times and the 81st is rejected.

But I don't review line by line. I ask one question: if two requests arrive together, what is the other one doing while each of them sits on a given line? You cannot see the answer in the code. You have to draw it.

2. Problem one: a transaction is not a queue

Put the two requests on one timeline, with 79 rows in the table:

The misunderstanding is about what @Transactional gives you. A transaction guarantees that a group of operations either all take effect or all roll back. It does not make transactions take turns. Two transactions can both be in the state "counted, not yet inserted", and both counted 79.

This pattern has a name: check-then-act. Whenever the decision to write depends on something you just read, and nothing prevents another request from slipping in between the read and the write, the check can be bypassed. Count limits, name uniqueness and "the set must still match what I saw" all belong here.

Review signal: when you see if (what I read satisfies the condition) { write }, stop and ask what guarantees nobody gets in between the read and the write. The answer can only be a unique key or a lock. If the answer is "there's a transaction", there is no guarantee.

Name uniqueness can fall back on a unique key: of two concurrent inserts, the later one gets a duplicate-key error, which you catch and turn into a business message. A count limit has no unique key to lean on, so it needs a lock.

Lock what, though? This is easy to get wrong: the row you need to guard against does not exist yet, so there is no "80th row" to lock. What you can lock is the parent row they all share, the merchant. Every add request for the same merchant first competes for the row lock on that merchant. The winner proceeds and the rest wait.

3. Why a lock is still not enough: which line does it go on?

"Add a row lock" is advice you can find anywhere. In review I also check where the lock sits inside the transaction, because this version is wrong too:

@Transactional
public void addQuickReply(long shopId, long operatorId, String content) {
    Operator op = operatorMapper.selectById(operatorId); // plain read
    checkPermission(op, shopId);

    shopMapper.lockById(shopId);                         // SELECT ... FOR UPDATE
    int count = replyMapper.countByShop(shopId);         // plain read
    if (count >= 80) {
        throw new BusinessException("Limit reached");
    }
    replyMapper.insert(shopId, content);
}

It locks before it counts, so what is wrong? Draw it:

B did wait, and it did resume only after A committed, yet it still counted 79. The reason lies in two rules of MySQL's default isolation level, REPEATABLE READ:

  1. A plain SELECT reads a snapshot, and that snapshot is fixed by the first plain read in the transaction. The whole transaction sees that one view from then on (consistent reads).
  2. SELECT ... FOR UPDATE reads the latest committed data, and takes a lock that others queue on (locking reads).

So the lock in this code works fine. The problem is the plain read at the top, the operator check, which pinned the snapshot to a moment before A committed. Counting after the lock is acquired still counts the old world.

The lock must be the first statement in the transaction, or at least come before any plain read. A single plain read ahead of the lock reduces the queue to a formality: the request waits, and then sees the data from before it waited.
Two caveats. First, this section assumes REPEATABLE READ. Under READ COMMITTED every statement gets a fresh snapshot, so this particular problem does not appear, though the one in section 2 still does. Second, the diagrams here are derived from the documented InnoDB semantics, not from a load test.

4. The correct version

Move the lock to the top:

@Transactional
public void addQuickReply(long shopId, long operatorId, String content) {
    shopMapper.lockById(shopId);                         // first statement in the transaction
    Operator op = operatorMapper.selectById(operatorId);
    checkPermission(op, shopId);
    int count = replyMapper.countByShop(shopId);
    if (count >= 80) {
        throw new BusinessException("Limit reached");
    }
    replyMapper.insert(shopId, content);
}

Only one thing differs from the previous diagram: B did no plain read before it queued, so its snapshot is created after it gets the lock and naturally includes the row A committed.

What if you have to query first to know what to lock? One place in this batch was exactly that case: adding a tag to a customer, capped at 100 per customer. The input is a conversation ID, so you must look up the conversation to learn which customer it is, and that lookup is itself a plain read. Declarative transactions are not enough here. The transaction boundary has to shrink to just "lock, read, write":

public void addTag(long conversationId, String name) {
    // Outside the transaction: look up the conversation and check ownership,
    // only to learn which row to lock
    Customer customer = resolveCustomer(conversationId);

    transactionTemplate.execute(status -> {
        customerMapper.lockById(customer.getId());   // first statement in the transaction
        List<Tag> tags = tagMapper.listByCustomer(customer.getId());
        if (containsName(tags, name)) return null;   // same name counts as success
        if (tags.size() >= 100) throw new BusinessException("Limit reached");
        tagMapper.insert(customer.getId(), name);
        return null;
    });
}

Keeping the ownership check outside the transaction is acceptable: it verifies "is this conversation yours", a fact that does not change within milliseconds. The limit and the duplicate check, on the other hand, must happen inside the lock.

5. Problem two: a whole-list overwrite with no version

The second kind of problem has nothing to do with locks. The requirement is a "job title dictionary" dialog: an admin adds, deletes, renames and reorders titles in the dialog, then submits the whole list on save. The AI implemented it like this:

@Transactional
public void saveAll(long shopId, List<Item> items) {
    List<Title> current = titleMapper.listByShop(shopId);
    // Items with an id are renames, items without one are new,
    // and anything in the table but missing from the submission is a delete
    ...
}

"Anything in the table but missing from the submission is a delete" holds under one assumption: the submitted draft was edited from the list that is in the table right now. Once two admins have the dialog open at the same time, the assumption fails:

X did nothing wrong, and the service followed its rule exactly. The result is that Y's data was silently deleted. This is harder to spot than a broken limit: no error, nothing over quota, and the log shows one ordinary save.

The fix is to give the list a version. The list endpoint returns a version value (a digest of the list contents is enough), the save request sends it back unchanged, and the server compares first:

@Transactional
public Result saveAll(long shopId, String version, List<Item> items) {
    shopMapper.lockById(shopId);                       // still the first statement
    List<Title> current = titleMapper.listByShop(shopId);
    if (!versionOf(current).equals(version)) {
        return Result.stale(current);                  // stale draft: reject and return the latest list
    }
    ...
}

If the version does not match, the whole save is rejected. The frontend says "the list was changed by someone else" and resets the draft from the latest list that came back. X has to redo the rename on the new list, and that cost is deliberate: redoing one edit is better than quietly deleting someone else's data.

Review signal: when you see "the client's full submission is the truth, anything missing gets deleted", ask how the server knows the submission was edited from the latest state. The answer can only be a version check.

Both tools solve the same thing, what you read may be out of date by the time you write, but they fit different situations:

Row lock (pessimistic)Version check (optimistic)
Gap between read and writeWithin one request, millisecondsAcross requests, the user may edit for minutes
On conflictThe later one waits, then continues on fresh dataThe later one is rejected and must redo on fresh data
FitsLimits, uniqueness, decrementsWhole-list saves, long forms, draft-style editing

You cannot hold a database lock for the minutes a dialog stays open, so a version is the only option there. Both appear in the code above because "compare the version, then write" is itself check-then-act and still needs the lock to hold.

6. Why AI tends to write code like this

Looking back at what was sent back, the pieces share one trait: treated as a single request running top to bottom, all of them are correct. My observation is that an AI generating code works from that viewpoint by default. It implements "what happens after one request comes in", while concurrency problems live "between two requests", in something the code text never spells out.

That also explains why these problems are especially hard to notice in AI-written code:

  • The code looks complete. Transactions, validation, error codes and comments are all there, and a reviewer is easily persuaded by the polish.
  • Self-testing always passes. One person on one thread can never trigger the interleaving.
  • The AI is not ignorant of it. In the same batch, a reorder endpoint did carry a staleness check, and another uniqueness rule was backed by a unique key. The knowledge was there. It just was not applied systematically to every write endpoint.

That last point sets the direction for improvement: what is missing is not knowledge but a checklist that gets run every time.

7. Where to improve

For the reviewer: turn the questions above into a decision tree. Walk through it for any write endpoint:

For the AI: write the review conclusions into rules it reads every time. A verbal correction only lasts for the current conversation. Next time it starts from the single-request viewpoint again. What I did was put the conclusions into the project's instruction file, so it goes through them while drafting a plan and while self-testing:

Self-check for every create, update and delete endpoint:
1. Check-then-act must be serialized: count limits, name uniqueness and
   set-consistency checks need either a unique key behind them or a lock on
   the parent row inside the transaction. A transaction alone is not mutual exclusion.
2. The lock must come before any plain read in the transaction. If you must
   query first to know what to lock, do that query outside the transaction and
   wrap "lock, read, write" in a programmatic transaction.
3. Whole-list or whole-object overwrites must carry a version: for semantics
   like "anything missing from the submission is deleted", verify the version
   the draft was based on, and reject stale drafts with the latest data.
In every plan, state for each write endpoint: what serializes it.

The last line is the key one. Requiring the plan to state explicitly what serializes each endpoint turns the question it would not ask by default into a blank it must fill in. Wherever it cannot fill the blank is where the review needs to look.

For the fix itself: it needs review too. Having the rules written down does not mean you can relax. In the second review round of this batch, the AI added an early return while fixing a scope check. The issue that had been raised was fixed correctly, but the early return also skipped an existing check further down, the one verifying that the resource still exists, and that kind of problem was not on the checklist. A checklist guards against the kinds of problems you have already seen, not new ones, and every round of changes can bring something from outside it. So a re-review cannot stop at "were last round's comments addressed". It also has to ask "what does this change bypass?"

8. Principles that transfer

  1. Reading AI code line by line is not enough. Ask what happens when two requests arrive together. Polish does not mean concurrency safety, and a sequence diagram exposes problems more readily than the code does.
  2. A transaction handles "all or nothing". It does not handle queuing. Queuing comes only from a unique key or a lock.
  3. A lock has a position requirement. Under REPEATABLE READ, one plain read ahead of the lock means everything read afterwards is old.
  4. Use a version for read-then-write across requests, and a lock within a request. Both solve the same problem: what you read is out of date by the time you write.
  5. What the AI lacks is often not knowledge but a checklist that runs every time. Writing review conclusions into its standing rules works better than correcting it again each time.
  6. The fix needs review too. A checklist only guards against problems you have seen. When re-reviewing, check last round's comments, then check which existing validations the new change bypasses.
In one sentence: the AI gets a single request right, and the human asks what happens between requests. Then hand that question to the AI as well, so it asks itself first every time.