Skip to content

fix: failover and read/write splitting use the plugin service's host list provider in aio - #1371

Merged
JuanLeee merged 2 commits into
mainfrom
fix/integration-test-failures-2
Nov 19, 2026
Merged

JuanLeee merged 2 commits into
mainfrom
fix/integration-test-failures-2

Conversation

@JuanLeee

@JuanLeee JuanLeee commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Description

Since #1292 (a2ac1ada, 2026-10-28, after the 3.1.0 release), the first async connection to an Aurora instance endpoint, an IP or a custom domain starts on AsyncStaticHostListProvider, built from the guessed dialect, and the plugin service swaps in the Aurora provider once the dialect is confirmed. AsyncFailoverPlugin and AsyncReadWriteSplittingPlugin keep the provider they were built with, so on that connection writer failover can keep reconnecting to the old writer, as every gdb_failover writer-failover test did in run 43391980255, reader failover sees only the seed host and set_read_only(True) stays on the writer. The replacement provider also never gets the probe its topology monitor needs for panic mode. Two older async gaps are on the failover path: an error raised while the wrapper creates the driver cursor reaches the application raw, and reader failover marks every reader, and the original writer, it couldn't reach as unavailable for 5 minutes, for every async connection in the process. Two more defects reach sync code: the stale DNS helper, in both engines, keeps a deleted writer cached, so after a failover a connect to the writer cluster endpoint can be sent to the old writer; and a sync mysql-connector cursor from before a failover raises ReferenceError on close, which in a with block replaces the failover error.

On main, the integration tests' failover helper can run past pytest's 600 s --timeout, which ends the whole session, and returns while the old writer is still restarting, and GitHub's integration jobs lose 1 to 3 tests per run when an Aurora instance or the cluster endpoint stops accepting connections in the middle of a session.

