Skip to content

Commit e3e3644

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 ef9f864 commit e3e3644

5 files changed

Lines changed: 293 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
*/
@@ -1046,6 +1060,7 @@ public function transBegin(bool $testMode = false): bool
10461060

10471061
if ($this->_transBegin()) {
10481062
$this->transDepth++;
1063+
$this->clearServerRolledBackTransaction();
10491064

10501065
return true;
10511066
}
@@ -1063,7 +1078,19 @@ public function transCommit(): bool
10631078
}
10641079

10651080
// When transactions are nested we only begin/commit/rollback the outermost ones
1066-
if ($this->transDepth > 1 || $this->_transCommit()) {
1081+
if ($this->transDepth > 1) {
1082+
$this->transDepth--;
1083+
1084+
return true;
1085+
}
1086+
1087+
// InnoDB already removed the victim transaction. mysqli::commit()
1088+
// returns true anyway, which would publish later writes and report success.
1089+
if ($this->transServerRolledBack) {
1090+
return false;
1091+
}
1092+
1093+
if ($this->_transCommit()) {
10671094
$this->transDepth--;
10681095

10691096
return true;
@@ -1085,6 +1112,10 @@ public function transRollback(): bool
10851112
if ($this->transDepth > 1 || $this->_transRollback()) {
10861113
$this->transDepth--;
10871114

1115+
if ($this->transDepth === 0) {
1116+
$this->clearServerRolledBackTransaction();
1117+
}
1118+
10881119
return true;
10891120
}
10901121

@@ -1113,6 +1144,35 @@ public function handleTransStatus(): void
11131144
}
11141145
}
11151146

1147+
/**
1148+
* Remember that the server has rolled the open transaction back.
1149+
*/
1150+
protected function markServerRolledBackTransaction(): void
1151+
{
1152+
$this->transServerRolledBack = true;
1153+
$this->transNeedsServerRestart = true;
1154+
}
1155+
1156+
/**
1157+
* True once, when the next statement must BEGIN before it runs.
1158+
*/
1159+
protected function consumeServerTransactionRestart(): bool
1160+
{
1161+
if (! $this->transNeedsServerRestart || $this->transDepth < 1) {
1162+
return false;
1163+
}
1164+
1165+
$this->transNeedsServerRestart = false;
1166+
1167+
return true;
1168+
}
1169+
1170+
private function clearServerRolledBackTransaction(): void
1171+
{
1172+
$this->transServerRolledBack = false;
1173+
$this->transNeedsServerRestart = false;
1174+
}
1175+
11161176
/**
11171177
* Begin Transaction
11181178
*/

‎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: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ Bugs Fixed
3939
- **CLI:** Fixed a bug where a prompt asked again forever when its input was piped or redirected and ran out before a valid answer: ``CLI::prompt()`` and ``CLI::promptByKey()`` whose default fails the validation rules, and ``CLI::promptByMultipleKeys()`` whose options have string keys. They now throw a ``CLIException``. The new ``InputOutput::isAtEnd()`` tells that end of the input from an empty line. Pressing Ctrl+D at a terminal still asks again.
4040
- **Commands:** Fixed a bug where generator commands did not sort the imports of a template with CRLF line endings.
4141
- **Database:** Fixed ``reconnect()`` so a replaced socket does not keep the transaction that died with the old connection. ``transDepth`` is cleared and the transaction status is failed before the new connection is opened, so a failed reconnect cannot still report success. OCI8 commit mode returns to autocommit. ``transComplete()`` does not report success. This applies when ``ping()`` reports the connection lost; PostgreSQL's ``pg_ping()`` reconnects a broken connection itself, so it is not covered.
42+
- **Database:** Fixed MySQLi errno 1213 (``ER_LOCK_DEADLOCK``) so a following write on the victim connection does not autocommit, and ``transCommit()`` does not return true after InnoDB has rolled the victim transaction back. Errno 1205 is unchanged. See `#10649 <https://github.com/codeigniter4/CodeIgniter4/issues/10649>`_.
4243
- **Format:** Fixed ``XMLFormatter`` so that an array key that becomes empty after sanitization no longer triggers a ``ValueError``; the fallback tag name ``item`` is used instead. Values that cannot be converted to a string, such as objects not implementing ``Stringable``, now throw a ``FormatException`` instead of a fatal ``Error``.
4344
- **Helpers:** Fixed a regression in v4.7.5 where ``set_value()`` threw a ``TypeError`` when the default value was not a string or an array, such as an integer, a float, ``null``, or a ``Stringable`` object. Such values are now converted to a string.
4445
- **HTTP:** Fixed a bug in ``ContentSecurityPolicy`` where a numeric source such as ``'0'`` threw a ``TypeError``, and a space-separated directive string in ``Config\\ContentSecurityPolicy`` was emitted as one unquoted source.

‎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)