Skip to content

Commit 81f02e6

Browse files
fix: keep writes transactional after MySQL deadlock 1213
InnoDB rolls the victim transaction back and mysqli::commit() still returns true. The next statement now starts a new server transaction, and transCommit() does not report success. Fixes #10649 Co-authored-by: Cursor <cursoragent@cursor.com>
1 parent df8b96b commit 81f02e6

5 files changed

Lines changed: 296 additions & 1 deletion

File tree

‎system/Database/BaseConnection.php‎

Lines changed: 61 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,20 @@ abstract class BaseConnection implements ConnectionInterface
337337
*/
338338
protected $transFailure = false;
339339

340+
/**
341+
* The server has already rolled this transaction back (MySQLi errno 1213).
342+
* mysqli::commit() still returns true, so transCommit() must not report success.
343+
*/
344+
protected bool $transServerRolledBack = false;
345+
346+
/**
347+
* The next statement must open a server transaction before it runs.
348+
* InnoDB ended the previous one and the connection is back in autocommit.
349+
* Errno 1205 does not set this: innodb_rollback_on_timeout decides whether
350+
* that error rolled the transaction back.
351+
*/
352+
protected bool $transNeedsServerRestart = false;
353+
340354
/**
341355
* Whether to throw exceptions during transaction
342356
*/
@@ -1022,6 +1036,7 @@ public function transBegin(bool $testMode = false): bool
10221036

10231037
if ($this->_transBegin()) {
10241038
$this->transDepth++;
1039+
$this->clearServerRolledBackTransaction();
10251040

10261041
return true;
10271042
}
@@ -1039,7 +1054,19 @@ public function transCommit(): bool
10391054
}
10401055

10411056
// When transactions are nested we only begin/commit/rollback the outermost ones
1042-
if ($this->transDepth > 1 || $this->_transCommit()) {
1057+
if ($this->transDepth > 1) {
1058+
$this->transDepth--;
1059+
1060+
return true;
1061+
}
1062+
1063+
// InnoDB already removed the victim transaction. mysqli::commit()
1064+
// returns true anyway, which would publish later writes and report success.
1065+
if ($this->transServerRolledBack) {
1066+
return false;
1067+
}
1068+
1069+
if ($this->_transCommit()) {
10431070
$this->transDepth--;
10441071

10451072
return true;
@@ -1061,6 +1088,10 @@ public function transRollback(): bool
10611088
if ($this->transDepth > 1 || $this->_transRollback()) {
10621089
$this->transDepth--;
10631090

1091+
if ($this->transDepth === 0) {
1092+
$this->clearServerRolledBackTransaction();
1093+
}
1094+
10641095
return true;
10651096
}
10661097

@@ -1089,6 +1120,35 @@ public function handleTransStatus(): void
10891120
}
10901121
}
10911122

1123+
/**
1124+
* Remember that the server has rolled the open transaction back.
1125+
*/
1126+
protected function markServerRolledBackTransaction(): void
1127+
{
1128+
$this->transServerRolledBack = true;
1129+
$this->transNeedsServerRestart = true;
1130+
}
1131+
1132+
/**
1133+
* True once, when the next statement must BEGIN before it runs.
1134+
*/
1135+
protected function consumeServerTransactionRestart(): bool
1136+
{
1137+
if (! $this->transNeedsServerRestart || $this->transDepth < 1) {
1138+
return false;
1139+
}
1140+
1141+
$this->transNeedsServerRestart = false;
1142+
1143+
return true;
1144+
}
1145+
1146+
private function clearServerRolledBackTransaction(): void
1147+
{
1148+
$this->transServerRolledBack = false;
1149+
$this->transNeedsServerRestart = false;
1150+
}
1151+
10921152
/**
10931153
* Begin Transaction
10941154
*/

