Repository navigation
fix: failover and read/write splitting use the plugin service's host list provider in aio - #1371
Merged
Merged
Conversation
karenc-bq
reviewed
Nov 14, 2026
| DbApiMethod.INIT_HOST_PROVIDER.method_name, | ||
| DbApiMethod.CONNECT.method_name, | ||
| DbApiMethod.FORCE_CONNECT.method_name, | ||
| DbApiMethod.CONNECTION_CURSOR.method_name, |
Contributor
Author
There was a problem hiding this comment.
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
karenc-bq
approved these changes
Nov 14, 2026
karenc-bq
reviewed
Nov 14, 2026
| # 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)) |
Contributor
There was a problem hiding this comment.
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?
Contributor
Author
There was a problem hiding this comment.
Just added to keep it the same as the sync tests but can remove it from both if it is not required.
JuanLeee
force-pushed
the
fix/integration-test-failures-2
branch
from
November 18, 2026 17:50
976b7cb to
5cdfd7e
Compare
JuanLeee
marked this pull request as ready for review
November 18, 2026 17:51
…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
force-pushed
the
fix/integration-test-failures-2
branch
from
November 18, 2026 18:48
e633758 to
7740027
Compare
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 onAsyncStaticHostListProvider, built from the guessed dialect, and the plugin service swaps in the Aurora provider once the dialect is confirmed.AsyncFailoverPluginandAsyncReadWriteSplittingPluginkeep the provider they were built with, so on that connection writer failover can keep reconnecting to the old writer, as everygdb_failoverwriter-failover test did in run 43391980255, reader failover sees only the seed host andset_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 raisesReferenceErroron close, which in awithblock 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
availablebefore each test and reruns a test once after a cluster outage.AsyncFailoverPluginandAsyncReadWriteSplittingPluginstored the providerbuild_async_pluginshanded them and refreshed through it: in_do_failover's topology refresh, in the writer loopAsyncRetryUtil.get_writer_connectionand in read/write splitting's switches. For a connection whose guessed dialect isRDS_PG,RDS_MYSQL,PGorMYSQL, 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." andset_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_providerfromplugin_service.host_list_providerthrough a read-only property, falling back to the factory's provider only when the service has none, andAsyncGdbFailoverPluginandAsyncGdbReadWriteSplittingPlugininherit 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.AsyncPluginServiceImpl._update_host_list_providercopied the panic-mode probe onto the replacement provider only when the previous provider had one, andAsyncStaticHostListProvidernever does. The Aurora provider that replaced a static one therefore built its topology monitor without a probe, so_should_panicreturnedFalseand the monitor never searched the hosts for the new writer once its own monitoring connection was gone. The service now builds the probe withbuild_probe_hostwhen the previous provider has none and sets it before its firstforce_refresh_host_list, as the wrapper already does for the provider it builds first.AsyncFailoverPlugin._SUBSCRIBEDdidn't listConnection.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_asyncfailed on Aurora PostgreSQL withpsycopg.OperationalError"the connection is closed", raised from_resolve_target_cursor.CONNECTION_CURSORis 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.AsyncFailoverPlugin._failover_reader_implmarked each reader candidate it couldn't open, and the original writer when its connect failed,UNAVAILABLEinAsyncPluginServiceImpl._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 markedUNAVAILABLEat 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).StaleDnsHelper.notify_host_list_changedandAsyncStaleDnsPlugin.notify_host_list_changedreset the cached writer only onHostEvent.CONVERTED_TO_READER. A topology refresh that drops a host reportsHOST_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 onHOST_DELETEDas well, which covers the syncfailover,failover_v2andstale_dnsplugins and the asyncstale_dnsplugin. The reset-only-on-reader rule dates from feat: stale dns plugin #102 (2023).AwsWrapperCursorheld only the driver cursor, and mysql-connector's cursor holds its connection throughweakref.proxy. Once failover replaced the connection and nothing else referenced the old one,close()on a cursor from before the failover raisedReferenceError: weakly-referenced object no longer exists, which in awithblock replacedFailoverSuccessError, andexecuteraisedmysql.connector.errors.ProgrammingError: Cursor is not connectedinstead of the wrapper'sAwsWrapperError. The sync cursor now keeps the driver connection it was made on, unwrapped from SQLAlchemy's pool proxy withdriver_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
RdsTestUtility.failover_cluster_and_wait_until_writer_changedcould 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=600with--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'sAuroraTestUtilityre-requests when Aurora restores the original writer.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 statusavailableand then, as before, until each accepts a connection. It reads the cluster's instances with onedescribe_db_instancescall per 2 s poll, and one 300 s budget, or the caller's earlier deadline, covers the status wait and every connect.availableor 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.retry_until(lambda: aurora_utility.is_db_instance_writer(...))first, as their sync twins do.srwtests now pointsrw_read_endpointandsrw_write_endpointat instance endpoints, because thesrwdocs say a cluster endpoint may connect to the previous writer right after a failover.Behaviour changes
FailoverSuccessError,TransactionResolutionUnknownErrororFailoverFailedErrorinstead of the driver's error. This differs from 3.1.0.executeon a cursor from before a failover now always raisesAwsWrapperError("The internal connection has changed since ... was created"), andcloseno longer raisesReferenceError. Such a cursor keeps its old driver connection object alive while the cursor exists.Dependency
The
testgroup gainspytest-rerunfailures = "^16.7"(locked 16.7), and its pytest floor rises from>=7.4.4to>=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 formake_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 onmain. The conftest's rerun wiring has no automated test.pytest tests/unit -Werrorpasses 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-aurorawith-k "TestAuroraFailover or TestReadWriteSplitting"had 73 passed and 0 failed,test-pg-aurorawith-k TestAuroraFailoverhad 36 passed and 0 failed, andtest-dockerhad 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.