Skip to content

Commit daf35d4

Browse files
committed
fix: prevent infinite loop in worker mode transaction cleanup
1 parent e4d791d commit daf35d4

3 files changed

Lines changed: 117 additions & 1 deletion

File tree

‎docs/changelogs/v4.7.7.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ Release Date: Unreleased
2727
- **Cache:** Fixed a bug where `PredisHandler::increment()` and `PredisHandler::decrement()` updated the unused `'data'` hash field instead of `'__ci_value'`, causing `get()` to return stale values for existing counters.
2828
- **CORS:** Fixed a bug where `Cors::hasResponseHeaders()` matched header substrings via `str_contains()`, causing false positives when existing exposed headers shared a prefix with configured exposed headers.
2929
- **Database:** Fixed a bug where `BaseConnection::prepare()` did not reset pretend mode when the closure threw an exception, leaving the connection in pretend mode so that subsequent queries on it were silently discarded.
30+
- **Database:** Fixed an infinite loop in `Database\Config::cleanupForWorkerMode()` when `transRollback()` failed, threw, or did not change the transaction depth, which hung the FrankenPHP worker process after a request left an uncommitted transaction.
3031
- **Database:** Fixed a bug where `Postgre`, `OCI8`, and `SQLSRV` `Forge::_dropKeyAsConstraint()` interpolated table, constraint, and schema names without escaping.
3132
- **Database:** Fixed a bug where `Postgre\Connection::insertID()` interpolated table, column, and sequence names without escaping.
3233
- **Database:** Fixed a bug where `SQLSRV\Builder::_upsertBatch()` concatenated `$table` unescaped into `Object_ID()`, causing syntax errors for table names with quotes or special characters.

‎system/Database/Config.php‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
use CodeIgniter\Config\BaseConfig;
1717
use CodeIgniter\Exceptions\InvalidArgumentException;
1818
use Config\Database as DbConfig;
19+
use Throwable;
1920

2021
class Config extends BaseConfig
2122
{
@@ -181,7 +182,21 @@ public static function cleanupForWorkerMode(): void
181182
log_message('error', "Uncommitted transaction detected in database group '{$group}'. Transactions must be completed before request ends.");
182183

183184
while ($connection->transDepth > 0) {
184-
$connection->transRollback();
185+
$transDepth = $connection->transDepth;
186+
187+
try {
188+
$rolledBack = $connection->transRollback();
189+
} catch (Throwable $e) {
190+
log_message('error', "Database: Failed to roll back an uncommitted transaction in database group '{$group}'. Transaction cleanup aborted: " . $e->getMessage());
191+
192+
break;
193+
}
194+
195+
if (! $rolledBack || $connection->transDepth >= $transDepth) {
196+
log_message('error', "Database: Failed to roll back an uncommitted transaction in database group '{$group}'. Transaction cleanup aborted.");
197+
198+
break;
199+
}
185200
}
186201
}
187202

‎tests/system/Database/ConfigTest.php‎

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,10 @@
1616
use CodeIgniter\Database\Postgre\Connection as PostgreConnection;
1717
use CodeIgniter\Test\CIUnitTestCase;
1818
use CodeIgniter\Test\ReflectionHelper;
19+
use CodeIgniter\Test\TestLogger;
1920
use PHPUnit\Framework\Attributes\DataProvider;
2021
use PHPUnit\Framework\Attributes\Group;
22+
use RuntimeException;
2123