This PR makes the async plugins read the plugin service's provider, as the sync plugins already do, subscribes async failover to cursor creation as sync failover is and drops the reader-failover marks as sync failover v2 and JDBC's failover2 do. It fixes the stale DNS reset in both engines and the sync cursor's connection, and in the test harness it bounds the failover helper by one deadline, waits for the RDS status available before each test and reruns a test once after a cluster outage.

  1. AsyncFailoverPlugin and AsyncReadWriteSplittingPlugin stored the provider build_async_plugins handed them and refreshed through it: in _do_failover's topology refresh, in the writer loop AsyncRetryUtil.get_writer_connection and in read/write splitting's switches. For a connection whose guessed dialect is RDS_PG, RDS_MYSQL, PG or MYSQL, that provider is the static one and returns only the seed host, so writer failover ended with "[Failover] Unable to establish SQL connection to the writer instance." and set_read_only(True) logged "[ReadWriteSplittingPlugin] A reader instance was requested via set_read_only, but there are no readers in the host list" and stayed on the writer. Both classes now read _host_list_provider from plugin_service.host_list_provider through a read-only property, falling back to the factory's provider only when the service has none, and AsyncGdbFailoverPlugin and AsyncGdbReadWriteSplittingPlugin inherit it. Classic cluster endpoints were unaffected, because their guess is already Aurora; the cluster-group endpoints feat: add new RDS endpoint pattern #1366 adds are guessed like instance endpoints.
  2. AsyncPluginServiceImpl._update_host_list_provider copied the panic-mode probe onto the replacement provider only when the previous provider had one, and AsyncStaticHostListProvider never does. The Aurora provider that replaced a static one therefore built its topology monitor without a probe, so _should_panic returned False and the monitor never searched the hosts for the new writer once its own monitoring connection was gone. The service now builds the probe with build_probe_host when the previous provider has none and sets it before its first force_refresh_host_list, as the wrapper already does for the provider it builds first.
  3. AsyncFailoverPlugin._SUBSCRIBED didn't list Connection.cursor. The async wrapper creates the driver cursor on the first cursor operation and sends that call through the plugin pipeline, so on a broken connection the driver's error reached the application and failover never started: in run 43391980255, test_fail_from_reader_to_writer_async failed on Aurora PostgreSQL with psycopg.OperationalError "the connection is closed", raised from _resolve_target_cursor. CONNECTION_CURSOR is now subscribed, as it is in sync failover v1 and v2 through the driver dialect's network-bound methods, so the error starts failover. The gap dates from feat: asyncio support (async wrapper, plugins, and SQLAlchemy dialects) #1257 and is in 3.1.0.
  4. AsyncFailoverPlugin._failover_reader_impl marked each reader candidate it couldn't open, and the original writer when its connect failed, UNAVAILABLE in AsyncPluginServiceImpl._host_availability_expiring_cache, a class-level cache shared by every async connection in the process for 5 minutes. The default random selector picks only available hosts, so a reader that was down for a moment during a failover, or an original writer restarting as a reader, stayed out of selection afterwards. A failed candidate is now only dropped from the current pass and a failed original writer is skipped until the next pass; the failed current host is still marked UNAVAILABLE at the start of _do_failover. The marks date from feat: asyncio support (async wrapper, plugins, and SQLAlchemy dialects) #1257, but in 3.1.0 they were written by alias and read by URL, so they changed host selection only from chore: update dependencies #1302 (7129ddce, 2026-10-22) to refactor: revert the alias removal and async topology move #1328 (2408eea8, 2026-10-26) and again since refactor: identify hosts by host id and host-and-port instead of aliases #1297 (20d619b3, 2026-11-03).
  5. StaleDnsHelper.notify_host_list_changed and AsyncStaleDnsPlugin.notify_host_list_changed reset the cached writer only on HostEvent.CONVERTED_TO_READER. A topology refresh that drops a host reports HOST_DELETED, so when a failover's refresh dropped the old writer the helper kept it, and a later connect to the writer cluster endpoint, whose DNS now gives the new writer, was treated as stale DNS and sent to the cached old writer, now a reader. Both now reset on HOST_DELETED as well, which covers the sync failover, failover_v2 and stale_dns plugins and the async stale_dns plugin. The reset-only-on-reader rule dates from feat: stale dns plugin #102 (2023).
  6. AwsWrapperCursor held only the driver cursor, and mysql-connector's cursor holds its connection through weakref.proxy. Once failover replaced the connection and nothing else referenced the old one, close() on a cursor from before the failover raised ReferenceError: weakly-referenced object no longer exists, which in a with block replaced FailoverSuccessError, and execute raised mysql.connector.errors.ProgrammingError: Cursor is not connected instead of the wrapper's AwsWrapperError. The sync cursor now keeps the driver connection it was made on, unwrapped from SQLAlchemy's pool proxy with driver_dialect.unwrap_connection, as psycopg cursors already do for their own connection. aiomysql and psycopg's async cursors hold a strong reference, so async needs no change.

Test harness

  1. RdsTestUtility.failover_cluster_and_wait_until_writer_changed could request a failover up to 5 times, each with 300 s for a new writer, then wait for DNS and up to 300 s per instance, far past pytest's --timeout=600 with --timeout-method=thread. Every wait now shares one 420 s deadline, and on Aurora the helper waits for the initial writer to answer as a reader. It requests the failover again only when that instance keeps answering as the writer for a full minute, at most twice and with at least 120 s left, as JDBC's AuroraTestUtility re-requests when Aurora restores the original writer.
  2. When the helper gives up, the test fails with "Failover from did not finish within 420 s", or, once the re-requests are used up or less than 120 s is left, with "Failover cluster request was not successful.". If the initial writer never answers as a reader, the helper logs a warning and lets the test's own asserts decide.
  3. make_sure_instances_up, which runs before every Aurora and Multi-AZ DB cluster test and after each failover, now waits until every instance it checks has the RDS status available and then, as before, until each accepts a connection. It reads the cluster's instances with one describe_db_instances call per 2 s poll, and one 300 s budget, or the caller's earlier deadline, covers the status wait and every connect.
  4. On Aurora and Multi-AZ DB clusters, a failed test runs once more after 60 s, with at most 5 reruns per session, when every failed phase of the attempt was a cluster outage: "did not finish within", an instance that didn't reach available or accept a connection, or, before the test requested a failover, a connect timeout with only connect-timeout errors in its exception chain. Wrapper failover or read/write splitting errors, assertions, a full server, an unreadable RDS status, an instance missing from the cluster and anything after the test cut connectivity itself are never rerun, and neither are the autoscaling, blue/green and performance tests. Each rerun gets a new pytest-timeout timer, and a failed test on such a cluster logs the cluster's and its instances' RDS events from the last 15 minutes and attaches them to the report.
  5. Four async writer-failover tests compared the connection's instance with the RDS API's writer right after failover, although their own comment says the control plane can lag "by tens of seconds to minutes". They now wait with retry_until(lambda: aurora_utility.is_db_instance_writer(...)) first, as their sync twins do.
  6. The conftest now clears the async host-availability cache before each test, as it already clears the sync one, so a mark one test leaves (item 4 above) can't reach the next.
  7. Two async srw tests now point srw_read_endpoint and srw_write_endpoint at instance endpoints, because the srw docs say a cluster endpoint may connect to the previous writer right after a failover.

