Skip to content

Avoid reauthenticating when database was changed - #1671

Merged
bgrainger merged 9 commits into
mysql-net:masterfrom
VerstraeteNick:reset-without-reauth
Oct 26, 2026
Merged

bgrainger merged 9 commits into
mysql-net:masterfrom
VerstraeteNick:reset-without-reauth

Conversation

@VerstraeteNick

@VerstraeteNick VerstraeteNick commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary (updated to match the final code; the original description below is partly out of date)

Relates to #1561 and #1534. When a pooled session's database has been changed (with ChangeDatabase, or a USE that the server reported through session tracking), the pool now selects the connection string's Database again without reauthenticating, so ProvidePasswordCallback isn't called. That's the problem #1534 and #1561 run into with IAM authentication.

What the pool sends when it reuses a session whose database was changed:

Connection string and server Before After
Database set, ConnectionReset=true, MySQL ≥ 5.7.3 or MariaDB ≥ 10.2.4 COM_CHANGE_USER (reauthenticates), SET NAMES COM_RESET_CONNECTION, SET NAMES, COM_INIT_DB: one write when pipelining is on, three round trips with Pipelining=False or UseCompression=True
Database set, ConnectionReset=false, any server COM_CHANGE_USER (reauthenticates), SET NAMES COM_INIT_DB only
No Database COM_CHANGE_USER (reauthenticates), SET NAMES Unchanged: reauthenticating is the only way to deselect a database
ConnectionReset=true, MySQL < 5.7.3 or MariaDB < 10.2.4 COM_CHANGE_USER (reauthenticates), SET NAMES Unchanged