‎system/Database/MySQLi/Connection.php‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -283,6 +283,14 @@ public function getVersion(): string
283283
*/
284284
protected function execute(string $sql)
285285
{
286+
// Errno 1213 ends the server transaction. Begin again before this
287+
// statement so it does not autocommit. Errno 1205 is not handled:
288+
// innodb_rollback_on_timeout decides whether InnoDB rolled that
289+
// transaction back.
290+
if ($this->connID instanceof mysqli && $this->consumeServerTransactionRestart()) {
291+
$this->connID->begin_transaction();
292+
}
293+
286294
while ($this->connID->more_results()) {
287295
$this->connID->next_result();
288296
if ($res = $this->connID->store_result()) {
@@ -300,6 +308,10 @@ protected function execute(string $sql)
300308
'trace' => render_backtrace($e->getTrace()),
301309
]);
302310

311+
if ((int) $e->getCode() === 1213 && $this->transDepth > 0) {
312+
$this->markServerRolledBackTransaction();
313+
}
314+
303315
if ($this->DBDebug) {
304316
throw new DatabaseException($e->getMessage(), $e->getCode(), $e);
305317
}
Lines changed: 207 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,207 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* This file is part of CodeIgniter 4 framework.
7+
*
8+
* (c) CodeIgniter Foundation <admin@codeigniter.com>
9+
*
10+
* For the full copyright and license information, please view
11+
* the LICENSE file that was distributed with this source code.
12+
*/
13+
14+
namespace CodeIgniter\Database\Live\MySQLi;
15+
16+
use CodeIgniter\Database\BaseConnection;
17+
use CodeIgniter\Test\CIUnitTestCase;
18+
use CodeIgniter\Test\DatabaseTestTrait;
19+
use Config\Database;
20+
use mysqli;
21+
use PHPUnit\Framework\Attributes\Group;
22+
use Throwable;
23+
24+
/**
25+
* InnoDB errno 1213 rolls the victim transaction back. These tests lock two
26+
* rows in opposite orders so the CodeIgniter connection is that victim.
27+
*
28+
* Errno 1205 is a different outcome and is not a passing result here.
29+
*
30+
* @internal
31+
*/
32+
#[Group('DatabaseLive')]
33+
final class DeadlockTransactionTest extends CIUnitTestCase
34+
{
35+
use DatabaseTestTrait;
36+
37+
protected $migrate = false;
38+
private ?BaseConnection $waiter = null;
39+
private ?mysqli $held = null;
40+
private ?string $probeTable = null;
41+
42+
protected function setUp(): void
43+
{
44+
$config = config('Database');
45+
46+
if ($config->tests['DBDriver'] !== 'MySQLi') {
47+
$this->markTestSkipped('Only MySQLi can complete this test.');
48+
}
49+
50+
$this->db = Database::connect($this->DBGroup, false);
51+
52+
parent::setUp();
53+
}
54+
55+
protected function tearDown(): void
56+
{
57+
$this->releaseDeadlock();
58+
59+
parent::tearDown();
60+
}
61+
62+
public function testFollowingWriteDoesNotAutocommitAndTransCommitReturnsFalse(): void
63+
{
64+
$this->assertDeadlockVictimDoesNotPublishTheNextWrite(false);
65+
}
66+
67+
public function testFollowingWriteDoesNotAutocommitAndTransCompleteRollsItBack(): void
68+
{
69+
$this->assertDeadlockVictimDoesNotPublishTheNextWrite(true);
70+
}
71+
72+
private function assertDeadlockVictimDoesNotPublishTheNextWrite(bool $useComplete): void
73+
{
74+
$table = $this->db->escapeIdentifier($this->db->prefixTable('deadlock_probe'));
75+
$this->probeTable = $table;
76+
$this->forceDeadlock($table);
77+
78+
$this->assertSame(1213, (int) $this->db->error()['code']);
79+
$this->assertSame(1, $this->db->transDepth);
80+
81+
$this->db->query('INSERT INTO ' . $table . " (id, note) VALUES (102, 'after')");
82+
83+
$visibleBefore = $this->committedIds($table);
84+
$finished = $useComplete ? $this->db->transComplete() : $this->db->transCommit();
85+
$visibleAfter = $this->committedIds($table);
86+
87+
$this->assertSame(
88+
['visible_before' => [], 'finished' => false, 'visible_after' => []],
89+
[
90+
'visible_before' => $visibleBefore,
91+
'finished' => $finished,
92+
'visible_after' => $visibleAfter,
93+
],
94+
);
95+
}
96+
97+
/**
98+
* Make $this->db the InnoDB deadlock victim. The victim row is id 101.
99+
*/
100+
private function forceDeadlock(string $table): void
101+
{
102+
for ($attempt = 1; $attempt <= 3; $attempt++) {
103+
$this->releaseDeadlock();
104+
$this->resetProbe($table);
105+
106+
$this->waiter = Database::connect($this->DBGroup, false);
107+
$this->waiter->initialize();
108+
$this->waiter->query('SET SESSION innodb_lock_wait_timeout = 3');
109+
$this->waiter->transStart();
110+
111+
for ($i = 0; $i < 20; $i++) {
112+
$this->waiter->query('UPDATE ' . $table . " SET note = 'w{$i}' WHERE id = 1");
113+
}
114+
115+
$held = $this->waiter->getConnection();
116+
$this->assertInstanceOf(mysqli::class, $held);
117+
$this->held = $held;
118+
119+
// The victim has to lock row 2 before the waiter asks for it.
120+
// Sending that request first lets the waiter take row 2, and the
121+
// victim then waits out innodb_lock_wait_timeout (errno 1205).
122+
$this->db->query('SET SESSION innodb_lock_wait_timeout = 3');
123+
$this->db->transException(false);
124+
$this->db->transStart();
125+
$this->db->query('INSERT INTO ' . $table . " (id, note) VALUES (101, 'victim')");
126+
$this->db->query('UPDATE ' . $table . " SET note = 'held' WHERE id = 2");
127+
128+
$this->held->query('UPDATE ' . $table . " SET note = 'waiting' WHERE id = 2", MYSQLI_ASYNC);
129+
usleep(400000);
130+
131+
$this->db->query('UPDATE ' . $table . " SET note = 'closing' WHERE id = 1");
132+
133+
if ((int) $this->db->error()['code'] === 1213) {
134+
return;
135+
}
136+
}
137+
138+
$this->fail('Precondition: InnoDB did not report errno 1213 on the CodeIgniter connection.');
139+
}
140+
141+
private function resetProbe(string $table): void
142+
{
143+
if ($this->db->transDepth > 0) {
144+
$this->db->transRollback();
145+
}
146+
147+
$this->db->query('DROP TABLE IF EXISTS ' . $table);
148+
$this->db->query(
149+
'CREATE TABLE ' . $table . ' ('
150+
. 'id INT NOT NULL, '
151+
. 'note VARCHAR(32) NOT NULL, '
152+
. 'PRIMARY KEY (id)'
153+
. ') ENGINE=InnoDB',
154+
);
155+
$this->db->query('INSERT INTO ' . $table . " (id, note) VALUES (1, 'one'), (2, 'two')");
156+
}
157+
158+
/**
159+
* @return list<int>
160+
*/
161+
private function committedIds(string $table): array
162+
{
163+
$observer = Database::connect($this->DBGroup, false);
164+
$observer->initialize();
165+
$rows = $observer->query('SELECT id FROM ' . $table . ' WHERE id IN (101, 102) ORDER BY id')->getResultArray();
166+
$observer->close();
167+
168+
$ids = [];
169+
170+
foreach ($rows as $row) {
171+
$ids[] = (int) $row['id'];
172+
}
173+
174+
return $ids;
175+
}
176+
177+
private function releaseDeadlock(): void
178+
{
179+
if ($this->held instanceof mysqli) {
180+
try {
181+
$this->held->reap_async_query();
182+
} catch (Throwable) {
183+
// The waiting statement already finished, or the socket is closed.
184+
}
185+
186+
$this->held = null;
187+
}
188+
189+
if ($this->waiter instanceof BaseConnection) {
190+
if ($this->waiter->transDepth > 0) {
191+
$this->waiter->transRollback();
192+
}
193+
194+
$this->waiter->close();
195+
$this->waiter = null;
196+
}
197+
198+
if ($this->db instanceof BaseConnection && $this->db->transDepth > 0) {
199+
$this->db->transRollback();
200+
}
201+
202+
if ($this->probeTable !== null && $this->db instanceof BaseConnection) {
203+
$this->db->query('DROP TABLE IF EXISTS ' . $this->probeTable);
204+
$this->probeTable = null;
205+
}
206+
}
207+
}

‎user_guide_src/source/changelogs/v4.7.6.rst‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,10 @@ Deprecations
3232
Bugs Fixed
3333
**********
3434

35+
- **Database:** Fixed MySQLi errno 1213 (``ER_LOCK_DEADLOCK``) so a following
36+
write on the victim connection does not autocommit, and ``transCommit()``
37+
does not return true after InnoDB has rolled the victim transaction back.
38+
Errno 1205 is unchanged. See `#10649 <https://github.com/codeigniter4/CodeIgniter4/issues/10649>`_.
3539
- **Commands:** Fixed a bug where generator commands did not sort the imports of a template with CRLF line endings.
3640
- **Format:** Fixed ``XMLFormatter`` so that an array key that becomes empty after
3741
sanitization no longer triggers a ``ValueError``; the fallback tag name ``item``

‎user_guide_src/source/database/transactions.rst‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,18 @@ if you would like to run transactions manually you can do so as follows:
145145
.. note:: Make sure to use ``$this->db->transBegin()`` when running manual
146146
transactions, **NOT** ``$this->db->transStart()``.
147147

148+
MySQL Deadlocks
149+
===============
150+
151+
InnoDB error 1213 rolls the victim transaction back. CodeIgniter keeps that
152+
transaction open. The next statement on the same connection starts a new
153+
server transaction, so the write does not autocommit, and ``transCommit()``
154+
returns false. ``transComplete()`` rolls the new server transaction back.
155+
156+
Error 1205 is not handled this way. ``innodb_rollback_on_timeout`` decides
157+
whether InnoDB rolled that transaction back, and the message is the same
158+
either way.
159+
148160
Nested Transactions
149161
===================
150162

0 commit comments

Comments
 (0)