Behaviour changes

  1. A driver error raised while the async wrapper creates a cursor on a broken connection now starts failover, so the application gets FailoverSuccessError, TransactionResolutionUnknownError or FailoverFailedError instead of the driver's error. This differs from 3.1.0.
  2. Async reader failover no longer marks the reader candidates or the original writer it couldn't reach as unavailable, so they stay in host selection.
  3. When the plugin service replaces a static provider, the new provider's topology monitor now opens a probe connection to each host in panic mode, as a provider the wrapper builds directly already does.
  4. In both engines, the stale DNS helper now forgets its cached writer when a topology refresh deletes that host, and then logs "[StaleDnsPlugin] Reset stored writer host." at DEBUG.
  5. With mysql-connector, execute on a cursor from before a failover now always raises AwsWrapperError ("The internal connection has changed since ... was created"), and close no longer raises ReferenceError. Such a cursor keeps its old driver connection object alive while the cursor exists.

Dependency

The test group gains pytest-rerunfailures = "^16.7" (locked 16.7), and its pytest floor rises from >=7.4.4 to >=8.2,!=8.2.2, which pytest-rerunfailures 16.7 requires; the locked pytest stays 9.2.0. Runtime dependencies don't change.

Tests

The 53 new unit test functions (93 cases) cover two areas. The 14 wrapper tests (5 for async failover, 1 for the panic-mode probe, 2 for read/write splitting, 2 for stale DNS, 4 for the sync cursor) fail on main's source with the head's test files, 14 failed and 225 passed, each on an assertion or the old exception, and they pass with this change. The other 39 (79 cases) test the harness helpers: 19 for the failover helper, 14 for make_sure_instances_up, 41 cases for the outage classifier and the rest for the RDS events lookup and cluster waits; they import names added here, so they don't run on main. The conftest's rerun wiring has no automated test. pytest tests/unit -Werror passes 2653 tests on Python 3.10 and 3.12, with mypy, flake8 and isort clean.

The repo's Gradle harness ran at this tree on Python 3.12 against fresh Aurora clusters with 2 instances in us-east-2: test-mysql-aurora with -k "TestAuroraFailover or TestReadWriteSplitting" had 73 passed and 0 failed, test-pg-aurora with -k TestAuroraFailover had 36 passed and 0 failed, and test-docker had 120 passed. Those Aurora tasks exclude the async drivers, so the async fixes ran on Aurora only in CI. The Integration Tests workflow at this tree (run 44269686718) passed all 16 jobs, LTS and Latest on Python 3.11 to 3.14 with mysql and pg: each mysql job passed 585 tests and each pg job 527, with 0 failed, 0 reruns, 0 RDS event dumps and 0 status waits, so the rerun, events and status-wait paths haven't run end to end. main's run 43391980255 at the base failed all 8 LTS jobs. CI's Gradle tasks exclude Multi-AZ DB clusters, Blue/Green, telemetry and performance tests, and Multi-AZ DB clusters weren't run locally either. No CHANGELOG entry, message key or docs change.

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

