orm: Syntax error or access violation: 1305 SAVEPOINT DOCTRINE_x does not exist

Feature Request

Q A
New Feature yes
RFC yes
BC Break no?

Summary

Hi,

We see exception Syntax error or access violation: 1305 SAVEPOINT DOCTRINE_205 does not exist every now&then.

It comes from https://github.com/doctrine/orm/blob/ccfc97c32f63aaa0988ac6aa42e71c5590bb794d/lib/Doctrine/ORM/UnitOfWork.php#L485

Im looking for ways to debug it, but i’m worried the original exception is hidden.

Im wondering if we could try/catch it and let the original exception bubble up.

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 22 (8 by maintainers)

Commits related to this issue

Most upvoted comments

I write simple PHP script for illustrate problem (with deadlock):

<?php

namespace Acme;

use Doctrine\DBAL\Connection;
use Doctrine\DBAL\DriverManager;
use Doctrine\DBAL\Tools\DsnParser;
use Symfony\Component\Process\Process;

include_once __DIR__.'/vendor/autoload.php';

define('PHP_EXECUTABLE', '/usr/local/bin/php');
define('DATABASE_URL', 'pdo-mysql://lottery-user:Q1w2e3r4@lottery-db:3306/lottery?serverVersion=8.0');

function isUseSavepoints(): bool
{
    $argv = $_SERVER['argv'] ?? [];

    return ($argv[1] ?? null) === 'savepoint' || ($argv[2] ?? null) === 'savepoint';
}

function makeConnection(): Connection
{
    $dsnParser = new DsnParser();
    $connectionParams = $dsnParser
        ->parse(DATABASE_URL);

    $connection = DriverManager::getConnection($connectionParams);
    $connection->setNestTransactionsWithSavepoints(isUseSavepoints());

    return $connection;
}

function prepareDb(Connection $connection): void
{
    $connection->executeStatement('DROP TABLE IF EXISTS tbl1');
    $connection->executeStatement('DROP TABLE IF EXISTS tbl2');

    $connection->executeStatement('CREATE TABLE tbl1 (id VARCHAR(255), b VARCHAR(255))');
    $connection->executeStatement('CREATE TABLE tbl2 (id VARCHAR(255), b VARCHAR(255))');

    $connection->executeStatement('INSERT INTO tbl1 (id, b) VALUES (1, 1)');
    $connection->executeStatement('INSERT INTO tbl2 (id, b) VALUES (1, 1)');
}

$process = $argv[1] ?? '';

if ('' === $process || 'savepoint' === $process) {
    $connection = makeConnection();
    prepareDb($connection);

    print 'Successfully initialize test tables in DB.'.PHP_EOL.PHP_EOL;

    /** @var Process[] $processes */
    $processes = [];

    $processes['session 1'] = new Process([
        PHP_EXECUTABLE,
        __FILE__,
        'first',
        isUseSavepoints() ? 'savepoint' : '',
        '&',
    ]);

    $processes['session 2'] = new Process([
        PHP_EXECUTABLE,
        __FILE__,
        'second',
        isUseSavepoints() ? 'savepoint' : '',
        '&',
    ]);

    foreach ($processes as $session => $process) {
        $process->start(function ($type, $output) use ($session) {
            print '---'.$session.'---'.PHP_EOL;
            print $output.PHP_EOL;
            print '<--'.$session.'--- END'.PHP_EOL;
        });
    }

    foreach ($processes as $process) {
        $process->wait();
    }
}

function waitBetweenProcesses(): void
{
    usleep(1 * (10 ** 6));
}

if ('first' === $process) {
    $connection = makeConnection();

    $connection->beginTransaction();
    $connection->executeStatement('UPDATE tbl1 SET b = 1 WHERE id = 1');

    print 'Session #1: Success execute start transaction and update tbl1.'.PHP_EOL;
    waitBetweenProcesses();

    print 'UPDATE tbl2'.PHP_EOL;
    $connection->executeStatement('UPDATE tbl2 SET b = 1 WHERE id = 1;');
}

if ('second' === $process) {
    usleep(0.5 * (10 ** 6)); // Wait 0.5 second (timeout between processes - 0.5 second).
    $connection = makeConnection();

    $connection->beginTransaction();
    $connection->executeStatement('UPDATE tbl2 SET b = 1 WHERE id = 1');

    print 'Session #2: Success execute start transaction and update tbl2.'.PHP_EOL;
    waitBetweenProcesses();

    print 'UPDATE tbl1'.PHP_EOL;

    if (isUseSavepoints()) {
        try { // This block really imitate EntityManager::flush inside opened transaction (inside DoctrineTransactionMiddleware as an example)
            $connection->beginTransaction();
            $connection->executeStatement('UPDATE tbl1 SET b = 1 WHERE id = 1;');
        } catch (\Throwable $error) {
            $connection->rollBack();
        }
    } else {
        $connection->executeStatement('UPDATE tbl1 SET b = 1 WHERE id = 1;');
    }
}

You can run:

php script.php                 # without savepoints
php script.php savepoint       # with savepoints

If we run without savepoints, we see real error - deadlock. But if we run with savepoints we see error - savepoint does not exist.

I am not an expert in Doctrine, much less in DBAL, but maybe better will be throw real (origin) error on DBAL side (because in any cases origin error is deadlock from MySQL)?

P.S. Sorry for big PHP code…

also if you’re tracking transaction level in custom connection middleware, the count will be totally broken after switching to savepoints.

Because without savepoints, the transaction level is pretty much a boolean?

I can reproduce it locally 😃

