Skip to content

PDO pool: a slot carries no defined state or configuration contract (incl. silent TLS downgrade) #203

Closed

Description

@EdmondDantes

Summary

A pooled connection has no defined contract for what it carries or how it is taken. Five symptoms, one root problem:

  • Nothing is applied on acquire, so a slot never receives the configuration the user asked for, whether given to the constructor or to setAttribute() (A, B). A is a silent TLS downgrade.
  • Nothing is reset on release, so a slot arrives carrying the previous coroutine's session state (C, D).
  • A slot is taken when none is needed (E).

All five confirmed by execution on 8.6.0-dev ZTS DEBUG, TrueAsync ABI v0.24.0, true_async 0.7.10, MySQL 8 (have_ssl=YES, TLSv1.2/1.3). All are silent — no warning, no error.


A. Constructor driver options reach no slot — TLS is silently dropped

pdo_pool_factory calls the driver with no options at all:

if (UNEXPECTED(!dbh->driver->db_handle_factory(conn, NULL))) {   /* options = NULL */

So every driver-specific option given to the PDO constructor is ignored for pooled connections, including the TLS ones. Confirmed with a deliberately unusable CA, so the two outcomes cannot be confused:

<?php
$dsn = "mysql:host=127.0.0.1;port=3306;dbname=test";
$ssl = [
    PDO::ATTR_ERRMODE                      => PDO::ERRMODE_EXCEPTION,
    Pdo\Mysql::ATTR_SSL_CA                 => '/nonexistent/definitely-not-a-ca.pem',
    Pdo\Mysql::ATTR_SSL_VERIFY_SERVER_CERT => true,
];

foreach ([['direct', []],
          ['pooled', [PDO::ATTR_POOL_ENABLED => true, PDO::ATTR_POOL_MIN => 0, PDO::ATTR_POOL_MAX => 2]]]
         as [$name, $extra]) {
    try {
        $pdo = new PDO($dsn, "test", "test", $ssl + $extra);
        $c = $pdo->query("SHOW SESSION STATUS LIKE 'Ssl_cipher'")->fetch(PDO::FETCH_ASSOC)['Value'];
        echo str_pad($name, 8), "CONNECTED, Ssl_cipher='", $c, "'\n";
    } catch (Throwable $e) {
        echo str_pad($name, 8), "REFUSED: ", substr($e->getMessage(), 0, 90), "\n";
    }
}
direct  REFUSED: SQLSTATE[HY000] [2002] Cannot connect to MySQL using SSL
pooled  CONNECTED, Ssl_cipher=''

The direct connection correctly refuses an unverifiable CA. The pooled one connects in plaintext — Ssl_cipher is empty — having ignored both ATTR_SSL_CA and ATTR_SSL_VERIFY_SERVER_CERT.

An application that configures TLS with certificate verification gets unencrypted connections the moment it enables pooling. Credentials and query data go over the wire in the clear, with no error and nothing in the logs to notice. Enabling a performance feature silently removes transport security.

Same mechanism, also confirmed — ATTR_MULTI_STATEMENTS => false is ignored, because ext/pdo_mysql/mysql_driver.c:753-758 reads:

if (!driver_options) { connect_opts |= CLIENT_MULTI_STATEMENTS; }

An option set to disable something ends up enabling it:

  multi-statement via pooled conn accepted: true      <-- option ignored
  multi-statement via direct conn accepted: false     <-- correct, same options

By the same path (mysql_driver.c:905-958), INIT_COMMAND, ATTR_TIMEOUT, COMPRESS, LOCAL_INFILE, FOUND_ROWS, IGNORE_SPACE and the remaining SSL_* options are dropped too.

B. setAttribute() reaches one slot only

ext/pdo/pdo_dbh.c:1084-1097 dispatches to the currently acquired conn; ext/pdo_mysql/mysql_driver.c:479-490 writes dbh->auto_commit on that slot, never the template. Slots created later keep the stale template value.

For ATTR_AUTOCOMMIT this loses data. Four coroutines, each inserting a row then calling rollBack():

  coro0 autocommit=0 rollBack=true
  coro1 autocommit=1 rollBack='EXCEPTION: There is no active transaction'
  coro2 autocommit=1 rollBack='EXCEPTION: There is no active transaction'
  coro3 autocommit=1 rollBack='EXCEPTION: There is no active transaction'

SURVIVED ROLLBACK (should be empty): ["coro1","coro2","coro3"]

Three of four rows committed despite an explicit rollBack(). getAttribute(ATTR_AUTOCOMMIT) reports false the whole time.

C. Session state leaks between coroutines

pdo_mysql registers NULL for both pool hooks (ext/pdo_mysql/mysql_driver.c:714-715), so release only rolls back in_txn and clears the error code. Everything else stays on the wire.

With POOL_MAX => 1 (forces reuse of the same physical connection), coroutine B inherits from A:

A conn id: 505
A GET_LOCK: 1
B conn id: 505
B sees @secret   : 'coroutine-A-data'
B sees sql_mode  : 'ANSI_QUOTES'
B sees time_zone : '+05:00'
B sees temp table: 42
B IS_USED_LOCK   : 505

sql_mode=ANSI_QUOTES changes how " is parsed, so identical SQL can mean different things per coroutine. time_zone silently shifts every TIMESTAMP. A held GET_LOCK is the worst: other coroutines block on a lock nobody in their code took, and only that connection can release it.

Reproducer
<?php
$dsn = "mysql:host=localhost;unix_socket=/var/run/mysqld/mysqld.sock;dbname=test";
$pdo = new PDO($dsn, "test", "test", [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_POOL_ENABLED => true,
    PDO::ATTR_POOL_MIN => 0, PDO::ATTR_POOL_MAX => 1,
]);

Async\await(Async\spawn(function () use ($pdo) {
    echo "A conn id: ",  $pdo->query("SELECT CONNECTION_ID()")->fetchColumn(), "\n";
    $pdo->exec("SET @secret = 'coroutine-A-data'");
    $pdo->exec("SET SESSION sql_mode = 'ANSI_QUOTES'");
    $pdo->exec("SET SESSION time_zone = '+05:00'");
    $pdo->exec("CREATE TEMPORARY TABLE tmp_a (v INT)");
    $pdo->exec("INSERT INTO tmp_a VALUES (42)");
    echo "A GET_LOCK: ", $pdo->query("SELECT GET_LOCK('leaky', 0)")->fetchColumn(), "\n";
}));

Async\await(Async\spawn(function () use ($pdo) {
    echo "B conn id: ",       $pdo->query("SELECT CONNECTION_ID()")->fetchColumn(), "\n";
    echo "B sees @secret   : '", $pdo->query("SELECT @secret")->fetchColumn(), "'\n";
    echo "B sees sql_mode  : '", $pdo->query("SELECT @@session.sql_mode")->fetchColumn(), "'\n";
    echo "B sees time_zone : '", $pdo->query("SELECT @@session.time_zone")->fetchColumn(), "'\n";
    echo "B sees temp table: ",  $pdo->query("SELECT v FROM tmp_a")->fetchColumn(), "\n";
    echo "B IS_USED_LOCK   : ",  $pdo->query("SELECT IS_USED_LOCK('leaky')")->fetchColumn(), "\n";
}));

D. Transaction opened with raw SQL is never rolled back

The auto-rollback checks PDO's own flag rather than the server state — ext/pdo/pdo_pool.c, pdo_pool_before_release:

if (conn->in_txn && conn->methods) { ... }   /* in_txn is set only by beginTransaction() */

So START TRANSACTION via exec(), and implicit transactions under autocommit=0, skip the rollback entirely and the open transaction is handed to the next coroutine:

=== RAW SQL (START TRANSACTION) ===
  A: conn=507 open_trx=1
  B: conn=507 inherited_open_trx=1 sees_uncommitted_rows=1     <-- leaked

=== PDO::beginTransaction() ===
  A: conn=508 open_trx=0
  B: conn=509 inherited_open_trx=0 sees_uncommitted_rows=0     <-- correct

The next coroutine reads dirty data and inherits row locks it never took. pdo_mysql already exposes the real state via pdo_mysql_in_transaction (mysql_driver.c:687-692) — it just isn't consulted.

E. inTransaction() takes a slot it does not need and never gives it back

pdo_is_in_transaction() (ext/pdo/pdo_dbh.c:757-767) calls pdo_pool_acquire_conn() with no matching pdo_pool_maybe_release(). The same helper is the precheck inside beginTransaction() / commit() / rollBack().

bool(false)
  after inTransaction() (main flow)  count=1 idle=0 active=1
bool(false)
  inside coroutine after inTransaction count=2 idle=0 active=2
  after coroutine finished           count=2 idle=1 active=1

active goes 0 → 1 for a call that reports "no transaction" and needs no connection at all; in the main flow the slot stays pinned for the whole request. Frameworks that call inTransaction() defensively will reach ATTR_POOL_MAX far sooner than the workload warrants.

Not a crash — a capacity bug, but on the same acquire path as A and B.


Suggested direction

  1. Acquire — where does a slot's configuration come from? Constructor driver_options should be stashed on the template and passed to db_handle_factory in pdo_pool_factory; connection-level attributes set later should be recorded on the template and re-applied per slot in pool_before_acquire. That covers A and B and makes getAttribute() mean something again. Given the TLS result, until this is fixed it is worth refusing to create a pool when security-relevant options were passed, rather than silently downgrading.

  2. Release — what must a connection have forgotten before it goes back? For pdo_mysql, a pool_before_release hook issuing COM_RESET_CONNECTION (mysqlnd_conn::reset_connection) covers C and D at once, returning false on failure so the pool destroys a connection it could not clean. Independently, pdo_pool_before_release should prefer conn->methods->in_transaction(conn) over the in_txn flag. The same question then applies to pdo_pgsql (DISCARD ALL).

  3. Acquire discipline — for E, use pdo_pool_peek_conn() and report false when no connection is bound: no connection means no transaction, so acquiring one cannot change the answer.

Environment

PHP        8.6.0-dev (cli) (ZTS DEBUG TrueAsync ABI v0.24.0)
true_async 0.7.10
pdo_mysql  8.6.0-dev
MySQL      8.x, have_ssl=YES, TLSv1.2/TLSv1.3
OS         Linux 6.6.114.1-microsoft-standard-WSL2

Found while auditing the pool code path for #200. All five are pre-existing and independent of that fix.

Activity

  1. changed the title [-]Pooled MySQL connections are recycled without a session reset — state leaks between coroutines[/-] [+]PDO pool: a slot carries no defined state or configuration contract[/+] on Jul 22, 2026
  2. changed the title [-]PDO pool: a slot carries no defined state or configuration contract[/-] [+]PDO pool: a slot carries no defined state or configuration contract (incl. silent TLS downgrade)[/+] on Jul 22, 2026
  3. added
    bug
    on Jul 22, 2026
  4. self-assigned this
    on Jul 22, 2026
  5. EdmondDantes commented on Jul 22, 2026

    @EdmondDantes
    ContributorAuthor

    One more item for the acquire half, found while auditing the #200 branch.

    F. PDO::ATTR_POOL_MIN does nothing — pre-warm is dead code

    ZEND_ASYNC_NEW_POOL pre-warms the pool inside zend_async_pool_create_internal, but pdo_pool_create assigns user_data only after that call returns:

    dbh->pool = ZEND_ASYNC_NEW_POOL(..., (uint32_t)min_size, ...);   /* pre-warm runs here */
    ...
    dbh->pool->user_data = dbh;                                       /* too late */

    Every pre-warm factory call therefore bails out immediately at the top of pdo_pool_factory:

    const pdo_dbh_t *dbh = (const pdo_dbh_t *)pool->user_data;
    if (UNEXPECTED(dbh == NULL || dbh->driver == NULL)) {
        return false;
    }

    Confirmed: idleCount() is 0 right after constructing with POOL_MIN => 3. So the connections a user asks to have ready up front are never created, and the first N coroutines each pay full connect latency — exactly what POOL_MIN exists to avoid.

    Belongs with the rest of this issue: it is the same question of what the pool is supposed to have set up before handing anything out.

    Fix is ordering — set user_data before the pool is created (or pass it into the create call) so the pre-warm factory can see the template.

    Note for whoever touches the tests: several existing pool tests pass POOL_MIN => 1 on the assumption that it warms a connection. It does not, so no test currently fails because of this.

  6. added 7 commits that reference this issue on Jul 23, 2026
  7. EdmondDantes commented on Jul 23, 2026

    @EdmondDantes
    ContributorAuthor

    All five symptoms fixed in php-src true-async-stable, across changelog PRs #209 (A), #210 (acquire half), #211 (release half), all merged.

    • A — constructor driver_options now reach the slot: pdo_pool_factory builds connections with the real options instead of NULL, so ATTR_SSL_CA / ATTR_SSL_VERIFY_SERVER_CERT / ATTR_MULTI_STATEMENTS etc. are honored; enabling the pool no longer silently downgrades TLS. Test: ext/pdo_sqlite/tests/pool_012_driver_specific_options_applied.phpt.
    • B — setAttribute() is recorded on the template and re-applied to every slot on acquire. Test: ext/pdo/tests/pdo_pool_024_set_attribute_reaches_every_slot.phpt.
    • C/D — session state and raw-SQL / implicit transactions no longer leak to the next coroutine: reset is issued on acquire (COM_RESET_CONNECTION for mysqlnd), the constructor-configured state is restored after the reset, and auto-rollback consults the real driver state instead of the in_txn flag. A session-state detector also catches state hidden behind leading comments and versioned/executable comments (/*! */, /*M! */); DDL no longer pins a slot. Tests: pdo_pool_025_raw_sql_transaction_not_leaked, pdo_pool_026_session_state_not_leaked, pdo_pool_027_reset_restores_connect_state, pdo_pool_028_session_state_behind_a_disguise.
    • E — inTransaction() uses pdo_pool_peek_conn() and reports false without acquiring a slot; ATTR_POOL_STMT_CACHE_SIZE no longer takes a connection just by being passed. Tests: ext/pdo_sqlite/tests/pool_015_in_transaction_takes_no_slot, pool_013_stmt_cache_option_takes_no_slot.

    Closing as completed.

  8. added a commit that references this issue on Jul 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions