diff --git a/docs/changelogs/v4.7.7.md b/docs/changelogs/v4.7.7.md index 01419ee93694..056fc5edd03a 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. 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 79b8bcaa6447..da9ce494c194 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 { @@ -177,14 +178,39 @@ 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."); 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()); + $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 980404ea9f3d..319a70c67414 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,102 @@ public static function provideConvertDSN(): iterable ], ]; } + + 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 { + $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('close'); + $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('close'); + $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('close'); + $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; + } }