Sessions whose database wasn't changed are unaffected.

  • COM_INIT_DB is sent after SET NAMES: on MySQL, COM_RESET_CONNECTION reverts character_set_client to the server default (bug 97633), and the server decodes the database name with it.
  • COM_INIT_DB is sent whenever the database was changed, even if it was changed back to the connection string's database, because a later USE might not have been tracked.
  • If COM_INIT_DB fails (database dropped or access revoked), Open() throws and the session is discarded, as when COM_CHANGE_USER fails.
  • Without reauthentication (as for any pooled reuse where the database didn't change), a locked or re-passworded account isn't rejected, privileges and default roles aren't re-read, and MAX_CONNECTIONS_PER_HOUR isn't charged. The general log shows Init DB instead of Change user.
  • With ConnectionReset=false, a session whose database changed is no longer reset: user variables and other session state carry over, and ConnectionOpenedCallback gets MySqlConnectionOpenedConditions.None instead of Reset.
  • The pipelined bytes including COM_INIT_DB are built on first use and cached per session.
  • These paths log the new Debug events 2162 (reset and restore) and 2163 (restore only, ConnectionReset=false) instead of 2112.
  • connection-options.md now describes the database restore under ConnectionReset=false.

Round trips when pipelined: MySQL 8.0 goes from 3 to 1 and MariaDB from 2 to 1. Without pipelining, MySQL stays at 3 and MariaDB goes from 2 to 3. With 50 ms added in each direction in front of MySQL 8.0.46, a pooled reopen after ChangeDatabase went from about 360 ms to about 125 ms.

Tests: FakeMySqlServer records the commands it receives and can withhold the reset reply until the whole pipelined batch arrives. The unit tests cover:

  • command order, pipelined and not
  • a 400-byte non-ASCII database name
  • changing back to the same database (COM_INIT_DB is still sent)
  • the COM_CHANGE_USER fallbacks (no Database, MySQL 5.7.2, MariaDB 10.2.3)
  • ConnectionReset=false sending only COM_INIT_DB, also on MySQL 5.7.2 and MariaDB 10.2.3
  • a failing COM_INIT_DB

The integration tests check that:

  • after ChangeDatabase (sync and async) or USE, the reopened connection is in the connection string's database, user variables are cleared (kept with ConnectionReset=false), and ProvidePasswordCallback was called once
  • an untracked USE made after changing to the same database is undone
  • a pool without Database still reauthenticates

CI passes on MariaDB 10.11–12.3, MySQL 8.4, 9.7 and 26.10, .NET Framework and .NET 8/10/11. The ordering that matters for a latin1 server with a non-ASCII database name is only covered by the unit tests' command-order assertions, not against a real server.


Original description, kept for reference. The parts about skipping COM_INIT_DB when the database was changed back are out of date.

Relates to #1561. This implements the approach described in #1561 (comment), following your suggestion in #1534.

Changed since my comment on #1561, as you suggested: if the database was changed back to the connection string's database (ordinal comparison), COM_INIT_DB is skipped and the session gets a plain reset. Your other notes were already covered: the reset and COM_INIT_DB bytes are cached per session (built on first use rather than at connect time, so sessions that never change database don't pay for it), the non-pipelined path still avoids reauthentication (three round trips), this path has its own log event, and the FakeMySqlServer tests check the command order.

When a pooled session's database has been changed (with ChangeDatabase, or a USE detected through session tracking) and the connection string specifies a Database, the reset now sends COM_RESET_CONNECTION, SET NAMES, then COM_INIT_DB for that database, instead of COM_CHANGE_USER. With pipelining, the three packets go out in one write. With ConnectionReset=false, only COM_INIT_DB is sent. The server doesn't authenticate the user again and ProvidePasswordCallback isn't called, which is what #1534 and #1561 run into with IAM authentication.

Database changed, Database set Before After, pipelined (default) After, Pipelining=False or UseCompression=True
MySQL 8.0 3 round trips (COM_CHANGE_USER, auth switch, SET NAMES) 1 round trip 3 round trips
MariaDB (from the code, not run) 2 round trips (COM_CHANGE_USER, SET NAMES) 1 round trip 3 round trips (one more than today)

Connection strings without a Database and sessions whose database wasn't changed are unchanged, and so are MySQL < 5.7.3 and MariaDB < 10.2.4 unless ConnectionReset=false.

With a proxy adding 50 ms in each direction in front of MySQL 8.0.46, a pooled reopen after ChangeDatabase went from about 360 ms to about 125 ms, the same as a reopen where the database didn't change. With Pipelining=False it stays at about 360 ms, but without authenticating.

  • COM_INIT_DB has to follow SET NAMES: on MySQL, COM_RESET_CONNECTION reverts character_set_client to the server default (bug 97633), and the server decodes the database name with it. On a server started with --character-set-server=latin1 and a database named café, the other order makes Open() fail; this order works pipelined, with Pipelining=False and with UseCompression=True. CI's MySQL servers are utf8mb4 with ASCII database names, so the ordered command list in the unit tests is what guards this.
  • If the database was changed back to the connection string's database, COM_INIT_DB is skipped: COM_RESET_CONNECTION keeps the current database selected.
  • If COM_INIT_DB fails (database dropped, or access to it revoked), Open() throws the same error as today and the session is discarded.
  • Without reauthentication (as for any pooled reuse where the database didn't change), a locked or re-passworded account isn't rejected, privileges and default roles aren't re-read, and MAX_CONNECTIONS_PER_HOUR isn't charged. The general log shows Init DB instead of Change user.
  • With ConnectionReset=false, a session whose database changed used to be reset by COM_CHANGE_USER. Now it only gets COM_INIT_DB (nothing if the database was changed back), on any server version, so it keeps its session state like any other ConnectionReset=false session and COM_RESET_CONNECTION is never sent. Without a Database, it still uses COM_CHANGE_USER.
  • The pipelined bytes including COM_INIT_DB are cached per session.
  • These paths log the new Debug events 2162 (reset) and 2163 (ConnectionReset=false) instead of 2112.

Tests: FakeMySqlServer now records the commands it receives and can withhold the reset reply until all three pipelined commands arrive. This verifies pipelining independently of TCP read boundaries. The unit tests check the command order with and without pipelining, a 400-byte non-ASCII database name, changing back to the same database (no COM_INIT_DB), the COM_CHANGE_USER fallbacks (no Database, MySQL 5.7.2, MariaDB 10.2.3), ConnectionReset=false sending only COM_INIT_DB (also on MySQL 5.7.2 and MariaDB 10.2.3) and a failing COM_INIT_DB. The integration tests check that after ChangeDatabase (sync and async) or USE (sync), the reopened connection has the connection string's database selected and user variables cleared (kept with ConnectionReset=false), and that ProvidePasswordCallback was called once; they include ConnectionReset=false cases and a sync test that a pool without Database still reauthenticates. The new tests fail on master, except the ones for unchanged behaviour.

Locally (net10.0, MySQL 8.0.46) the unit and integration tests pass, except SslSecurityTests and Metrics.ConnectionTimeTests, which fail here on master too; the pooling and reset tests also pass with UseCompression=True and Pipelining=False. I haven't run net11.0, MariaDB or MySQL 8.4 and later.

connection-options.md says ConnectionReset=false "avoids making an additional server round trip", which already isn't the case once the database has changed. I can add a sentence about that here if you'd like.

When a pooled session's database had been changed (with
MySqlConnection.ChangeDatabase, or a USE statement detected through
session tracking), retrieving it from the pool sent COM_CHANGE_USER just
to select the connection string's database again, even with
ConnectionReset=false. That is a full authentication exchange on every
such Open (two round trips on MySQL 8.0, plus SET NAMES), which is
expensive with IAM authentication.

If the connection string specifies a Database and the server supports
COM_RESET_CONNECTION, send COM_RESET_CONNECTION, SET NAMES, then
COM_INIT_DB for that database instead, as suggested in mysql-net#1534. COM_INIT_DB
is sent last because the server decodes the database name with
character_set_client, which COM_RESET_CONNECTION resets to the server
default. With pipelining, all three packets are sent in one write, so the
reset takes one round trip. If the database was changed back to the
connection string's database (compared ordinally), COM_INIT_DB is
skipped, because COM_RESET_CONNECTION keeps the current database.

As before, Open returns a reset session with the connection string's
database selected. COM_CHANGE_USER is still used if the connection
string has no Database (reauthenticating is the only way to deselect a
database) and for servers that don't support COM_RESET_CONNECTION. If
COM_INIT_DB fails (e.g., the database was dropped), the error is thrown
from Open and the session is discarded, as for a failed COM_CHANGE_USER.

Relates to mysql-net#1561.

Signed-off-by: Nick Verstraete <nick.verstraete@peripass.com>
Signed-off-by: Nick Verstraete <nick.verstraete@peripass.com>
Signed-off-by: Nick Verstraete <nick.verstraete@peripass.com>
With ConnectionReset=false, the pool only resets a session whose database
was changed. Select the connection string's database again with COM_INIT_DB
instead of resetting the session, so the session state is kept (as
documented for ConnectionReset=false) and no COM_RESET_CONNECTION or
pipelined packets are sent, as before. If the database was changed back to
the connection string's database, nothing is sent.

If the connection string doesn't specify a database, COM_CHANGE_USER is
still needed to deselect the current database.

Signed-off-by: Bradley Grainger <bgrainger@gmail.com>
Test cs.Database.Length instead of string.IsNullOrWhiteSpace; it can't be
null. Remove the assertion that 'cs' is the pool's ConnectionSettings.
Clear DatabaseOverride in the reset path only once the database has been
restored, consistently for the pipelined and non-pipelined paths.

Signed-off-by: Bradley Grainger <bgrainger@gmail.com>
@bgrainger bgrainger self-assigned this Oct 25, 2026
Select the connection string's database again whenever DatabaseOverride is set, in case it's been changed by an untracked 'USE' statement. When pipelining is enabled, this adds no round trip.

Signed-off-by: Bradley Grainger <bgrainger@gmail.com>
Signed-off-by: Bradley Grainger <bgrainger@gmail.com>
@bgrainger

Copy link
Copy Markdown
Member

if the database was changed back to the connection string's database (ordinal comparison), COM_INIT_DB is skipped and the session gets a plain reset

after further review, I've changed this back to submit a COM_INIT_DB packet (to ensure the right DB is selected), which can be pipelined for no additional roundtrip.

Signed-off-by: Bradley Grainger <bgrainger@gmail.com>
@adamkirkton

Copy link
Copy Markdown

@VerstraeteNick Thank you so much for doing this! I gave up on figuring out a solution for this but this looks like it can work for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

3 participants