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..5ffb896efec6 100644 --- a/docs/installation/worker_mode.md +++ b/docs/installation/worker_mode.md @@ -274,4 +274,5 @@ Database connections are automatically managed: - Connections persist across requests for performance - 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 +- Uncommitted transactions are rolled back at the end of each request, and an error is logged +- If rollback fails, the connection is closed and reconnection is attempted before the next request diff --git a/system/Database/Config.php b/system/Database/Config.php index 79b8bcaa6447..66c4c774cae6 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 { @@ -160,6 +161,7 @@ public static function reconnectForWorkerMode(): void { foreach (static::$instances as $connection) { $connection->reconnect(); + $connection->resetTransStatus(); } } @@ -177,14 +179,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..c830839a0e8e 100644 --- a/tests/system/Database/ConfigTest.php +++ b/tests/system/Database/ConfigTest.php @@ -14,10 +14,14 @@ namespace CodeIgniter\Database; use CodeIgniter\Database\Postgre\Connection as PostgreConnection; +use CodeIgniter\Database\SQLite3\Connection as SQLite3Connection; 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 +123,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 +271,142 @@ 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"); + } + + public function testReconnectForWorkerModeAllowsNewTransactionAfterFailedRollback(): void + { + $connection = new class (['DSN' => '', 'database' => ':memory:', 'DBDriver' => 'SQLite3', 'DBDebug' => true]) extends SQLite3Connection { + public bool $failRollback = true; + + protected function _transRollback(): bool + { + if ($this->failRollback) { + return false; + } + + return parent::_transRollback(); + } + }; + + $connection->initialize(); + $this->assertTrue($connection->transStart()); + $this->assertSame(1, $connection->transDepth); + + $this->setPrivateProperty(Config::class, 'instances', ['tests' => $connection]); + + Config::cleanupForWorkerMode(); + + $this->assertSame(1, $connection->transDepth); + $this->assertFalse($this->getPrivateProperty($connection, 'connID')); + $this->assertLogged('error', "Database: Failed to roll back an uncommitted transaction in database group 'tests'. Transaction cleanup aborted."); + + $connection->failRollback = false; + + Config::reconnectForWorkerMode(); + + $this->assertSame(0, $connection->transDepth); + $this->assertTrue($connection->transStatus()); + $this->assertTrue($connection->transStart()); + $this->assertSame(1, $connection->transDepth); + $this->assertTrue($connection->transComplete()); + $this->assertSame(0, $connection->transDepth); + $this->assertTrue($connection->transStatus()); + } + + /** + * @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; + } }