[{"data":1,"prerenderedAt":1276},["ShallowReactive",2],{"\u002Farticles\u002Freviewing-ai-code-concurrency":3},{"id":4,"title":5,"body":6,"date":1260,"description":1261,"extension":1262,"head":1263,"image":1264,"meta":1265,"navigation":289,"ogImage":1263,"path":1266,"rating":1267,"readingTime":1268,"robots":1263,"schemaOrg":1263,"seo":1269,"sitemap":1270,"stem":1271,"tags":1272,"__hash__":1275},"articles_en\u002Farticles\u002Freviewing-ai-code-concurrency.md","Every Line the AI Wrote Was Correct. It Still Failed Review: Transactions Don't Queue, and Where the Lock Goes",{"type":7,"value":8,"toc":1250},"minimark",[9,21,26,29,89,92,99,103,106,201,212,219,240,243,250,254,261,322,325,436,439,479,482,491,496,500,503,555,632,635,641,714,717,721,724,762,769,843,846,853,898,901,912,919,974,977,981,988,991,1012,1015,1019,1025,1115,1121,1183,1190,1199,1203,1241,1246],[10,11,12],"note",{},[13,14,15,16,20],"p",{},"The thesis in one sentence: ",[17,18,19],"strong",{},"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.",[22,23,25],"h2",{"id":24},"_1-would-this-pass-your-review","1. Would this pass your review?",[13,27,28],{},"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:",[30,31,36],"pre",{"className":32,"code":33,"language":34,"meta":35,"style":35},"language-java shiki shiki-themes github-light github-dark github-dark","@Transactional\npublic void addQuickReply(long shopId, String content) {\n    int count = replyMapper.countByShop(shopId);   \u002F\u002F count first\n    if (count >= 80) {\n        throw new BusinessException(\"Limit reached\");\n    }\n    replyMapper.insert(shopId, content);           \u002F\u002F then insert\n}\n","java","",[37,38,39,47,53,59,65,71,77,83],"code",{"__ignoreMap":35},[40,41,44],"span",{"class":42,"line":43},"line",1,[40,45,46],{},"@Transactional\n",[40,48,50],{"class":42,"line":49},2,[40,51,52],{},"public void addQuickReply(long shopId, String content) {\n",[40,54,56],{"class":42,"line":55},3,[40,57,58],{},"    int count = replyMapper.countByShop(shopId);   \u002F\u002F count first\n",[40,60,62],{"class":42,"line":61},4,[40,63,64],{},"    if (count >= 80) {\n",[40,66,68],{"class":42,"line":67},5,[40,69,70],{},"        throw new BusinessException(\"Limit reached\");\n",[40,72,74],{"class":42,"line":73},6,[40,75,76],{},"    }\n",[40,78,80],{"class":42,"line":79},7,[40,81,82],{},"    replyMapper.insert(shopId, content);           \u002F\u002F then insert\n",[40,84,86],{"class":42,"line":85},8,[40,87,88],{},"}\n",[13,90,91],{},"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.",[13,93,94,95,98],{},"But I don't review line by line. I ask one question: ",[17,96,97],{},"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.",[22,100,102],{"id":101},"_2-problem-one-a-transaction-is-not-a-queue","2. Problem one: a transaction is not a queue",[13,104,105],{},"Put the two requests on one timeline, with 79 rows in the table:",[30,107,111],{"className":108,"code":109,"language":110,"meta":35,"style":35},"language-mermaid shiki shiki-themes github-light github-dark github-dark","sequenceDiagram\n    participant A as Request A\n    participant DB as Database\n    participant B as Request B\n    A->>DB: BEGIN\n    B->>DB: BEGIN\n    A->>DB: SELECT COUNT\n    DB-->>A: 79\n    B->>DB: SELECT COUNT\n    DB-->>B: 79\n    Note over A,B: Both pass the \"fewer than 80\" check\n    A->>DB: INSERT\n    B->>DB: INSERT\n    A->>DB: COMMIT\n    B->>DB: COMMIT\n    Note over DB: 81 rows in the end, the limit is broken\n","mermaid",[37,112,113,118,123,128,133,138,143,148,153,159,165,171,177,183,189,195],{"__ignoreMap":35},[40,114,115],{"class":42,"line":43},[40,116,117],{},"sequenceDiagram\n",[40,119,120],{"class":42,"line":49},[40,121,122],{},"    participant A as Request A\n",[40,124,125],{"class":42,"line":55},[40,126,127],{},"    participant DB as Database\n",[40,129,130],{"class":42,"line":61},[40,131,132],{},"    participant B as Request B\n",[40,134,135],{"class":42,"line":67},[40,136,137],{},"    A->>DB: BEGIN\n",[40,139,140],{"class":42,"line":73},[40,141,142],{},"    B->>DB: BEGIN\n",[40,144,145],{"class":42,"line":79},[40,146,147],{},"    A->>DB: SELECT COUNT\n",[40,149,150],{"class":42,"line":85},[40,151,152],{},"    DB-->>A: 79\n",[40,154,156],{"class":42,"line":155},9,[40,157,158],{},"    B->>DB: SELECT COUNT\n",[40,160,162],{"class":42,"line":161},10,[40,163,164],{},"    DB-->>B: 79\n",[40,166,168],{"class":42,"line":167},11,[40,169,170],{},"    Note over A,B: Both pass the \"fewer than 80\" check\n",[40,172,174],{"class":42,"line":173},12,[40,175,176],{},"    A->>DB: INSERT\n",[40,178,180],{"class":42,"line":179},13,[40,181,182],{},"    B->>DB: INSERT\n",[40,184,186],{"class":42,"line":185},14,[40,187,188],{},"    A->>DB: COMMIT\n",[40,190,192],{"class":42,"line":191},15,[40,193,194],{},"    B->>DB: COMMIT\n",[40,196,198],{"class":42,"line":197},16,[40,199,200],{},"    Note over DB: 81 rows in the end, the limit is broken\n",[13,202,203,204,207,208,211],{},"The misunderstanding is about what ",[37,205,206],{},"@Transactional"," gives you. A transaction guarantees that ",[17,209,210],{},"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.",[13,213,214,215,218],{},"This pattern has a name: ",[17,216,217],{},"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.",[220,221,222],"tip",{},[13,223,224,227,228,231,232,235,236,239],{},[17,225,226],{},"Review signal",": when you see ",[37,229,230],{},"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 ",[17,233,234],{},"unique key"," or a ",[17,237,238],{},"lock",". If the answer is \"there's a transaction\", there is no guarantee.",[13,241,242],{},"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.",[13,244,245,246,249],{},"Lock what, though? This is easy to get wrong: the row you need to guard against ",[17,247,248],{},"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.",[22,251,253],{"id":252},"_3-why-a-lock-is-still-not-enough-which-line-does-it-go-on","3. Why a lock is still not enough: which line does it go on?",[13,255,256,257,260],{},"\"Add a row lock\" is advice you can find anywhere. In review I also check ",[17,258,259],{},"where the lock sits inside the transaction",", because this version is wrong too:",[30,262,264],{"className":32,"code":263,"language":34,"meta":35,"style":35},"@Transactional\npublic void addQuickReply(long shopId, long operatorId, String content) {\n    Operator op = operatorMapper.selectById(operatorId); \u002F\u002F plain read\n    checkPermission(op, shopId);\n\n    shopMapper.lockById(shopId);                         \u002F\u002F SELECT ... FOR UPDATE\n    int count = replyMapper.countByShop(shopId);         \u002F\u002F plain read\n    if (count >= 80) {\n        throw new BusinessException(\"Limit reached\");\n    }\n    replyMapper.insert(shopId, content);\n}\n",[37,265,266,270,275,280,285,291,296,301,305,309,313,318],{"__ignoreMap":35},[40,267,268],{"class":42,"line":43},[40,269,46],{},[40,271,272],{"class":42,"line":49},[40,273,274],{},"public void addQuickReply(long shopId, long operatorId, String content) {\n",[40,276,277],{"class":42,"line":55},[40,278,279],{},"    Operator op = operatorMapper.selectById(operatorId); \u002F\u002F plain read\n",[40,281,282],{"class":42,"line":61},[40,283,284],{},"    checkPermission(op, shopId);\n",[40,286,287],{"class":42,"line":67},[40,288,290],{"emptyLinePlaceholder":289},true,"\n",[40,292,293],{"class":42,"line":73},[40,294,295],{},"    shopMapper.lockById(shopId);                         \u002F\u002F SELECT ... FOR UPDATE\n",[40,297,298],{"class":42,"line":79},[40,299,300],{},"    int count = replyMapper.countByShop(shopId);         \u002F\u002F plain read\n",[40,302,303],{"class":42,"line":85},[40,304,64],{},[40,306,307],{"class":42,"line":155},[40,308,70],{},[40,310,311],{"class":42,"line":161},[40,312,76],{},[40,314,315],{"class":42,"line":167},[40,316,317],{},"    replyMapper.insert(shopId, content);\n",[40,319,320],{"class":42,"line":173},[40,321,88],{},[13,323,324],{},"It locks before it counts, so what is wrong? Draw it:",[30,326,328],{"className":108,"code":327,"language":110,"meta":35,"style":35},"sequenceDiagram\n    participant A as Request A\n    participant DB as Database\n    participant B as Request B\n    A->>DB: BEGIN\n    B->>DB: BEGIN\n    B->>DB: Plain read: check the operator\n    Note over B: B's snapshot is fixed here\u003Cbr>the table has 79 rows\n    A->>DB: Plain read: check the operator\n    A->>DB: Lock the merchant row\n    B->>DB: Lock the merchant row\n    Note over B: Waits in line\n    A->>DB: SELECT COUNT\n    DB-->>A: 79\n    A->>DB: INSERT, then COMMIT\n    Note over DB: 80 rows committed\n    DB-->>B: Lock acquired\n    B->>DB: SELECT COUNT\n    DB-->>B: 79\n    Note over B: Reads the old snapshot, cannot see A's row\n    B->>DB: INSERT, then COMMIT\n    Note over DB: 81 rows in the end\n",[37,329,330,334,338,342,346,350,354,359,364,369,374,379,384,388,392,397,402,408,413,418,424,430],{"__ignoreMap":35},[40,331,332],{"class":42,"line":43},[40,333,117],{},[40,335,336],{"class":42,"line":49},[40,337,122],{},[40,339,340],{"class":42,"line":55},[40,341,127],{},[40,343,344],{"class":42,"line":61},[40,345,132],{},[40,347,348],{"class":42,"line":67},[40,349,137],{},[40,351,352],{"class":42,"line":73},[40,353,142],{},[40,355,356],{"class":42,"line":79},[40,357,358],{},"    B->>DB: Plain read: check the operator\n",[40,360,361],{"class":42,"line":85},[40,362,363],{},"    Note over B: B's snapshot is fixed here\u003Cbr>the table has 79 rows\n",[40,365,366],{"class":42,"line":155},[40,367,368],{},"    A->>DB: Plain read: check the operator\n",[40,370,371],{"class":42,"line":161},[40,372,373],{},"    A->>DB: Lock the merchant row\n",[40,375,376],{"class":42,"line":167},[40,377,378],{},"    B->>DB: Lock the merchant row\n",[40,380,381],{"class":42,"line":173},[40,382,383],{},"    Note over B: Waits in line\n",[40,385,386],{"class":42,"line":179},[40,387,147],{},[40,389,390],{"class":42,"line":185},[40,391,152],{},[40,393,394],{"class":42,"line":191},[40,395,396],{},"    A->>DB: INSERT, then COMMIT\n",[40,398,399],{"class":42,"line":197},[40,400,401],{},"    Note over DB: 80 rows committed\n",[40,403,405],{"class":42,"line":404},17,[40,406,407],{},"    DB-->>B: Lock acquired\n",[40,409,411],{"class":42,"line":410},18,[40,412,158],{},[40,414,416],{"class":42,"line":415},19,[40,417,164],{},[40,419,421],{"class":42,"line":420},20,[40,422,423],{},"    Note over B: Reads the old snapshot, cannot see A's row\n",[40,425,427],{"class":42,"line":426},21,[40,428,429],{},"    B->>DB: INSERT, then COMMIT\n",[40,431,433],{"class":42,"line":432},22,[40,434,435],{},"    Note over DB: 81 rows in the end\n",[13,437,438],{},"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:",[440,441,442,465],"ol",{},[443,444,445,452,453,456,457,464],"li",{},[17,446,447,448,451],{},"A plain ",[37,449,450],{},"SELECT"," reads a snapshot",", and that snapshot is fixed by the ",[17,454,455],{},"first plain read"," in the transaction. The whole transaction sees that one view from then on (",[458,459,463],"a",{"href":460,"rel":461},"https:\u002F\u002Fdev.mysql.com\u002Fdoc\u002Frefman\u002F8.0\u002Fen\u002Finnodb-consistent-read.html",[462],"nofollow","consistent reads",").",[443,466,467,473,474,464],{},[17,468,469,472],{},[37,470,471],{},"SELECT ... FOR UPDATE"," reads the latest committed data",", and takes a lock that others queue on (",[458,475,478],{"href":476,"rel":477},"https:\u002F\u002Fdev.mysql.com\u002Fdoc\u002Frefman\u002F8.0\u002Fen\u002Finnodb-locking-reads.html",[462],"locking reads",[13,480,481],{},"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.",[483,484,485],"warning",{},[13,486,487,490],{},[17,488,489],{},"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.",[10,492,493],{},[13,494,495],{},"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.",[22,497,499],{"id":498},"_4-the-correct-version","4. The correct version",[13,501,502],{},"Move the lock to the top:",[30,504,506],{"className":32,"code":505,"language":34,"meta":35,"style":35},"@Transactional\npublic void addQuickReply(long shopId, long operatorId, String content) {\n    shopMapper.lockById(shopId);                         \u002F\u002F first statement in the transaction\n    Operator op = operatorMapper.selectById(operatorId);\n    checkPermission(op, shopId);\n    int count = replyMapper.countByShop(shopId);\n    if (count >= 80) {\n        throw new BusinessException(\"Limit reached\");\n    }\n    replyMapper.insert(shopId, content);\n}\n",[37,507,508,512,516,521,526,530,535,539,543,547,551],{"__ignoreMap":35},[40,509,510],{"class":42,"line":43},[40,511,46],{},[40,513,514],{"class":42,"line":49},[40,515,274],{},[40,517,518],{"class":42,"line":55},[40,519,520],{},"    shopMapper.lockById(shopId);                         \u002F\u002F first statement in the transaction\n",[40,522,523],{"class":42,"line":61},[40,524,525],{},"    Operator op = operatorMapper.selectById(operatorId);\n",[40,527,528],{"class":42,"line":67},[40,529,284],{},[40,531,532],{"class":42,"line":73},[40,533,534],{},"    int count = replyMapper.countByShop(shopId);\n",[40,536,537],{"class":42,"line":79},[40,538,64],{},[40,540,541],{"class":42,"line":85},[40,542,70],{},[40,544,545],{"class":42,"line":155},[40,546,76],{},[40,548,549],{"class":42,"line":161},[40,550,317],{},[40,552,553],{"class":42,"line":167},[40,554,88],{},[30,556,558],{"className":108,"code":557,"language":110,"meta":35,"style":35},"sequenceDiagram\n    participant A as Request A\n    participant DB as Database\n    participant B as Request B\n    A->>DB: BEGIN\n    B->>DB: BEGIN\n    A->>DB: Lock the merchant row\n    B->>DB: Lock the merchant row\n    Note over B: Waits in line, no snapshot yet\n    A->>DB: SELECT COUNT\n    DB-->>A: 79\n    A->>DB: INSERT, then COMMIT\n    DB-->>B: Lock acquired\n    B->>DB: SELECT COUNT\n    Note over B: First plain read, the snapshot is fixed only now\n    DB-->>B: 80\n    B-->>B: Rejected: limit reached\n",[37,559,560,564,568,572,576,580,584,588,592,597,601,605,609,613,617,622,627],{"__ignoreMap":35},[40,561,562],{"class":42,"line":43},[40,563,117],{},[40,565,566],{"class":42,"line":49},[40,567,122],{},[40,569,570],{"class":42,"line":55},[40,571,127],{},[40,573,574],{"class":42,"line":61},[40,575,132],{},[40,577,578],{"class":42,"line":67},[40,579,137],{},[40,581,582],{"class":42,"line":73},[40,583,142],{},[40,585,586],{"class":42,"line":79},[40,587,373],{},[40,589,590],{"class":42,"line":85},[40,591,378],{},[40,593,594],{"class":42,"line":155},[40,595,596],{},"    Note over B: Waits in line, no snapshot yet\n",[40,598,599],{"class":42,"line":161},[40,600,147],{},[40,602,603],{"class":42,"line":167},[40,604,152],{},[40,606,607],{"class":42,"line":173},[40,608,396],{},[40,610,611],{"class":42,"line":179},[40,612,407],{},[40,614,615],{"class":42,"line":185},[40,616,158],{},[40,618,619],{"class":42,"line":191},[40,620,621],{},"    Note over B: First plain read, the snapshot is fixed only now\n",[40,623,624],{"class":42,"line":197},[40,625,626],{},"    DB-->>B: 80\n",[40,628,629],{"class":42,"line":404},[40,630,631],{},"    B-->>B: Rejected: limit reached\n",[13,633,634],{},"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.",[13,636,637,640],{},[17,638,639],{},"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\":",[30,642,644],{"className":32,"code":643,"language":34,"meta":35,"style":35},"public void addTag(long conversationId, String name) {\n    \u002F\u002F Outside the transaction: look up the conversation and check ownership,\n    \u002F\u002F only to learn which row to lock\n    Customer customer = resolveCustomer(conversationId);\n\n    transactionTemplate.execute(status -> {\n        customerMapper.lockById(customer.getId());   \u002F\u002F first statement in the transaction\n        List\u003CTag> tags = tagMapper.listByCustomer(customer.getId());\n        if (containsName(tags, name)) return null;   \u002F\u002F same name counts as success\n        if (tags.size() >= 100) throw new BusinessException(\"Limit reached\");\n        tagMapper.insert(customer.getId(), name);\n        return null;\n    });\n}\n",[37,645,646,651,656,661,666,670,675,680,685,690,695,700,705,710],{"__ignoreMap":35},[40,647,648],{"class":42,"line":43},[40,649,650],{},"public void addTag(long conversationId, String name) {\n",[40,652,653],{"class":42,"line":49},[40,654,655],{},"    \u002F\u002F Outside the transaction: look up the conversation and check ownership,\n",[40,657,658],{"class":42,"line":55},[40,659,660],{},"    \u002F\u002F only to learn which row to lock\n",[40,662,663],{"class":42,"line":61},[40,664,665],{},"    Customer customer = resolveCustomer(conversationId);\n",[40,667,668],{"class":42,"line":67},[40,669,290],{"emptyLinePlaceholder":289},[40,671,672],{"class":42,"line":73},[40,673,674],{},"    transactionTemplate.execute(status -> {\n",[40,676,677],{"class":42,"line":79},[40,678,679],{},"        customerMapper.lockById(customer.getId());   \u002F\u002F first statement in the transaction\n",[40,681,682],{"class":42,"line":85},[40,683,684],{},"        List\u003CTag> tags = tagMapper.listByCustomer(customer.getId());\n",[40,686,687],{"class":42,"line":155},[40,688,689],{},"        if (containsName(tags, name)) return null;   \u002F\u002F same name counts as success\n",[40,691,692],{"class":42,"line":161},[40,693,694],{},"        if (tags.size() >= 100) throw new BusinessException(\"Limit reached\");\n",[40,696,697],{"class":42,"line":167},[40,698,699],{},"        tagMapper.insert(customer.getId(), name);\n",[40,701,702],{"class":42,"line":173},[40,703,704],{},"        return null;\n",[40,706,707],{"class":42,"line":179},[40,708,709],{},"    });\n",[40,711,712],{"class":42,"line":185},[40,713,88],{},[13,715,716],{},"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.",[22,718,720],{"id":719},"_5-problem-two-a-whole-list-overwrite-with-no-version","5. Problem two: a whole-list overwrite with no version",[13,722,723],{},"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:",[30,725,727],{"className":32,"code":726,"language":34,"meta":35,"style":35},"@Transactional\npublic void saveAll(long shopId, List\u003CItem> items) {\n    List\u003CTitle> current = titleMapper.listByShop(shopId);\n    \u002F\u002F Items with an id are renames, items without one are new,\n    \u002F\u002F and anything in the table but missing from the submission is a delete\n    ...\n}\n",[37,728,729,733,738,743,748,753,758],{"__ignoreMap":35},[40,730,731],{"class":42,"line":43},[40,732,46],{},[40,734,735],{"class":42,"line":49},[40,736,737],{},"public void saveAll(long shopId, List\u003CItem> items) {\n",[40,739,740],{"class":42,"line":55},[40,741,742],{},"    List\u003CTitle> current = titleMapper.listByShop(shopId);\n",[40,744,745],{"class":42,"line":61},[40,746,747],{},"    \u002F\u002F Items with an id are renames, items without one are new,\n",[40,749,750],{"class":42,"line":67},[40,751,752],{},"    \u002F\u002F and anything in the table but missing from the submission is a delete\n",[40,754,755],{"class":42,"line":73},[40,756,757],{},"    ...\n",[40,759,760],{"class":42,"line":79},[40,761,88],{},[13,763,764,765,768],{},"\"Anything in the table but missing from the submission is a delete\" holds under one assumption: ",[17,766,767],{},"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:",[30,770,772],{"className":108,"code":771,"language":110,"meta":35,"style":35},"sequenceDiagram\n    participant X as Admin X\n    participant S as Service\n    participant Y as Admin Y\n    X->>S: Open the dialog\n    S-->>X: Manager, Clerk\n    Y->>S: Open the dialog\n    S-->>Y: Manager, Clerk\n    Y->>S: Add \"Supervisor\" and save\n    Note over S: Table: Manager, Clerk, Supervisor\n    X->>S: Rename \"Clerk\" and save\u003Cbr>Submits: Manager, Store Lead\n    Note over S: \"Supervisor\" is not in the submission\u003Cbr>so it is treated as a delete\n    S-->>X: Saved\n    Note over Y: Y's new \"Supervisor\" is gone, with no warning\n",[37,773,774,778,783,788,793,798,803,808,813,818,823,828,833,838],{"__ignoreMap":35},[40,775,776],{"class":42,"line":43},[40,777,117],{},[40,779,780],{"class":42,"line":49},[40,781,782],{},"    participant X as Admin X\n",[40,784,785],{"class":42,"line":55},[40,786,787],{},"    participant S as Service\n",[40,789,790],{"class":42,"line":61},[40,791,792],{},"    participant Y as Admin Y\n",[40,794,795],{"class":42,"line":67},[40,796,797],{},"    X->>S: Open the dialog\n",[40,799,800],{"class":42,"line":73},[40,801,802],{},"    S-->>X: Manager, Clerk\n",[40,804,805],{"class":42,"line":79},[40,806,807],{},"    Y->>S: Open the dialog\n",[40,809,810],{"class":42,"line":85},[40,811,812],{},"    S-->>Y: Manager, Clerk\n",[40,814,815],{"class":42,"line":155},[40,816,817],{},"    Y->>S: Add \"Supervisor\" and save\n",[40,819,820],{"class":42,"line":161},[40,821,822],{},"    Note over S: Table: Manager, Clerk, Supervisor\n",[40,824,825],{"class":42,"line":167},[40,826,827],{},"    X->>S: Rename \"Clerk\" and save\u003Cbr>Submits: Manager, Store Lead\n",[40,829,830],{"class":42,"line":173},[40,831,832],{},"    Note over S: \"Supervisor\" is not in the submission\u003Cbr>so it is treated as a delete\n",[40,834,835],{"class":42,"line":179},[40,836,837],{},"    S-->>X: Saved\n",[40,839,840],{"class":42,"line":185},[40,841,842],{},"    Note over Y: Y's new \"Supervisor\" is gone, with no warning\n",[13,844,845],{},"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.",[13,847,848,849,852],{},"The fix is to give the list a ",[17,850,851],{},"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:",[30,854,856],{"className":32,"code":855,"language":34,"meta":35,"style":35},"@Transactional\npublic Result saveAll(long shopId, String version, List\u003CItem> items) {\n    shopMapper.lockById(shopId);                       \u002F\u002F still the first statement\n    List\u003CTitle> current = titleMapper.listByShop(shopId);\n    if (!versionOf(current).equals(version)) {\n        return Result.stale(current);                  \u002F\u002F stale draft: reject and return the latest list\n    }\n    ...\n}\n",[37,857,858,862,867,872,876,881,886,890,894],{"__ignoreMap":35},[40,859,860],{"class":42,"line":43},[40,861,46],{},[40,863,864],{"class":42,"line":49},[40,865,866],{},"public Result saveAll(long shopId, String version, List\u003CItem> items) {\n",[40,868,869],{"class":42,"line":55},[40,870,871],{},"    shopMapper.lockById(shopId);                       \u002F\u002F still the first statement\n",[40,873,874],{"class":42,"line":61},[40,875,742],{},[40,877,878],{"class":42,"line":67},[40,879,880],{},"    if (!versionOf(current).equals(version)) {\n",[40,882,883],{"class":42,"line":73},[40,884,885],{},"        return Result.stale(current);                  \u002F\u002F stale draft: reject and return the latest list\n",[40,887,888],{"class":42,"line":79},[40,889,76],{},[40,891,892],{"class":42,"line":85},[40,893,757],{},[40,895,896],{"class":42,"line":155},[40,897,88],{},[13,899,900],{},"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.",[220,902,903],{},[13,904,905,907,908,911],{},[17,906,226],{},": 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 ",[17,909,910],{},"version check",".",[13,913,914,915,918],{},"Both tools solve the same thing, ",[17,916,917],{},"what you read may be out of date by the time you write",", but they fit different situations:",[920,921,922,937],"table",{},[923,924,925],"thead",{},[926,927,928,931,934],"tr",{},[929,930],"th",{},[929,932,933],{},"Row lock (pessimistic)",[929,935,936],{},"Version check (optimistic)",[938,939,940,952,963],"tbody",{},[926,941,942,946,949],{},[943,944,945],"td",{},"Gap between read and write",[943,947,948],{},"Within one request, milliseconds",[943,950,951],{},"Across requests, the user may edit for minutes",[926,953,954,957,960],{},[943,955,956],{},"On conflict",[943,958,959],{},"The later one waits, then continues on fresh data",[943,961,962],{},"The later one is rejected and must redo on fresh data",[926,964,965,968,971],{},[943,966,967],{},"Fits",[943,969,970],{},"Limits, uniqueness, decrements",[943,972,973],{},"Whole-list saves, long forms, draft-style editing",[13,975,976],{},"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.",[22,978,980],{"id":979},"_6-why-ai-tends-to-write-code-like-this","6. Why AI tends to write code like this",[13,982,983,984,987],{},"Looking back at what was sent back, the pieces share one trait: ",[17,985,986],{},"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.",[13,989,990],{},"That also explains why these problems are especially hard to notice in AI-written code:",[992,993,994,1000,1006],"ul",{},[443,995,996,999],{},[17,997,998],{},"The code looks complete."," Transactions, validation, error codes and comments are all there, and a reviewer is easily persuaded by the polish.",[443,1001,1002,1005],{},[17,1003,1004],{},"Self-testing always passes."," One person on one thread can never trigger the interleaving.",[443,1007,1008,1011],{},[17,1009,1010],{},"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.",[13,1013,1014],{},"That last point sets the direction for improvement: what is missing is not knowledge but a checklist that gets run every time.",[22,1016,1018],{"id":1017},"_7-where-to-improve","7. Where to improve",[13,1020,1021,1024],{},[17,1022,1023],{},"For the reviewer: turn the questions above into a decision tree."," Walk through it for any write endpoint:",[30,1026,1028],{"className":108,"code":1027,"language":110,"meta":35,"style":35},"flowchart TD\n    S([\"A write endpoint\"]) --> Q1{\"Does whether or how it writes\u003Cbr>depend on something read first?\"}\n    Q1 -->|No| OK[\"Pass\"]\n    Q1 -->|Yes| Q2{\"What does it read?\"}\n    Q2 -->|Whether one row already exists| U{\"Is there a unique key?\"}\n    U -->|Yes| U1[\"Catch the duplicate-key error\u003Cbr>return a business message\"]\n    U -->|No| U2[\"Add a unique key\"]\n    Q2 -->|The size or contents of a set| L{\"Is the parent row locked\u003Cbr>inside the transaction?\"}\n    L -->|No| L1[\"Add a parent-row lock\"]\n    L -->|Yes| L2{\"Is the lock the first statement?\"}\n    L2 -->|Yes| OK\n    L2 -->|No| L3[\"Move the lock up\u003Cbr>use a programmatic transaction if needed\"]\n    Q2 -->|A full copy sent back by the client| V{\"Is there a version check?\"}\n    V -->|Yes| OK\n    V -->|No| V1[\"Add a version, reject stale drafts\"]\n    style OK fill:#DCFCE7,stroke:#16A34A,color:#14532D\n    style L3 fill:#FEF3C7,stroke:#D97706,color:#78350F\n",[37,1029,1030,1035,1040,1045,1050,1055,1060,1065,1070,1075,1080,1085,1090,1095,1100,1105,1110],{"__ignoreMap":35},[40,1031,1032],{"class":42,"line":43},[40,1033,1034],{},"flowchart TD\n",[40,1036,1037],{"class":42,"line":49},[40,1038,1039],{},"    S([\"A write endpoint\"]) --> Q1{\"Does whether or how it writes\u003Cbr>depend on something read first?\"}\n",[40,1041,1042],{"class":42,"line":55},[40,1043,1044],{},"    Q1 -->|No| OK[\"Pass\"]\n",[40,1046,1047],{"class":42,"line":61},[40,1048,1049],{},"    Q1 -->|Yes| Q2{\"What does it read?\"}\n",[40,1051,1052],{"class":42,"line":67},[40,1053,1054],{},"    Q2 -->|Whether one row already exists| U{\"Is there a unique key?\"}\n",[40,1056,1057],{"class":42,"line":73},[40,1058,1059],{},"    U -->|Yes| U1[\"Catch the duplicate-key error\u003Cbr>return a business message\"]\n",[40,1061,1062],{"class":42,"line":79},[40,1063,1064],{},"    U -->|No| U2[\"Add a unique key\"]\n",[40,1066,1067],{"class":42,"line":85},[40,1068,1069],{},"    Q2 -->|The size or contents of a set| L{\"Is the parent row locked\u003Cbr>inside the transaction?\"}\n",[40,1071,1072],{"class":42,"line":155},[40,1073,1074],{},"    L -->|No| L1[\"Add a parent-row lock\"]\n",[40,1076,1077],{"class":42,"line":161},[40,1078,1079],{},"    L -->|Yes| L2{\"Is the lock the first statement?\"}\n",[40,1081,1082],{"class":42,"line":167},[40,1083,1084],{},"    L2 -->|Yes| OK\n",[40,1086,1087],{"class":42,"line":173},[40,1088,1089],{},"    L2 -->|No| L3[\"Move the lock up\u003Cbr>use a programmatic transaction if needed\"]\n",[40,1091,1092],{"class":42,"line":179},[40,1093,1094],{},"    Q2 -->|A full copy sent back by the client| V{\"Is there a version check?\"}\n",[40,1096,1097],{"class":42,"line":185},[40,1098,1099],{},"    V -->|Yes| OK\n",[40,1101,1102],{"class":42,"line":191},[40,1103,1104],{},"    V -->|No| V1[\"Add a version, reject stale drafts\"]\n",[40,1106,1107],{"class":42,"line":197},[40,1108,1109],{},"    style OK fill:#DCFCE7,stroke:#16A34A,color:#14532D\n",[40,1111,1112],{"class":42,"line":404},[40,1113,1114],{},"    style L3 fill:#FEF3C7,stroke:#D97706,color:#78350F\n",[13,1116,1117,1120],{},[17,1118,1119],{},"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:",[30,1122,1126],{"className":1123,"code":1124,"language":1125,"meta":35,"style":35},"language-txt shiki shiki-themes github-light github-dark github-dark","Self-check for every create, update and delete endpoint:\n1. Check-then-act must be serialized: count limits, name uniqueness and\n   set-consistency checks need either a unique key behind them or a lock on\n   the parent row inside the transaction. A transaction alone is not mutual exclusion.\n2. The lock must come before any plain read in the transaction. If you must\n   query first to know what to lock, do that query outside the transaction and\n   wrap \"lock, read, write\" in a programmatic transaction.\n3. Whole-list or whole-object overwrites must carry a version: for semantics\n   like \"anything missing from the submission is deleted\", verify the version\n   the draft was based on, and reject stale drafts with the latest data.\nIn every plan, state for each write endpoint: what serializes it.\n","txt",[37,1127,1128,1133,1138,1143,1148,1153,1158,1163,1168,1173,1178],{"__ignoreMap":35},[40,1129,1130],{"class":42,"line":43},[40,1131,1132],{},"Self-check for every create, update and delete endpoint:\n",[40,1134,1135],{"class":42,"line":49},[40,1136,1137],{},"1. Check-then-act must be serialized: count limits, name uniqueness and\n",[40,1139,1140],{"class":42,"line":55},[40,1141,1142],{},"   set-consistency checks need either a unique key behind them or a lock on\n",[40,1144,1145],{"class":42,"line":61},[40,1146,1147],{},"   the parent row inside the transaction. A transaction alone is not mutual exclusion.\n",[40,1149,1150],{"class":42,"line":67},[40,1151,1152],{},"2. The lock must come before any plain read in the transaction. If you must\n",[40,1154,1155],{"class":42,"line":73},[40,1156,1157],{},"   query first to know what to lock, do that query outside the transaction and\n",[40,1159,1160],{"class":42,"line":79},[40,1161,1162],{},"   wrap \"lock, read, write\" in a programmatic transaction.\n",[40,1164,1165],{"class":42,"line":85},[40,1166,1167],{},"3. Whole-list or whole-object overwrites must carry a version: for semantics\n",[40,1169,1170],{"class":42,"line":155},[40,1171,1172],{},"   like \"anything missing from the submission is deleted\", verify the version\n",[40,1174,1175],{"class":42,"line":161},[40,1176,1177],{},"   the draft was based on, and reject stale drafts with the latest data.\n",[40,1179,1180],{"class":42,"line":167},[40,1181,1182],{},"In every plan, state for each write endpoint: what serializes it.\n",[13,1184,1185,1186,1189],{},"The last line is the key one. Requiring the plan to ",[17,1187,1188],{},"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.",[13,1191,1192,1195,1196],{},[17,1193,1194],{},"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 ",[17,1197,1198],{},"\"what does this change bypass?\"",[22,1200,1202],{"id":1201},"_8-principles-that-transfer","8. Principles that transfer",[440,1204,1205,1211,1217,1223,1229,1235],{},[443,1206,1207,1210],{},[17,1208,1209],{},"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.",[443,1212,1213,1216],{},[17,1214,1215],{},"A transaction handles \"all or nothing\". It does not handle queuing."," Queuing comes only from a unique key or a lock.",[443,1218,1219,1222],{},[17,1220,1221],{},"A lock has a position requirement."," Under REPEATABLE READ, one plain read ahead of the lock means everything read afterwards is old.",[443,1224,1225,1228],{},[17,1226,1227],{},"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.",[443,1230,1231,1234],{},[17,1232,1233],{},"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.",[443,1236,1237,1240],{},[17,1238,1239],{},"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.",[220,1242,1243],{},[13,1244,1245],{},"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.",[1247,1248,1249],"style",{},"html .light .shiki span {color: var(--shiki-light);background: var(--shiki-light-bg);font-style: var(--shiki-light-font-style);font-weight: var(--shiki-light-font-weight);text-decoration: var(--shiki-light-text-decoration);}html.light .shiki span {color: var(--shiki-light);background: var(--shiki-light-bg);font-style: var(--shiki-light-font-style);font-weight: var(--shiki-light-font-weight);text-decoration: var(--shiki-light-text-decoration);}html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html.dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}",{"title":35,"searchDepth":49,"depth":49,"links":1251},[1252,1253,1254,1255,1256,1257,1258,1259],{"id":24,"depth":49,"text":25},{"id":101,"depth":49,"text":102},{"id":252,"depth":49,"text":253},{"id":498,"depth":49,"text":499},{"id":719,"depth":49,"text":720},{"id":979,"depth":49,"text":980},{"id":1017,"depth":49,"text":1018},{"id":1201,"depth":49,"text":1202},"2026-11-20","An AI delivered a batch of write endpoints with transactions, validation and comments. Each line holds up on its own, yet none of it survives concurrency. From the reviewer's seat, four sequence diagrams cover check-then-act, lock placement and whole-list overwrites, plus how to stop the AI from repeating them.","md",null,"\u002Farticles\u002Freviewing-ai-code-concurrency.svg",{},"\u002Farticles\u002Freviewing-ai-code-concurrency",4.5,"12",{"title":5,"description":1261},{"loc":1266},"articles\u002Freviewing-ai-code-concurrency",[1273,1274],"LLM Apps","Backend","jFfgSJZhVLsU3RqwC_IoG7mWUDXU57UDnaPUuWu60pU",1795761651280]