DROP TABLE IF EXISTS tbl1 ;
DROP TABLE IF EXISTS tbl2 ;

CREATE TABLE tbl1
(
    id VARCHAR(255) PRIMARY KEY,
    b  VARCHAR(255)
);
CREATE TABLE tbl2
(
    id VARCHAR(255) PRIMARY KEY,
    b  VARCHAR(255)
);

INSERT INTO tbl1 (id, b)
VALUES (1, 1);
INSERT INTO tbl2 (id, b)
VALUES (1, 1);

Test without savepoint

Session #1 Session #2 Description
START TRANSACTION;
UPDATE tbl1 SET b = 1 WHERE id = 1;
START TRANSACTION;
UPDATE tbl2 SET b = 1 WHERE id = 1;
UPDATE tbl2 SET b = 1 WHERE id = 1; wait lock (locked in session #2)
UPDATE tbl1 SET b = 1 WHERE id = 1; Deadlock (recursion)
COMMIT;
ROLLBACK; Entity manager call rollback

Test with savepoints

Session #1 Session #2 Description
START TRANSACTION;
UPDATE tbl1 SET b = 1 WHERE id = 1;
START TRANSACTION;
SAVEPOINT savepoint_1;
UPDATE tbl2 SET b = 1 WHERE id = 1;
UPDATE tbl2 SET b = 1 WHERE id = 1; wait lock (locked in session #2)
UPDATE tbl1 SET b = 1 WHERE id = 1; Deadlock (recursion)
COMMIT;
ROLLBACK TO savepoint_1; Entity manager call rollback (ERROR)

Sorry for more SQL.

By documentation from MySQL https://dev.mysql.com/doc/refman/8.0/en/innodb-error-handling.html DEADLOCK will lead rollback the entire transaction. As result, in session #2 after deadlock error we CANNOT execute rollback to savepoint, because MySQL roll back ENTIRE transaction, but by default logic in EntityManager::flush (UnitOfWork::commit) - after catched error system try to execute rollback.

P.S. This is only possible if save points are enabled. If savepoints are disabled (by default in Dbal 3.*) - developers not see this error, because system not open savepoints.

I am hitting the same issue on the bootstrap of unit test

<?php

use App\Kernel;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Dotenv\Dotenv;

require dirname(__DIR__).'/vendor/autoload.php';

if (file_exists(dirname(__DIR__).'/config/bootstrap.php')) {
    require dirname(__DIR__).'/config/bootstrap.php';
} elseif (method_exists(Dotenv::class, 'bootEnv')) {
    (new Dotenv())->bootEnv(dirname(__DIR__).'/.env');
}

$kernel = new Kernel('test', true); // create a "test" kernel
$kernel->boot();

$application = new Application($kernel);
$application->setAutoExit(false);

$commands = [
    ['command' => 'doctrine:schema:drop', '--force' => true, '--full-database' => true, '--quiet' => true],
    //['command' => 'doctrine:schema:create'],
    ['command' => 'doctrine:migrations:migrate', '--no-interaction' => true],
    ['command' => 'doctrine:fixtures:load', '--append' => true, '-v'],
];

foreach ($commands as $command) {
    $application->run(new ArrayInput(is_array($command) ? $command : [
        'command' => $command,
    ]), new ConsoleOutput());
}

If I use doctrine:migrations:migrate then I hit the issue during the fixtures:load, if I use doctrine:schema:create then no issue

The database is in the same state after doctrine:migrations:migrate or doctrine:schema:create

If I make all migrations non transactional with

    public function isTransactional(): bool
    {
        return false;
    }

Then I don’t get the issue. (Though I get a warning Exception in third-party event subscriber: There is no active transaction, but that seems to be because of the ‘–full-database’ option)

Why is a previous command influencing the state of a future command?

Just read the full thread while trying to find out what @ro0NL meant by “eg. due SAVEPOINT DOCTRINE_2 does not exist” in #11423 … wouldn’t the next logical step be to file a DBAL bug report?

So, if I understand the issue correctly, the DBAL does not detect a deadlock correctly and thus assumes a wrong transaction nesting level? This needs to be fixed in the DBAL then.

both errors are real to me 😅 i mean, in both cases “concurrent mysql” is the issue

im not sure how to deal with it on DBAL/ORM side either. That’s future work for maintainers 😃

for now im going to opt-out our command from running transactional (it’s not a real requirement for this specific case), that solves the issue as well. Im not really happy with try/catching the commit/rollback flow really, even though the “return bool” API allows for it.

eventually maybe just take some error percentage for granted as well, but time will tell.

If savepoints are required for application, then developer should total control it.

but we cant in case of concurrency, because “mysql”. Note im not an infrastructural expert 😉

also IIUC doctrine/orm:^3 will enforce savepoints either way

i just thought it was nice to have command execution wrapped in a transaction by default

i think i’ll rewrite our transaction middleware so that it only creates an outer transaction, and thus avoid nested savepoints in this case.

I’m guessing this is MySQL? Do you by change perform any DDL operations

Correct, and not that i’m aware of 😅

Since we already had a custom connection middleware, i’ve added this gem to exec() for now:

        if (str_starts_with($sql, 'ROLLBACK TO SAVEPOINT ')) {
            // @see https://github.com/doctrine/orm/issues/11230
            try {
                return parent::exec($sql);
            } catch (\Throwable $e) {
                $this->logger->warning('Failed to rollback to savepoint', ['exception' => $e]);

                return 0;
            }
        }

        return parent::exec($sql);

Will monitor prod today to see if it reveals our issue 👍