From 5d4f8e2492d43bedd939576de084fb27b69c244e Mon Sep 17 00:00:00 2001 From: Bogdan Date: Fri, 20 Nov 2026 23:56:00 +0100 Subject: [PATCH 1/2] fix: prevent infinite loop in worker mode transaction cleanup --- docs/changelogs/v4.7.7.md | 1 + system/Database/Config.php | 17 ++++- tests/system/Database/ConfigTest.php | 103 +++++++++++++++++++++++++++ 3 files changed, 120 insertions(+), 1 deletion(-) diff --git a/docs/changelogs/v4.7.7.md b/docs/changelogs/v4.7.7.md index 01419ee93694..0d0d69ccc4c7 100644 --- a/docs/changelogs/v4.7.7.md +++ b/docs/changelogs/v4.7.7.md @@ -27,6 +27,7 @@ Release Date: Unreleased - **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. - **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. - **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. +- **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. - **Database:** Fixed a bug where `Postgre`, `OCI8`, and `SQLSRV` `Forge::_dropKeyAsConstraint()` interpolated table, constraint, and schema names without escaping. - **Database:** Fixed a bug where `Postgre\Connection::insertID()` interpolated table, column, and sequence names without escaping. - **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. diff --git a/system/Database/Config.php b/system/Database/Config.php index 79b8bcaa6447..6b4c87b260ec 100644 --- a/system/Database/Config.php +++ b/system/Database/Config.php @@ -16,6 +16,7 @@ use CodeIgniter\Config\BaseConfig; use CodeIgniter\Exceptions\InvalidArgumentException; use Config\Database as DbConfig; +use Throwable; class Config extends BaseConfig { @@ -181,7 +182,21 @@ public static function cleanupForWorkerMode(): void log_message('error', "Uncommitted transaction detected in database group '{$group}'. Transactions must be completed before request ends."); while ($connection->transDepth > 0) { - $connection->transRollback(); + $transDepth = $connection->transDepth; + + try { + $rolledBack = $connection->transRollback(); + } catch (Throwable $e) { + log_message('error', "Database: Failed to roll back an uncommitted transaction in database group '{$group}'. Transaction cleanup aborted: " . $e->getMessage()); + + break; + } + + if (! $rolledBack || $connection->transDepth >= $transDepth) { + log_message('error', "Database: Failed to roll back an uncommitted transaction in database group '{$group}'. Transaction cleanup aborted."); + + break; + } } } diff --git a/tests/system/Database/ConfigTest.php b/tests/system/Database/ConfigTest.php index 980404ea9f3d..356796c2678a 100644 --- a/tests/system/Database/ConfigTest.php +++ b/tests/system/Database/ConfigTest.php @@ -16,8 +16,11 @@ use CodeIgniter\Database\Postgre\Connection as PostgreConnection; use CodeIgniter\Test\CIUnitTestCase; use CodeIgniter\Test\ReflectionHelper; +use CodeIgniter\Test\TestLogger; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\MockObject\MockObject; +use RuntimeException; /** * @internal @@ -119,9 +122,19 @@ final class ConfigTest extends CIUnitTestCase 'port' => 5432, ]; + protected function setUp(): void + { + parent::setUp(); + + $this->setPrivateProperty(TestLogger::class, 'op_logs', []); + } + protected function tearDown(): void { + parent::tearDown(); + $this->setPrivateProperty(Config::class, 'instances', []); + $this->setPrivateProperty(TestLogger::class, 'op_logs', []); } public function testConnectionGroup(): void @@ -257,4 +270,94 @@ public static function provideConvertDSN(): iterable ], ]; } + + public function testCleanupForWorkerModeRollsBackUncommittedTransactions(): void + { + $depth = 3; + $connection = $this->createConnectionMock($depth); + $connection->expects($this->exactly($depth)) + ->method('transRollback') + ->willReturnCallback(static function () use (&$depth): bool { + $depth--; + + return true; + }); + + $this->setPrivateProperty(Config::class, 'instances', ['tests' => $connection]); + + Config::cleanupForWorkerMode(); + + $this->assertSame(0, $depth); + $this->assertFalse(TestLogger::didLog('error', 'Transaction cleanup aborted.', false)); + } + + public function testCleanupForWorkerModeStopsWhenRollbackFails(): void + { + $depth = 2; + $connection = $this->createConnectionMock($depth); + $connection->expects($this->once()) + ->method('transRollback') + ->willReturn(false); + $connection->expects($this->once()) + ->method('resetTransStatus'); + + $this->setPrivateProperty(Config::class, 'instances', ['tests' => $connection]); + + Config::cleanupForWorkerMode(); + + $this->assertSame(2, $depth); + $this->assertLogged('error', "Database: Failed to roll back an uncommitted transaction in database group 'tests'. Transaction cleanup aborted."); + } + + public function testCleanupForWorkerModeStopsWhenRollbackMakesNoProgress(): void + { + $depth = 2; + $connection = $this->createConnectionMock($depth); + $connection->expects($this->once()) + ->method('transRollback') + ->willReturn(true); + $connection->expects($this->once()) + ->method('resetTransStatus'); + + $this->setPrivateProperty(Config::class, 'instances', ['tests' => $connection]); + + Config::cleanupForWorkerMode(); + + $this->assertSame(2, $depth); + $this->assertLogged('error', "Database: Failed to roll back an uncommitted transaction in database group 'tests'. Transaction cleanup aborted."); + } + + public function testCleanupForWorkerModeStopsWhenRollbackThrows(): void + { + $depth = 2; + $connection = $this->createConnectionMock($depth); + $connection->expects($this->once()) + ->method('transRollback') + ->willThrowException(new RuntimeException('MySQL server has gone away')); + $connection->expects($this->once()) + ->method('resetTransStatus'); + + $this->setPrivateProperty(Config::class, 'instances', ['tests' => $connection]); + + Config::cleanupForWorkerMode(); + + $this->assertSame(2, $depth); + $this->assertLogged('error', "Database: Failed to roll back an uncommitted transaction in database group 'tests'. Transaction cleanup aborted: MySQL server has gone away"); + } + + /** + * @param int $depth Current transaction depth reported by the connection. + * + * @return BaseConnection&MockObject + */ + private function createConnectionMock(int &$depth): BaseConnection + { + $connection = $this->createMock(BaseConnection::class); + $connection->method('__get')->willReturnCallback(static function (string $key) use (&$depth): ?int { + return $key === 'transDepth' ? $depth : null; + }); + $connection->method('resetTransStatus')->willReturnSelf(); + + return $connection; + } } From 3680f1d1a7ca8b41c958c1018a98a8a4757a9e44 Mon Sep 17 00:00:00 2001 From: Bogdan Date: Sun, 22 Nov 2026 21:58:06 +0100 Subject: [PATCH 2/2] fix: close the connection after a failed worker transaction rollback cleanupForWorkerMode() runs in the worker loop outside the request's try/catch, so an uncommitted transaction survives a failed rollback and leaks into the next request on the same live connection. BaseConnection::reconnect() abandons a lost transaction, but abandonLostTransaction() only clears transDepth once the connection has been closed. Closing it here lets reconnectForWorkerMode() clear the remaining transaction depth before the next request. The regression tests assert close() on every abort path, and that a successful rollback never closes the connection. --- docs/changelogs/v4.7.7.md | 2 +- docs/installation/worker_mode.md | 1 + system/Database/Config.php | 11 +++++++++++ tests/system/Database/ConfigTest.php | 8 ++++++++ 4 files changed, 21 insertions(+), 1 deletion(-) diff --git a/docs/changelogs/v4.7.7.md b/docs/changelogs/v4.7.7.md index 0d0d69ccc4c7..056fc5edd03a 100644 --- a/docs/changelogs/v4.7.7.md +++ b/docs/changelogs/v4.7.7.md @@ -27,7 +27,7 @@ Release Date: Unreleased - **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. - **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. - **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. -- **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. +- **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. A connection whose rollback fails is now closed, so the open transaction cannot reach the next request. - **Database:** Fixed a bug where `Postgre`, `OCI8`, and `SQLSRV` `Forge::_dropKeyAsConstraint()` interpolated table, constraint, and schema names without escaping. - **Database:** Fixed a bug where `Postgre\Connection::insertID()` interpolated table, column, and sequence names without escaping. - **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. diff --git a/docs/installation/worker_mode.md b/docs/installation/worker_mode.md index b00fca047ca7..58dee224ad54 100644 --- a/docs/installation/worker_mode.md +++ b/docs/installation/worker_mode.md @@ -275,3 +275,4 @@ Database connections are automatically managed: - Connections are validated at the start of each request - Failed connections are automatically re-established - Uncommitted transactions are automatically rolled back with a warning logged +- A connection whose rollback fails is closed, so the open transaction cannot reach the next request diff --git a/system/Database/Config.php b/system/Database/Config.php index 6b4c87b260ec..da9ce494c194 100644 --- a/system/Database/Config.php +++ b/system/Database/Config.php @@ -178,6 +178,8 @@ public static function reconnectForWorkerMode(): void public static function cleanupForWorkerMode(): void { foreach (static::$instances as $group => $connection) { + $rollbackFailed = false; + if ($connection->transDepth > 0) { log_message('error', "Uncommitted transaction detected in database group '{$group}'. Transactions must be completed before request ends."); @@ -188,18 +190,27 @@ public static function cleanupForWorkerMode(): void $rolledBack = $connection->transRollback(); } catch (Throwable $e) { log_message('error', "Database: Failed to roll back an uncommitted transaction in database group '{$group}'. Transaction cleanup aborted: " . $e->getMessage()); + $rollbackFailed = true; break; } if (! $rolledBack || $connection->transDepth >= $transDepth) { log_message('error', "Database: Failed to roll back an uncommitted transaction in database group '{$group}'. Transaction cleanup aborted."); + $rollbackFailed = true; break; } } } + if ($rollbackFailed) { + // A live connection would carry the open transaction into the + // next request. reconnectForWorkerMode() clears the remaining + // transaction depth before it establishes a new connection. + $connection->close(); + } + $connection->resetTransStatus(); } } diff --git a/tests/system/Database/ConfigTest.php b/tests/system/Database/ConfigTest.php index 356796c2678a..319a70c67414 100644 --- a/tests/system/Database/ConfigTest.php +++ b/tests/system/Database/ConfigTest.php @@ -275,6 +275,8 @@ public function testCleanupForWorkerModeRollsBackUncommittedTransactions(): void { $depth = 3; $connection = $this->createConnectionMock($depth); + $connection->expects($this->never()) + ->method('close'); $connection->expects($this->exactly($depth)) ->method('transRollback') ->willReturnCallback(static function () use (&$depth): bool { @@ -298,6 +300,8 @@ public function testCleanupForWorkerModeStopsWhenRollbackFails(): void $connection->expects($this->once()) ->method('transRollback') ->willReturn(false); + $connection->expects($this->once()) + ->method('close'); $connection->expects($this->once()) ->method('resetTransStatus'); @@ -316,6 +320,8 @@ public function testCleanupForWorkerModeStopsWhenRollbackMakesNoProgress(): void $connection->expects($this->once()) ->method('transRollback') ->willReturn(true); + $connection->expects($this->once()) + ->method('close'); $connection->expects($this->once()) ->method('resetTransStatus'); @@ -334,6 +340,8 @@ public function testCleanupForWorkerModeStopsWhenRollbackThrows(): void $connection->expects($this->once()) ->method('transRollback') ->willThrowException(new RuntimeException('MySQL server has gone away')); + $connection->expects($this->once()) + ->method('close'); $connection->expects($this->once()) ->method('resetTransStatus');