Skip to content

Commit 5d4f8e2

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

3 files changed

Lines changed: 120 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: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,11 @@
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 PHPUnit\Framework\MockObject\MockObject;
23+
use RuntimeException;
2124

2225
/**
2326
* @internal
@@ -119,9 +122,19 @@ final class ConfigTest extends CIUnitTestCase
119122
'port' => 5432,
120123
];
121124

125+
protected function setUp(): void
126+
{
127+
parent::setUp();
128+
129+
$this->setPrivateProperty(TestLogger::class, 'op_logs', []);
130+
}
131+
122132
protected function tearDown(): void
123133
{
134+
parent::tearDown();
135+
124136
$this->setPrivateProperty(Config::class, 'instances', []);
137+
$this->setPrivateProperty(TestLogger::class, 'op_logs', []);
125138
}
126139

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

0 commit comments

Comments
 (0)