Modular logistics and supply chain operating system (LSOS)
JavaScript driver-appfleet-managementfreight-managementinfrastructureinventory-managementlast-mile-deliverylogisticsondemandopen-sourceorder-managementroute-optimizationsupply-chain-managementtracking-and-monitoringtransport-management-systemtransportationwarehouse-management
fix(api): stop a committed write from reporting "There is no active transaction"
Ronald A. Richardson8556ea8532ba
diff --git a/api/app/Providers/AppServiceProvider.php b/api/app/Providers/AppServiceProvider.phpindex 1170659a..a35e8d62 100644--- a/api/app/Providers/AppServiceProvider.php+++ b/api/app/Providers/AppServiceProvider.php@@ -2,6 +2,12 @@namespace App\Providers;+use Illuminate\Database\Connection;+use Illuminate\Database\Events\QueryExecuted;+use Illuminate\Database\Events\TransactionBeginning;+use Illuminate\Database\Events\TransactionCommitting;+use Illuminate\Support\Facades\DB;+use Illuminate\Support\Facades\Event;use Illuminate\Support\Facades\Http;use Illuminate\Support\Facades\Log;use Illuminate\Support\ServiceProvider;@@ -10,6 +16,18 @@ use Psr\Http\Message\RequestInterface;class AppServiceProvider extends ServiceProvider{+ /**+ * Ring buffer of recent statements, kept only while the transaction tripwire is armed.+ *+ * @var array<int, string>+ */+ protected static array $recentStatements = [];++ /**+ * Whether a divergence has already been reported on this worker pass.+ */+ protected static bool $divergenceReported = false;+/*** Register any application services.*@@ -28,6 +46,116 @@ class AppServiceProvider extends ServiceProviderpublic function boot(){$this->configureOutboundHttpLogging();+ $this->configureTransactionTripwire();+ }++ /**+ * Detect the moment Laravel's transaction counter stops agreeing with the MySQL session.+ *+ * Laravel decides whether to issue a COMMIT from its own integer counter+ * (ManagesTransactions::commit(), and the inline twin inside transaction()),+ * while PDO decides whether a COMMIT is legal from the server's+ * SERVER_STATUS_IN_TRANS flag. If anything ends the server-side transaction+ * without going through the Connection - an implicit commit from DDL, or a+ * second PDO handle aliasing the same persistent MySQL session - the counter+ * keeps saying "1". Every statement issued since BEGIN is then already+ * durable, and the eventual commit throws "There is no active transaction",+ * so the caller reports failure for a write that landed.+ *+ * This logs the divergence at the statement that caused it, which is the+ * only place the culprit is still identifiable.+ */+ protected function configureTransactionTripwire(): void+ {+ if (!env('DB_TXN_TRIPWIRE_ENABLED', false)) {+ return;+ }++ // One report per transaction, not one per worker: a worker serves up to+ // --max-requests before it recycles, and a single latched flag would hide+ // every occurrence after the first.+ Event::listen(TransactionBeginning::class, function (TransactionBeginning $event) {+ if ($event->connection->transactionLevel() === 1) {+ static::$divergenceReported = false;+ }+ });++ DB::listen(function (QueryExecuted $query) {+ $this->recordStatement($query->sql);++ if ($query->connection->transactionLevel() < 1) {+ return;+ }++ $pdo = $query->connection->getRawPdo();++ if (!$pdo instanceof \PDO || $pdo->inTransaction()) {+ return;+ }++ $this->reportTransactionDivergence($query->connection, 'after-statement', $query->sql);+ });++ // Backstop: the divergence may be caused by something we never see as a+ // query of ours (another PDO handle on the same session). This catches it+ // immediately before the doomed COMMIT.+ Event::listen(TransactionCommitting::class, function (TransactionCommitting $event) {+ $pdo = $event->connection->getRawPdo();++ if ($pdo instanceof \PDO && !$pdo->inTransaction()) {+ $this->reportTransactionDivergence($event->connection, 'at-commit', null);+ }+ });+ }++ protected function recordStatement(string $sql): void+ {+ static::$recentStatements[] = Str::limit(preg_replace('/\s+/', ' ', $sql), 200);++ if (count(static::$recentStatements) > 25) {+ array_shift(static::$recentStatements);+ }+ }++ protected function reportTransactionDivergence(Connection $connection, string $phase, ?string $sql): void+ {+ // One report per worker pass. Re-entrancy guard as well: the CONNECTION_ID()+ // lookup below is itself a query and would otherwise trip the listener.+ if (static::$divergenceReported) {+ return;+ }++ static::$divergenceReported = true;++ $pdo = $connection->getRawPdo();++ try {+ $mysqlConnectionId = $pdo instanceof \PDO+ ? $pdo->query('SELECT CONNECTION_ID()')->fetchColumn()+ : null;+ } catch (\Throwable $e) {+ $mysqlConnectionId = 'unavailable: ' . $e->getMessage();+ }++ Log::error('[db:txn:divergence] transaction ended outside the Connection', [+ 'phase' => $phase,+ 'statement' => $sql === null ? null : Str::limit(preg_replace('/\s+/', ' ', $sql), 300),+ 'connection' => $connection->getName(),+ 'transaction_level' => $connection->transactionLevel(),+ 'pdo_object_id' => $pdo instanceof \PDO ? spl_object_id($pdo) : null,+ 'connection_object_id'=> spl_object_id($connection),+ 'mysql_connection_id' => $mysqlConnectionId,+ 'recent_statements' => static::$recentStatements,+ 'trace' => $this->applicationTrace(),+ ]);+ }++ protected function applicationTrace(): array+ {+ return collect(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 60))+ ->map(fn ($frame) => ($frame['file'] ?? '?') . ':' . ($frame['line'] ?? '?'))+ ->values()+ ->all();}protected function configureOutboundHttpLogging(): voiddiff --git a/api/config/octane.php b/api/config/octane.phpindex ed4b9324..8e1fd35b 100644--- a/api/config/octane.php+++ b/api/config/octane.php@@ -105,8 +105,21 @@ return [OperationTerminated::class => [FlushOnce::class,FlushTemporaryContainerInstances::class,- DisconnectFromDatabases::class,- CollectGarbage::class,+ // DisconnectFromDatabases::class,+ //+ // Left disabled, as upstream Octane ships it. It was enabled in+ // a5a5ddb to stop connection-pool exhaustion under load, but it never+ // did that: the mysql connections are opened with PDO::ATTR_PERSISTENT,+ // so disconnect() drops the PHP object and leaves the MySQL session+ // open in PHP's persistent pool. Measured on this stack: 40 concurrent+ // requests left 17 connections open and still idle minutes later.+ //+ // What it did do is churn a fresh PDO handle per request over that one+ // persistent session, which is how two live handles end up aliasing a+ // single MySQL transaction. A COMMIT through either handle ends the+ // transaction for both, and the loser's commit throws "There is no+ // active transaction" on a write that has already been made durable.+ CollectGarbage::class,],WorkerErrorOccurred::class => [