2224
/**
2325
* @internal
@@ -119,9 +121,19 @@ final class ConfigTest extends CIUnitTestCase
119121
'port' => 5432,
120122
];
121123

124+
protected function setUp(): void
125+
{
126+
parent::setUp();
127+
128+
$this->setPrivateProperty(TestLogger::class, 'op_logs', []);
129+
}
130+
122131
protected function tearDown(): void
123132
{
133+
parent::tearDown();
134+
124135
$this->setPrivateProperty(Config::class, 'instances', []);
136+
$this->setPrivateProperty(TestLogger::class, 'op_logs', []);
125137
}
126138

127139
public function testConnectionGroup(): void
@@ -257,4 +269,92 @@ public static function provideConvertDSN(): iterable
257269
],
258270
];
259271
}
272+
273+
public function testCleanupForWorkerModeRollsBackUncommittedTransactions(): void
274+
{
275+
$depth = 3;
276+
$connection = $this->createConnectionMock($depth);
277+
$connection->expects($this->exactly($depth))
278+
->method('transRollback')
279+
->willReturnCallback(static function () use (&$depth): bool {
280+
$depth--;
281+
282+
return true;
283+
});
284+
285+
$this->setPrivateProperty(Config::class, 'instances', ['tests' => $connection]);
286+
287+
Config::cleanupForWorkerMode();
288+
289+
$this->assertSame(0, $depth);
290+
$this->assertFalse(TestLogger::didLog('error', 'Transaction cleanup aborted.', false));
291+
}
292+
293+
public function testCleanupForWorkerModeStopsWhenRollbackFails(): void
294+
{
295+
$depth = 2;
296+
$connection = $this->createConnectionMock($depth);
297+
$connection->expects($this->once())
298+
->method('transRollback')
299+
->willReturn(false);
300+
$connection->expects($this->once())
301+
->method('resetTransStatus');
302+
303+
$this->setPrivateProperty(Config::class, 'instances', ['tests' => $connection]);
304+
305+
Config::cleanupForWorkerMode();
306+
307+
$this->assertSame(2, $depth);
308+
$this->assertLogged('error', "Database: Failed to roll back an uncommitted transaction in database group 'tests'. Transaction cleanup aborted.");
309+
}
310+
311+
public function testCleanupForWorkerModeStopsWhenRollbackMakesNoProgress(): void
312+
{
313+
$depth = 2;
314+
$connection = $this->createConnectionMock($depth);
315+
$connection->expects($this->once())
316+
->method('transRollback')
317+
->willReturn(true);
318+
$connection->expects($this->once())
319+
->method('resetTransStatus');
320+
321+
$this->setPrivateProperty(Config::class, 'instances', ['tests' => $connection]);
322+
323+
Config::cleanupForWorkerMode();
324+
325+
$this->assertSame(2, $depth);
326+
$this->assertLogged('error', "Database: Failed to roll back an uncommitted transaction in database group 'tests'. Transaction cleanup aborted.");
327+
}
328+
329+
public function testCleanupForWorkerModeStopsWhenRollbackThrows(): void
330+
{
331+
$depth = 2;
332+
$connection = $this->createConnectionMock($depth);
333+
$connection->expects($this->once())
334+
->method('transRollback')
335+
->willThrowException(new RuntimeException('MySQL server has gone away'));
336+
$connection->expects($this->once())
337+
->method('resetTransStatus');
338+
339+
$this->setPrivateProperty(Config::class, 'instances', ['tests' => $connection]);
340+
341+
Config::cleanupForWorkerMode();
342+
343+
$this->assertSame(2, $depth);
344+
$this->assertLogged('error', "Database: Failed to roll back an uncommitted transaction in database group 'tests'. Transaction cleanup aborted: MySQL server has gone away");
345+
}
346+
347+
/**
348+
* @param int $depth Current transaction depth reported by the connection.
349+
*/
350+
private function createConnectionMock(int &$depth): BaseConnection
351+
{
352+
$connection = $this->createMock(BaseConnection::class);
353+
$connection->method('__get')->willReturnCallback(static function (string $key) use (&$depth) {
354+
return $key === 'transDepth' ? $depth : null;
355+
});
356+
$connection->method('resetTransStatus')->willReturnSelf();
357+
358+
return $connection;
359+
}
260360
}

0 commit comments

Comments
 (0)