DbApiMethod.INIT_HOST_PROVIDER.method_name,
DbApiMethod.CONNECT.method_name,
DbApiMethod.FORCE_CONNECT.method_name,
DbApiMethod.CONNECTION_CURSOR.method_name,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this required?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, its also there in the sync version of failover. Without it, the async version misses the connection closed in the cursor() which fails to failover

# which can lag by tens of seconds to minutes post-failover.
assert await query_host_role_async(conn) == HostRole.WRITER
# RDS API lags behind the writer election, so we retry the check.
assert retry_until(lambda: aurora_utility.is_db_instance_writer(current_connection_id))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we still need this retry_util? I believe the RDS team pushed a fix that should have addressed the RDS API lag issue that we have been seeing?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just added to keep it the same as the sync tests but can remove it from both if it is not required.

@JuanLeee
JuanLeee force-pushed the fix/integration-test-failures-2 branch from 976b7cb to 5cdfd7e Compare November 18, 2026 17:50
@JuanLeee
JuanLeee marked this pull request as ready for review November 18, 2026 17:51
@JuanLeee JuanLeee changed the title fix(aio): failover and read/write splitting use the plugin service's host list provider fix: failover and read/write splitting use the plugin service's host list provider in aio Nov 18, 2026
…list provider in aio

The async failover and read/write splitting plugins kept the static host
list provider that the wrapper built from the guessed dialect. After the
plugin service swapped in the Aurora provider, they still saw only the
seed host: no readers, and a writer failover that never reached the new
writer. They now read the service's current provider. The replacement
provider gets the panic-mode probe before its first refresh.

Other wrapper changes:
- Async failover subscribes to Connection.cursor, as sync does, so a
  connection closed while a cursor is created starts failover.
- Async reader failover no longer marks an unreachable reader or original
  writer UNAVAILABLE, as sync failover v2 and JDBC failover2 do.
- The wrapper cursor keeps the driver connection it was made on.
  mysql-connector's cursor holds only a weak proxy, so closing a cursor
  from before a failover could raise ReferenceError. Execute on such a
  cursor now always raises AwsWrapperError, as it does with psycopg.
- The stale DNS helper forgets its cached writer when a topology refresh
  deletes that host, not only when it becomes a reader, in sync and async.

Integration test changes:
- The failover helper waits for the initial writer to rejoin as a reader
  and requests the failover again when Aurora keeps or restores the
  original writer. All its waits share one 420 s deadline.
- make_sure_instances_up waits for the RDS status "available" before it
  connects, within one 300 s budget.
- On Aurora and Multi-AZ DB clusters, a test that failed because the
  cluster stopped accepting connections runs once more after 60 s, using
  the new test dependency pytest-rerunfailures. A failed test logs the
  cluster's recent RDS events.
- The async writer-failover tests retry the RDS API writer check, as the
  sync tests do. The container conftest clears the async host-availability
  cache before each test, and two async simple read/write splitting tests
  use instance endpoints.
@JuanLeee
JuanLeee force-pushed the fix/integration-test-failures-2 branch from e633758 to 7740027 Compare November 18, 2026 18:48
test_verify_retries_then_falls_back_when_role_mismatches_and_current_usable
counted connect attempts inside a 250 ms retry budget, so a stall on a busy
runner left a single attempt and the test failed (assert 1 >= 2 on Python
3.14 in CI). It is now two tests whose attempt counts don't depend on time.
The retry test gets the reader role on the third probe, with a budget the
three attempts can't use up, and checks both wrong-role connections are
aborted and the plugin switches to the reader. The fallback test uses a
1 ms budget with a 50 ms interval, which allows exactly one attempt, and
checks the plugin stays on the usable current connection. A budget of 0
can't be used, because the async plugin replaces it with its 60 s default.
@JuanLeee
JuanLeee merged commit 480c178 into main Nov 19, 2026
9 checks passed
@JuanLeee
JuanLeee deleted the fix/integration-test-failures-2 branch November 19, 2026 08:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants