From 77400277478f9d4980bb12dc6b9aed91b797aab6 Mon Sep 17 00:00:00 2001 From: Juan Lee Date: Wed, 18 Nov 2026 11:32:02 -0700 Subject: [PATCH 1/2] fix: failover and read/write splitting use the plugin service's host 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. --- .../aio/failover_plugin.py | 16 +- .../aio/plugin_service.py | 14 +- .../aio/read_write_splitting_plugin.py | 11 +- .../aio/stale_dns_plugin.py | 3 +- .../stale_dns_plugin.py | 2 +- aws_advanced_python_wrapper/wrapper.py | 2 + poetry.lock | 18 +- pyproject.toml | 3 +- tests/integration/container/conftest.py | 123 ++- .../container/test_aurora_failover_async.py | 9 + .../test_read_write_splitting_async.py | 19 +- .../container/utils/proxy_helper.py | 5 +- .../container/utils/rds_test_utility.py | 302 ++++++- .../container/utils/test_timings.py | 52 ++ tests/unit/test_aio_failover_plugin.py | 139 ++++ tests/unit/test_aio_gdb_failover.py | 2 + tests/unit/test_aio_plugin_service_extras.py | 34 +- tests/unit/test_aio_read_write_splitting.py | 55 ++ tests/unit/test_aio_stale_dns_plugin.py | 18 +- tests/unit/test_connection.py | 97 ++- tests/unit/test_rds_test_utility.py | 737 ++++++++++++++++++ tests/unit/test_stale_dns_helper.py | 12 + 22 files changed, 1615 insertions(+), 58 deletions(-) create mode 100644 tests/unit/test_rds_test_utility.py diff --git a/aws_advanced_python_wrapper/aio/failover_plugin.py b/aws_advanced_python_wrapper/aio/failover_plugin.py index fa4381427..05d48916e 100644 --- a/aws_advanced_python_wrapper/aio/failover_plugin.py +++ b/aws_advanced_python_wrapper/aio/failover_plugin.py @@ -65,6 +65,7 @@ class AsyncFailoverPlugin(AsyncPlugin): DbApiMethod.INIT_HOST_PROVIDER.method_name, DbApiMethod.CONNECT.method_name, DbApiMethod.FORCE_CONNECT.method_name, + DbApiMethod.CONNECTION_CURSOR.method_name, DbApiMethod.CURSOR_EXECUTE.method_name, DbApiMethod.CURSOR_EXECUTEMANY.method_name, DbApiMethod.CURSOR_FETCHONE.method_name, @@ -80,7 +81,7 @@ def __init__( host_list_provider: AsyncHostListProvider, props: Properties) -> None: self._plugin_service = plugin_service - self._host_list_provider = host_list_provider + self._factory_host_list_provider = host_list_provider self._props = props # Shared writer-failover convergence helper (also reused by the GDB # failover subclass). See AsyncRetryUtil.get_writer_connection. @@ -132,6 +133,15 @@ def _determine_mode(props: Properties) -> FailoverMode: mode = get_failover_mode(props) return mode if mode is not None else FailoverMode.STRICT_WRITER + @property + def _host_list_provider(self) -> AsyncHostListProvider: + # The service replaces its provider once the dialect is confirmed + # (_update_host_list_provider), so read it at call time. Sync reads + # the topology through the plugin service too. + # The factory's provider only serves a service that has none. + current = self._plugin_service.host_list_provider + return current if current is not None else self._factory_host_list_provider + @property def subscribed_methods(self) -> Set[str]: return set(self._SUBSCRIBED) @@ -555,8 +565,6 @@ async def _failover_reader_impl( new_conn = await self._within_deadline( self._open_connection(candidate, driver_dialect), deadline) except Exception as e: # noqa: BLE001 - self._plugin_service.set_availability( - candidate, HostAvailability.UNAVAILABLE) last_error = e if candidate in remaining: remaining.remove(candidate) @@ -607,8 +615,6 @@ async def _failover_reader_impl( new_conn = await self._within_deadline( self._open_connection(original_writer, driver_dialect), deadline) except Exception as e: # noqa: BLE001 - self._plugin_service.set_availability( - original_writer, HostAvailability.UNAVAILABLE) last_error = e else: role = await self._probe_role(new_conn) diff --git a/aws_advanced_python_wrapper/aio/plugin_service.py b/aws_advanced_python_wrapper/aio/plugin_service.py index d379c7867..d57fef8a7 100644 --- a/aws_advanced_python_wrapper/aio/plugin_service.py +++ b/aws_advanced_python_wrapper/aio/plugin_service.py @@ -798,12 +798,16 @@ async def _update_host_list_provider(self, connection: Any) -> None: type(previous).__name__) return - if previous is not None: - # Carry the panic-mode probe across. + # Carry the panic-mode probe across, or arm it when the previous + # provider has none (a static one, built from the guessed dialect). + set_probe = getattr(replacement, "set_probe_host", None) + if callable(set_probe): probe_host = getattr(previous, "_probe_host", None) - set_probe = getattr(replacement, "set_probe_host", None) - if probe_host is not None and callable(set_probe): - set_probe(probe_host) + if probe_host is None: + from aws_advanced_python_wrapper.aio.cluster_topology_monitor import \ + build_probe_host + probe_host = build_probe_host(self, self._props) + set_probe(probe_host) self._host_list_provider = replacement logger.debug( diff --git a/aws_advanced_python_wrapper/aio/read_write_splitting_plugin.py b/aws_advanced_python_wrapper/aio/read_write_splitting_plugin.py index 96145ed75..250ccafc4 100644 --- a/aws_advanced_python_wrapper/aio/read_write_splitting_plugin.py +++ b/aws_advanced_python_wrapper/aio/read_write_splitting_plugin.py @@ -81,7 +81,7 @@ def __init__( host_list_provider: AsyncHostListProvider, props: Properties) -> None: self._plugin_service = plugin_service - self._host_list_provider = host_list_provider + self._factory_host_list_provider = host_list_provider self._props = props self._writer_conn: Optional[Any] = None self._writer_host_info: Optional[HostInfo] = None @@ -101,6 +101,15 @@ def __init__( self._switch_to_writer_counter = tf.create_counter( "rws.switches.to_writer.count") + @property + def _host_list_provider(self) -> AsyncHostListProvider: + # The service replaces its provider once the dialect is confirmed + # (_update_host_list_provider), so read it at call time. Sync reads + # the topology through the plugin service too. + # The factory's provider only serves a service that has none. + current = self._plugin_service.host_list_provider + return current if current is not None else self._factory_host_list_provider + @property def subscribed_methods(self) -> Set[str]: return set(self._SUBSCRIBED) diff --git a/aws_advanced_python_wrapper/aio/stale_dns_plugin.py b/aws_advanced_python_wrapper/aio/stale_dns_plugin.py index 9af6e6cb4..b0bc35023 100644 --- a/aws_advanced_python_wrapper/aio/stale_dns_plugin.py +++ b/aws_advanced_python_wrapper/aio/stale_dns_plugin.py @@ -242,7 +242,8 @@ def notify_host_list_changed( or changes.get(key_host_port) or changes.get(self._writer_host_info.host)) if (writer_changes is not None - and HostEvent.CONVERTED_TO_READER in writer_changes): + and (HostEvent.CONVERTED_TO_READER in writer_changes + or HostEvent.HOST_DELETED in writer_changes)): logger.debug("StaleDnsHelper.Reset") self._writer_host_info = None self._writer_host_address = None diff --git a/aws_advanced_python_wrapper/stale_dns_plugin.py b/aws_advanced_python_wrapper/stale_dns_plugin.py index 0491b169a..511838b8c 100644 --- a/aws_advanced_python_wrapper/stale_dns_plugin.py +++ b/aws_advanced_python_wrapper/stale_dns_plugin.py @@ -141,7 +141,7 @@ def notify_host_list_changed(self, changes: Dict[str, Set[HostEvent]]) -> None: return writer_changes = changes.get(self._writer_host_info.url, None) - if writer_changes is not None and HostEvent.CONVERTED_TO_READER in writer_changes: + if writer_changes is not None and (HostEvent.CONVERTED_TO_READER in writer_changes or HostEvent.HOST_DELETED in writer_changes): logger.debug("StaleDnsHelper.Reset") self._writer_host_info = None self._writer_host_address = None diff --git a/aws_advanced_python_wrapper/wrapper.py b/aws_advanced_python_wrapper/wrapper.py index 8ad8e7eb4..07fc9722f 100644 --- a/aws_advanced_python_wrapper/wrapper.py +++ b/aws_advanced_python_wrapper/wrapper.py @@ -355,6 +355,8 @@ def __init__( self._plugin_service: PluginService = plugin_service self._plugin_manager: PluginManager = plugin_manager self._target_cursor: Cursor = target_cursor + # The driver cursor may hold only a weak reference to its connection (mysql-connector), so keep that connection alive. + self._target_connection: Optional[Connection] = plugin_service.driver_dialect.unwrap_connection(plugin_service.current_connection) # It's not part of PEP249 @property diff --git a/poetry.lock b/poetry.lock index 0ec59bdde..cfe77e788 100644 --- a/poetry.lock +++ b/poetry.lock @@ -2908,6 +2908,22 @@ files = [ [package.dependencies] pytest = "*" +[[package]] +name = "pytest-rerunfailures" +version = "16.7" +description = "pytest plugin to re-run tests to eliminate flaky failures" +optional = false +python-versions = ">=3.10" +groups = ["test"] +files = [ + {file = "pytest_rerunfailures-16.7-py3-none-any.whl", hash = "sha256:edf1886209c2b7dafe35b5bf1708d6ec40ccf6c6b357f0f02807efcec0204c99"}, + {file = "pytest_rerunfailures-16.7.tar.gz", hash = "sha256:6956ddfb65ca1d07e7e3d99e2c5359d82300f4cb062e6049563bd2c106f72d5c"}, +] + +[package.dependencies] +packaging = ">=17.1" +pytest = ">=8.2,!=8.2.2" + [[package]] name = "pytest-timeout" version = "2.4.0" @@ -3968,4 +3984,4 @@ propcache = ">=0.2.1" [metadata] lock-version = "2.1" python-versions = "^3.10.0" -content-hash = "ef1d83160e6b4eacd82c37e91fa1c66ca9c0a21ac85b476bfbf0972c5d9791c5" +content-hash = "7e7c22d4a338ce64153f32009989b79d2bec995189830d6441d6e22a5c9f1a4e" diff --git a/pyproject.toml b/pyproject.toml index 4ded4d606..f705d02be 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -70,7 +70,7 @@ types-boto3 = "^1.42.95" coverage = "^7.13.5" debugpy = "^1.8.20" pydevd-pycharm = "^263.7031.30" -pytest = ">=7.4.4,<10.0.0" +pytest = ">=8.2,!=8.2.2,<10.0.0" pytest-mock = "^3.15.1" pytest-html = "^4.2.0" pytest-html-merger = ">=0.1.0,<0.1.1" @@ -85,6 +85,7 @@ opentelemetry-exporter-otlp-proto-grpc = "^1.43.0" opentelemetry-sdk-extension-aws = "^2.1.0" pytest-timeout = "^2.4.0" pytest-repeat = "^0.9.4" +pytest-rerunfailures = "^16.7" greenlet = ">=3" [tool.isort] diff --git a/tests/integration/container/conftest.py b/tests/integration/container/conftest.py index 7fae7b4d6..017e6897e 100644 --- a/tests/integration/container/conftest.py +++ b/tests/integration/container/conftest.py @@ -19,6 +19,8 @@ from aws_xray_sdk.core import xray_recorder +from aws_advanced_python_wrapper.aio.plugin_service import \ + AsyncPluginServiceImpl from aws_advanced_python_wrapper.connection_provider import \ ConnectionProviderManager from aws_advanced_python_wrapper.custom_endpoint_plugin import \ @@ -39,10 +41,13 @@ import socket import timeit from time import sleep -from typing import List +from typing import ClassVar, List import boto3 import pytest +import pytest_timeout # type: ignore[import-untyped] +from botocore.config import Config +from pytest_html import extras as html_extras # type: ignore[import-untyped] from .utils.connection_utils import ConnectionUtils from .utils.database_engine_deployment import DatabaseEngineDeployment @@ -50,9 +55,20 @@ from .utils.rds_test_utility import RdsTestUtility from .utils.test_environment import TestEnvironment from .utils.test_environment_features import TestEnvironmentFeatures +from .utils.test_timings import (CLUSTER_OUTAGE_RERUN_DELAY_SEC, + RDS_EVENTS_BUDGET_SEC, + RDS_EVENTS_CALL_TIMEOUT_SEC, + RDS_EVENTS_LOOKBACK_SEC) logger = Logger(__name__) +_CLUSTER_DEPLOYMENTS = (DatabaseEngineDeployment.AURORA, DatabaseEngineDeployment.RDS_MULTI_AZ_CLUSTER) +# During a long outage every test fails, so cap the reruns for the whole session +_MAX_CLUSTER_OUTAGE_RERUNS = 5 +_NO_RERUN_MODULE_PREFIXES = ( + "test_autoscaling", "test_blue_green_deployment", "test_failover_performance", + "test_read_write_splitting_performance") + @pytest.fixture(scope="session", autouse=True) def _prewarm_aws_pipeline(): @@ -101,6 +117,13 @@ def pytest_runtest_setup(item): logger.info("Starting test preparation for: " + test_name) + _Attempt.failed_other_than_outage = False + ProxyHelper.connectivity_disabled = False + RdsTestUtility.failover_requested = False + # pytest-timeout cancels its timer when an attempt fails, so a rerun needs a new one + if getattr(item, "execution_count", 1) > 1: + _set_timeout_timer(item) + segment: Optional[Segment] = None if TestEnvironmentFeatures.TELEMETRY_TRACES_ENABLED in TestEnvironment.get_current().get_features(): segment = xray_recorder.begin_segment("test: setup") @@ -169,6 +192,7 @@ def pytest_runtest_setup(item): RdsUtils.clear_cache() services_container.release_resources() PluginServiceImpl._host_availability_expiring_cache.clear() + AsyncPluginServiceImpl._host_availability_expiring_cache.clear() DatabaseDialectManager._known_endpoint_dialects.clear() CustomEndpointMonitor._custom_endpoint_info_cache.clear() @@ -232,6 +256,103 @@ def pytest_collection_modifyitems(config, items): reason=f"{kind} driver {driver.value} not applicable to " f"{file_kind} test file")) + # On Aurora and Multi-AZ DB clusters, run a test once more when it failed because the cluster stopped + # accepting connections. Autoscaling and blue/green tests change the cluster, and performance tests + # would measure a different run, so they are not rerun. + if TestEnvironment.get_current().get_deployment() in _CLUSTER_DEPLOYMENTS: + config.option.max_suite_reruns = _MAX_CLUSTER_OUTAGE_RERUNS + rerun_on_outage = pytest.mark.flaky( + reruns=1, reruns_delay=CLUSTER_OUTAGE_RERUN_DELAY_SEC, condition=_rerun_after_cluster_outage) + for item in items: + if not item.path.name.startswith(_NO_RERUN_MODULE_PREFIXES): + item.add_marker(rerun_on_outage) + + +class _Attempt: + # Set when a failed phase of the current attempt was not a cluster outage + failed_other_than_outage: ClassVar[bool] = False + + +def _phase_failed_on_cluster_outage(error: Optional[BaseException]) -> bool: + # A failure the test caused by cutting connectivity is not an outage + return not ProxyHelper.connectivity_disabled and RdsTestUtility.is_cluster_outage( + error, RdsTestUtility.failover_requested) + + +def _rerun_after_cluster_outage(error: Optional[BaseException]) -> bool: + # Rerun only when every failed phase of the attempt was an outage + return not _Attempt.failed_other_than_outage and _phase_failed_on_cluster_outage(error) + + +def _set_timeout_timer(item): + timeout_settings = pytest_timeout.get_env_settings(item.config) + timeout_marker = item.get_closest_marker("timeout") + if timeout_marker is not None: + if timeout_marker.args: + timeout = timeout_marker.args[0] + else: + timeout = timeout_marker.kwargs.get("timeout", timeout_settings.timeout) + if len(timeout_marker.args) > 1: + method = timeout_marker.args[1] + else: + method = timeout_marker.kwargs.get("method", timeout_settings.method) + timeout_settings = timeout_settings._replace( + timeout=timeout, + method=method, + func_only=timeout_marker.kwargs.get("func_only", timeout_settings.func_only)) + # pytest-timeout sets a function-only timer itself at the call. No timeout, or 0, means none. + if timeout_settings.func_only or not timeout_settings.timeout: + return + item.config.hook.pytest_timeout_set_timer(item=item, settings=timeout_settings) + + +# trylast makes this the inner wrapper, so the attempt's failures are recorded before +# pytest-rerunfailures evaluates the rerun condition in its own wrapper +@pytest.hookimpl(wrapper=True, trylast=True) +def pytest_runtest_makereport(item, call): + report = yield + if report.failed: + try: + outage = _phase_failed_on_cluster_outage(call.excinfo.value if call.excinfo is not None else None) + except Exception as e: # noqa: BLE001 -- an error here would end the whole session + logger.warning(f"Could not classify the failure, so the test is not rerun: {e}") + outage = False + if not outage: + _Attempt.failed_other_than_outage = True + if report.when in ("setup", "call"): + _attach_recent_rds_events(item, report) + return report + + +def _attach_recent_rds_events(item, report): + # Shows whether RDS restarted or failed over an instance around a failure + try: + info = TestEnvironment.get_current().get_info() + if info.get_request().get_database_engine_deployment() not in _CLUSTER_DEPLOYMENTS: + return + # pytest-timeout stops the test's timer only after this hook, and a lookup that ran past it + # would end the whole session instead of reporting this failure + item.config.hook.pytest_timeout_cancel_timer(item=item) + call_config = Config( + connect_timeout=RDS_EVENTS_CALL_TIMEOUT_SEC, read_timeout=RDS_EVENTS_CALL_TIMEOUT_SEC, + retries={"total_max_attempts": 1}) + rds_utility = RdsTestUtility(info.get_region(), info.get_rds_endpoint(), call_config) + instance_ids = [instance.get_instance_id() for instance in TestEnvironment.get_current().get_instances()] + events = rds_utility.get_recent_events( + info.get_db_name(), instance_ids, RDS_EVENTS_LOOKBACK_SEC, RDS_EVENTS_BUDGET_SEC) + lines = [f"{event.get('Date')} {event.get('SourceIdentifier')}: {event.get('Message')}" for event in events] + except Exception as e: + logger.warning(f"Could not read RDS events: {e}") + return + + for line in lines: + logger.warning(f"RDS event {line}") + if lines: + text = "\n".join(lines) + report.sections.append(("RDS events", text)) + # pytest-html leaves sections out of rerun reports, but keeps extras + report.extras = [*getattr(report, "extras", []), html_extras.text(text, name="RDS events")] + def pytest_sessionstart(session): TestEnvironment.get_current() diff --git a/tests/integration/container/test_aurora_failover_async.py b/tests/integration/container/test_aurora_failover_async.py index fd146ce2e..5b8d7a9bb 100644 --- a/tests/integration/container/test_aurora_failover_async.py +++ b/tests/integration/container/test_aurora_failover_async.py @@ -41,6 +41,7 @@ from aws_advanced_python_wrapper.utils.log import Logger from .utils.rds_test_utility import RdsTestUtility +from .utils.retry_helper import retry_until from .utils.test_environment import TestEnvironment from .utils.test_environment_features import TestEnvironmentFeatures from .utils.test_timings import FAILOVER_WITHIN_TRANSACTION_PYTEST_TIMEOUT_SEC @@ -269,6 +270,8 @@ async def inner() -> None: # than the control-plane ``DescribeDBClusters.IsClusterWriter``, # 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)) next_cluster_writer_id = aurora_utility.get_cluster_writer_instance_id() assert current_connection_id == next_cluster_writer_id assert current_connection_id != initial_writer_id @@ -318,6 +321,8 @@ async def inner() -> None: # than the control-plane ``DescribeDBClusters.IsClusterWriter``, # 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)) next_cluster_writer_id = aurora_utility.get_cluster_writer_instance_id() assert current_connection_id == next_cluster_writer_id assert current_connection_id != initial_writer_id @@ -367,6 +372,8 @@ async def inner() -> None: # assert that we are connected to the new writer after failover happens # Data-plane writer check; see earlier sites for rationale. 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)) next_cluster_writer_id: str = aurora_utility.get_cluster_writer_instance_id() assert current_connection_id == next_cluster_writer_id @@ -424,6 +431,8 @@ async def inner() -> None: # assert that we are connected to the new writer after failover happens # Data-plane writer check; see earlier sites for rationale. 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)) next_cluster_writer_id: str = aurora_utility.get_cluster_writer_instance_id() assert current_connection_id == next_cluster_writer_id diff --git a/tests/integration/container/test_read_write_splitting_async.py b/tests/integration/container/test_read_write_splitting_async.py index 72d31d157..eab162caf 100644 --- a/tests/integration/container/test_read_write_splitting_async.py +++ b/tests/integration/container/test_read_write_splitting_async.py @@ -872,11 +872,11 @@ async def inner(): {"plugins": plugin_value, "connect_timeout": 30, "autocommit": True} ) port = ( - test_environment.get_info().get_database_info().get_cluster_endpoint_port() + test_environment.get_info().get_database_info().get_instance_endpoint_port() ) - writer_endpoint = conn_utils.writer_cluster_host + writer_endpoint = conn_utils.writer_host - # Set both endpoints to writer (incorrect reader endpoint) + # Set both endpoints to the writer instance (incorrect reader endpoint) WrapperProperties.SRW_WRITE_ENDPOINT.set(props, f"{writer_endpoint}:{port}") WrapperProperties.SRW_READ_ENDPOINT.set(props, f"{writer_endpoint}:{port}") @@ -905,7 +905,13 @@ async def inner(): asyncio.run(inner()) def test_autocommit_state_preserved_across_connection_switches_async( - self, test_driver: TestDriver, props, conn_utils, rds_utils, plugin_config + self, + test_environment: TestEnvironment, + test_driver: TestDriver, + props, + conn_utils, + rds_utils, + plugin_config, ): plugin_name, _ = plugin_config if plugin_name != "srw": @@ -915,6 +921,11 @@ def test_autocommit_state_preserved_across_connection_switches_async( async def inner(): WrapperProperties.SRW_VERIFY_NEW_CONNECTIONS.set(props, "False") + port = test_environment.get_info().get_database_info().get_instance_endpoint_port() + # The cluster endpoints may route to the wrong instance, and with verification off + # srw won't check; the conftest moves the writer first, so the second instance is a reader. + WrapperProperties.SRW_WRITE_ENDPOINT.set(props, f"{conn_utils.writer_host}:{port}") + WrapperProperties.SRW_READ_ENDPOINT.set(props, f"{test_environment.get_instances()[1].get_host()}:{port}") conn = await connect_async( test_driver=test_driver, connect_params=conn_utils.get_connect_params(), diff --git a/tests/integration/container/utils/proxy_helper.py b/tests/integration/container/utils/proxy_helper.py index e6568bbb3..898f47c39 100644 --- a/tests/integration/container/utils/proxy_helper.py +++ b/tests/integration/container/utils/proxy_helper.py @@ -14,7 +14,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, ClassVar if TYPE_CHECKING: from .proxy_info import ProxyInfo @@ -29,6 +29,8 @@ class ProxyHelper: logger = Logger(__name__) + # Set when a test cuts connectivity, so that a failure it causes is not rerun as a cluster outage + connectivity_disabled: ClassVar[bool] = False @staticmethod def disable_all_connectivity(): @@ -43,6 +45,7 @@ def disable_connectivity(instance_name: str): @staticmethod def _disable_proxy_connectivity(proxy_info: ProxyInfo): + ProxyHelper.connectivity_disabled = True APIConsumer.host = proxy_info.control_host APIConsumer.port = proxy_info.control_port diff --git a/tests/integration/container/utils/rds_test_utility.py b/tests/integration/container/utils/rds_test_utility.py index e5beea69b..e42ed3736 100644 --- a/tests/integration/container/utils/rds_test_utility.py +++ b/tests/integration/container/utils/rds_test_utility.py @@ -16,23 +16,32 @@ from contextlib import closing from threading import Thread -from typing import TYPE_CHECKING, Any, Dict, List, Optional, cast +from typing import (TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Tuple, + cast) import botocore.exceptions from tests.integration.container.utils.proxy_helper import ProxyHelper if TYPE_CHECKING: + from botocore.config import Config + from aws_advanced_python_wrapper.pep249 import Connection from .test_database_info import TestDatabaseInfo +import asyncio +import re import socket import timeit -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from time import perf_counter_ns, sleep import boto3 +import psycopg +import psycopg.errors import pytest +from mysql.connector.errors import \ + ConnectionTimeoutError as MySQLConnectionTimeoutError from aws_advanced_python_wrapper.driver_info import DriverInfo from aws_advanced_python_wrapper.errors import UnsupportedOperationError @@ -40,6 +49,10 @@ from aws_advanced_python_wrapper.utils.log import Logger from aws_advanced_python_wrapper.utils.messages import Messages from tests.integration.container.utils.test_timings import ( + CLUSTER_STATUS_TIMEOUT_SEC, FAILOVER_DEADLINE_SEC, FAILOVER_MAX_REISSUES, + FAILOVER_REISSUE_MIN_REMAINING_SEC, INITIAL_WRITER_POLL_INTERVAL_SEC, + INITIAL_WRITER_REVERT_WINDOW_SEC, INSTANCE_STATUS_POLL_INTERVAL_SEC, + INSTANCE_UP_TIMEOUT_SEC, WRITER_CHANGE_TIMEOUT_SEC, WRITER_CHANGED_PROBE_CONNECT_TIMEOUT_SEC, WRITER_CHANGED_PROBE_POLL_INTERVAL_SEC) from .database_engine import DatabaseEngine @@ -49,17 +62,41 @@ from .test_environment import TestEnvironment from .test_instance_info import TestInstanceInfo +# An instance, the cluster or the network is down: the failover helper ran out of time, an instance did +# not reach the RDS status available or accept a connection, or a connect timed out. The conftest +# reruns a test that fails this way once. +_HELPER_OUTAGE_PATTERNS = ( + re.compile(r"did not finish within"), + re.compile(r"did not accept a connection"), + re.compile(r"did not become available"), +) +_CONNECT_TIMEOUT_PATTERNS = ( + re.compile(r"Can't connect to MySQL server.*timed out"), + re.compile(r"connection timeout expired"), +) +# A full server can come from leaked connections, so it is not an outage +_NOT_CLUSTER_OUTAGE_PATTERN = re.compile( + r"[Tt]oo many (connections|clients)|remaining connection slots are reserved") +# The driver errors a connect timeout surfaces as +_CONNECT_TIMEOUT_ERRORS = (MySQLConnectionTimeoutError, psycopg.OperationalError) +# What a connect timeout is raised from. Anything else in the chain, such as an assertion whose cleanup then +# failed to connect, or a query the test ran, is the test's own failure. +_CONNECT_TIMEOUT_CAUSES = (OSError, asyncio.TimeoutError, MySQLConnectionTimeoutError, psycopg.errors.ConnectionTimeout) + class RdsTestUtility: logger = Logger(__name__) + # Set when a test requests a failover, so that a connect timeout after it is not rerun as an outage + failover_requested: ClassVar[bool] = False _client: Any + _last_connect_error: Optional[str] = None - def __init__(self, region: str, endpoint: Optional[str] = None): + def __init__(self, region: str, endpoint: Optional[str] = None, config: Optional[Config] = None): if endpoint: - self._client = boto3.client(service_name='rds', region_name=region, endpoint_url=endpoint) + self._client = boto3.client(service_name='rds', region_name=region, endpoint_url=endpoint, config=config) else: - self._client = boto3.client(service_name='rds', region_name=region) + self._client = boto3.client(service_name='rds', region_name=region, config=config) @staticmethod def get_utility() -> RdsTestUtility: @@ -135,17 +172,79 @@ def wait_until_instance_has_desired_status( raise InterruptedError(Messages.get_formatted( "RdsTestUtility.InstanceDescriptionTimeout", instance_id, desired_status, wait_time_mins)) - def wait_until_cluster_has_desired_status(self, cluster_id: str, desired_status: str) -> None: - stop_time = datetime.now() + timedelta(minutes=10) + def wait_until_cluster_has_desired_status( + self, cluster_id: str, desired_status: str, timeout_sec: float = CLUSTER_STATUS_TIMEOUT_SEC) -> None: + stop_time = datetime.now() + timedelta(seconds=timeout_sec) cluster_info = self.get_db_cluster(cluster_id) status = cluster_info.get("Status") while status != desired_status: if datetime.now() > stop_time: - raise TimeoutError(f"Cluster {cluster_id} did not reach status '{desired_status}' within 10 minutes.") + raise TimeoutError(f"Cluster {cluster_id} did not reach status '{desired_status}' within {timeout_sec:.0f} s.") sleep(10) cluster_info = self.get_db_cluster(cluster_id) status = cluster_info.get("Status") + def get_recent_events( + self, cluster_id: str, instance_ids: List[str], lookback_sec: float, budget_sec: float) -> List[Dict[str, Any]]: + """Read the RDS events of a cluster and its instances. + + :param cluster_id: the cluster's identifier. + :param instance_ids: the identifiers of the cluster's instances. + :param lookback_sec: how far back to read, in seconds. + :param budget_sec: how long to keep reading, in seconds. Sources not read by then are skipped. + :return: the events read, oldest first. + """ + stop_time = timeit.default_timer() + budget_sec + start_time = datetime.now(timezone.utc) - timedelta(seconds=lookback_sec) + sources = [("db-cluster", cluster_id)] + [("db-instance", instance_id) for instance_id in instance_ids] + paginator = self._client.get_paginator("describe_events") + events: List[Dict[str, Any]] = [] + for source_type, source_id in sources: + if timeit.default_timer() >= stop_time: + break + for page in paginator.paginate(SourceType=source_type, SourceIdentifier=source_id, StartTime=start_time): + events.extend(page.get("Events", [])) + return sorted(events, key=lambda event: event.get("Date", datetime.min.replace(tzinfo=timezone.utc))) + + @staticmethod + def is_cluster_outage(error: Optional[BaseException], after_failover: bool = False) -> bool: + """Tell whether a test failed because the cluster stopped accepting connections. + + :param error: the exception the test failed with, or None. + :param after_failover: whether the test requested a failover before it failed. A connect + timeout is then not an outage, because the wrapper may have connected to the old writer. + :return: True if all of these hold. First, the exception itself is one of the helper's + outage failures (the failover did not finish in time, or an instance did not reach the + RDS status available or accept a connection) or, before any failover, a connect that + timed out. Second, its text doesn't say the server is full. Third, every exception it + was raised from or while handling is part of a connect timeout. + """ + if error is None: + return False + + message = f"{type(error).__name__}: {error}" + if _NOT_CLUSTER_OUTAGE_PATTERN.search(message): + return False + if isinstance(error, pytest.fail.Exception): + patterns: Tuple[re.Pattern, ...] = _HELPER_OUTAGE_PATTERNS + elif not after_failover and isinstance(error, _CONNECT_TIMEOUT_ERRORS): + patterns = _CONNECT_TIMEOUT_PATTERNS + else: + return False + if not any(pattern.search(message) for pattern in patterns): + return False + + chain: List[BaseException] = [] + pending: List[BaseException] = [error] + while pending: + current = pending.pop() + if any(current is seen for seen in chain): + continue + chain.append(current) + pending.extend(linked for linked in (current.__cause__, current.__context__) if linked is not None) + # Every exception the outermost one was raised from or while handling must be part of a connect timeout + return all(isinstance(exception, _CONNECT_TIMEOUT_CAUSES) for exception in chain[1:]) + def get_db_cluster(self, cluster_id: str) -> Any: response: Any = self._client.describe_db_clusters(DBClusterIdentifier=cluster_id) clusters = response.get("DBClusters") @@ -163,6 +262,8 @@ def failover_cluster_and_wait_until_writer_changed( raise Exception(Messages.get_formatted("RdsTestUtility.FailoverToTargetNotSupported", target_id, deployment)) start = perf_counter_ns() + deadline = timeit.default_timer() + FAILOVER_DEADLINE_SEC + self._last_connect_error = None if cluster_id is None: cluster_id = TestEnvironment.get_current().get_info().get_db_name() @@ -173,32 +274,63 @@ def failover_cluster_and_wait_until_writer_changed( cluster_endpoint = database_info.get_cluster_endpoint() initial_cluster_address = socket.gethostbyname(cluster_endpoint) - self.failover_cluster(cluster_id, target_id) - remaining_attempts = 5 - while not self.writer_changed(initial_writer_id, cluster_id, 300): - # if writer is not changed, try triggering failover again - remaining_attempts -= 1 - if remaining_attempts == 0: + self.failover_cluster(cluster_id, target_id, deadline - timeit.default_timer()) + remaining_reissues = FAILOVER_MAX_REISSUES + while True: + remaining_sec = deadline - timeit.default_timer() + if remaining_sec <= 0: + # The conftest reruns a test that fails with this message once + pytest.fail(f"Failover from {initial_writer_id} did not finish within {FAILOVER_DEADLINE_SEC} s. " + f"Last connect error: {self._last_connect_error}") + + if self.writer_changed(initial_writer_id, cluster_id, min(WRITER_CHANGE_TIMEOUT_SEC, remaining_sec)): + if not self._initial_writer_kept_writer_role(initial_writer_id, deadline): + if timeit.default_timer() >= deadline: + self.logger.warning( + f"Initial writer {initial_writer_id} did not answer as a reader before the failover deadline") + break + elif DatabaseEngineDeployment.AURORA == deployment: + # No new writer yet. If the initial writer doesn't answer, or stops answering as the writer, + # a second failover would not help, and on two instances it hands the writer role back. + # Check for a new writer again once the initial writer's window can't complete. + if self._query_instance_role(initial_writer_id) != HostRole.WRITER: + continue + window_deadline = min(deadline, timeit.default_timer() + 2 * INITIAL_WRITER_REVERT_WINDOW_SEC) + if not self._initial_writer_kept_writer_role(initial_writer_id, window_deadline): + continue + + # The failover did not take, or the initial writer is the writer again: request it again + if remaining_reissues == 0 or deadline - timeit.default_timer() < FAILOVER_REISSUE_MIN_REMAINING_SEC: raise Exception(Messages.get("RdsTestUtility.FailoverRequestNotSuccessful")) - self.failover_cluster(cluster_id, target_id) + self.wait_until_cluster_has_desired_status(cluster_id, "available", deadline - timeit.default_timer()) + if (DatabaseEngineDeployment.AURORA == deployment + and self._query_instance_role(initial_writer_id) != HostRole.WRITER): + # A failover that was still running has finished while the cluster was busy + continue + remaining_reissues -= 1 + self.failover_cluster(cluster_id, target_id, deadline - timeit.default_timer()) # Failover has finished, wait for DNS to be updated so cluster endpoint resolves to the new writer instance. cluster_address = socket.gethostbyname(cluster_endpoint) - start_time = timeit.default_timer() - while cluster_address == initial_cluster_address and (timeit.default_timer() - start_time) < 300: # 5 min + while cluster_address == initial_cluster_address and timeit.default_timer() < deadline: sleep(1) cluster_address = socket.gethostbyname(cluster_endpoint) # wait until all instances except initial writer instance to be available instances = [x.get_instance_id() for x in TestEnvironment.get_current().get_instances() if x.get_instance_id() != initial_writer_id] - self.make_sure_instances_up(instances) + self.make_sure_instances_up(instances, deadline) self.logger.debug("Testing.FinishedFailover", initial_writer_id, str((perf_counter_ns() - start) / 1_000_000)) - def failover_cluster(self, cluster_id: Optional[str] = None, target_id: Optional[str] = None) -> None: + def failover_cluster( + self, + cluster_id: Optional[str] = None, + target_id: Optional[str] = None, + timeout_sec: float = CLUSTER_STATUS_TIMEOUT_SEC) -> None: if cluster_id is None: cluster_id = TestEnvironment.get_current().get_info().get_db_name() - self.wait_until_cluster_has_desired_status(cluster_id, "available") + RdsTestUtility.failover_requested = True + self.wait_until_cluster_has_desired_status(cluster_id, "available", timeout_sec) remaining_attempts = 10 while remaining_attempts > 0: @@ -218,7 +350,7 @@ def failover_cluster(self, cluster_id: Optional[str] = None, target_id: Optional raise Exception(Messages.get_formatted("RdsTestUtility.FailoverClusterFailed", cluster_id)) - def writer_changed(self, initial_writer_id: str, cluster_id: str, timeout: int) -> bool: + def writer_changed(self, initial_writer_id: str, cluster_id: str, timeout_sec: float) -> bool: """Detect whether Aurora has promoted a new writer instance. For Aurora deployments, queries the data-plane SQL catalog through the @@ -234,7 +366,7 @@ def writer_changed(self, initial_writer_id: str, cluster_id: str, timeout: int) engine = TestEnvironment.get_current().get_engine() if (DatabaseEngineDeployment.AURORA != deployment or engine not in (DatabaseEngine.PG, DatabaseEngine.MYSQL)): - return self._writer_changed_via_rds_api(initial_writer_id, cluster_id, timeout) + return self._writer_changed_via_rds_api(initial_writer_id, cluster_id, timeout_sec) info = TestEnvironment.get_current().get_database_info() cluster_endpoint = info.get_cluster_endpoint() @@ -255,10 +387,10 @@ def writer_changed(self, initial_writer_id: str, cluster_id: str, timeout: int) # control plane and lag the data plane by tens of seconds on # multi-instance Aurora topologies. Returning as soon as the data # plane flips lets those assertions race the control plane. Wait - # for control-plane convergence too -- within the same ``timeout`` + # for control-plane convergence too -- within the same ``timeout_sec`` # budget -- so callers see a consistent view across both planes. data_plane_changed = False - wait_until = timeit.default_timer() + timeout + wait_until = timeit.default_timer() + timeout_sec while timeit.default_timer() < wait_until: try: conn = connect_func(**connect_params) @@ -272,6 +404,7 @@ def writer_changed(self, initial_writer_id: str, cluster_id: str, timeout: int) conn.close() except Exception as ex: # Aurora may briefly reject connections mid-failover; keep polling. + self._last_connect_error = f"{type(ex).__name__}: {ex}" self.logger.debug("writer_changed SQL probe failed: " + str(ex)) if data_plane_changed: try: @@ -284,8 +417,8 @@ def writer_changed(self, initial_writer_id: str, cluster_id: str, timeout: int) sleep(WRITER_CHANGED_PROBE_POLL_INTERVAL_SEC) return False - def _writer_changed_via_rds_api(self, initial_writer_id: str, cluster_id: str, timeout: int) -> bool: - wait_until = timeit.default_timer() + timeout + def _writer_changed_via_rds_api(self, initial_writer_id: str, cluster_id: str, timeout_sec: float) -> bool: + wait_until = timeit.default_timer() + timeout_sec current_writer_id = self.get_cluster_writer_instance_id(cluster_id) while initial_writer_id == current_writer_id and timeit.default_timer() < wait_until: @@ -293,6 +426,58 @@ def _writer_changed_via_rds_api(self, initial_writer_id: str, cluster_id: str, t current_writer_id = self.get_cluster_writer_instance_id(cluster_id) return initial_writer_id != current_writer_id + def _initial_writer_kept_writer_role(self, initial_writer_id: str, deadline: float) -> bool: + """Tell whether the initial writer is still, or again, the writer after the failover. + + Polls the initial writer until it answers as a reader, or keeps answering as the writer + for ``INITIAL_WRITER_REVERT_WINDOW_SEC`` without a break. + + :param initial_writer_id: the instance that was the writer before the failover. + :param deadline: the ``timeit.default_timer()`` value at which to stop waiting. + :return: True if it kept answering as the writer for the whole window. + False if it answered as a reader, off Aurora, or at the deadline. + """ + if DatabaseEngineDeployment.AURORA != TestEnvironment.get_current().get_deployment(): + return False + + first_writer_reading: Optional[float] = None + while timeit.default_timer() < deadline: + role = self._query_instance_role(initial_writer_id) + if role == HostRole.READER: + return False + if role is None: + # It restarts: a writer reading after the restart starts a new window + first_writer_reading = None + elif role == HostRole.WRITER: + now = timeit.default_timer() + if first_writer_reading is None: + first_writer_reading = now + elif now - first_writer_reading >= INITIAL_WRITER_REVERT_WINDOW_SEC: + self.logger.debug(f"Initial writer {initial_writer_id} is still the writer") + return True + sleep(INITIAL_WRITER_POLL_INTERVAL_SEC) + + return False + + def _query_instance_role(self, instance_id: str) -> Optional[HostRole]: + """Connect to one instance and ask for its role. + + :param instance_id: the instance to ask. + :return: its role, or None if it can't be reached, for example while it restarts. + """ + env = TestEnvironment.get_current() + instance_info = env.get_database_info().get_instance(instance_id) + try: + conn = self._open_connection(instance_info) + try: + return self.query_host_role(conn, env.get_engine()) + finally: + conn.close() + except Exception as e: + self._last_connect_error = f"{type(e).__name__}: {e}" + self.logger.debug(f"Instance {instance_id} did not answer: {e}") + return None + def assert_first_query_throws( self, conn, @@ -538,21 +723,72 @@ def _get_driver_for_database_engine(self, database_engine: DatabaseEngine) -> Te else: raise UnsupportedOperationError(database_engine.value) - def make_sure_instances_up(self, instances: List[str]) -> None: + def make_sure_instances_up(self, instances: List[str], deadline: Optional[float] = None) -> None: + """Wait until the instances have the RDS status ``available``, then until each accepts a connection. + + All the waits together last up to ``INSTANCE_UP_TIMEOUT_SEC``, or until ``deadline`` if that is + sooner. The status is read at least once and, if every instance is available, each one gets at + least one connection attempt, even after that time. + + :param instances: the ids of the instances to check. + :param deadline: a ``timeit.default_timer()`` value that ends the waits sooner. + """ + stop_time = timeit.default_timer() + INSTANCE_UP_TIMEOUT_SEC + if deadline is not None: + stop_time = min(stop_time, deadline) + self._wait_until_instances_available(instances, stop_time) + database_info: TestDatabaseInfo = TestEnvironment.get_current().get_database_info() for i in instances: instance_info: TestInstanceInfo = database_info.get_instance(i) - success: bool = False - start_time = timeit.default_timer() - while (timeit.default_timer() - start_time) < 300: # 5 min + last_error: Optional[Exception] = None + # Try each instance at least once, even when the deadline has already passed + while True: try: conn = self._open_connection(instance_info) conn.close() - success = True + last_error = None break - except Exception: + except Exception as e: + last_error = e + if timeit.default_timer() >= stop_time: + break sleep(1) - assert success + if last_error is not None: + # The conftest reruns a test that fails with this message once + pytest.fail(f"Instance {i} did not accept a connection: {type(last_error).__name__}: {last_error}") + + def _wait_until_instances_available(self, instance_ids: List[str], stop_time: float) -> None: + cluster_id = TestEnvironment.get_current().get_cluster_name() + filters = [{"Name": "db-cluster-id", "Values": [cluster_id]}] + last_detail = "" + # Read the status at least once, even when the deadline has already passed + while True: + try: + response = self._client.describe_db_instances(Filters=filters) + except Exception as e: + detail = f"{type(e).__name__}: {e}" + # Not a cluster outage, so the conftest doesn't rerun a test that fails with this message + failure = f"Could not read the RDS status of the instances: {detail}" + else: + statuses = { + instance["DBInstanceIdentifier"]: instance["DBInstanceStatus"] for instance in response["DBInstances"]} + missing = [instance_id for instance_id in instance_ids if instance_id not in statuses] + if missing: + # RDS lists an instance from its creation until its deletion, so waiting doesn't help + pytest.fail(f"Instances not in cluster '{cluster_id}': {', '.join(missing)}") + not_available = [instance_id for instance_id in instance_ids if statuses[instance_id] != "available"] + if not not_available: + return + detail = ", ".join(f"{instance_id} is '{statuses[instance_id]}'" for instance_id in not_available) + # The conftest reruns a test that fails with this message once + failure = f"Instances did not become available: {detail}" + if detail != last_detail: + self.logger.debug(f"Waiting for the RDS status available: {detail}") + last_detail = detail + if timeit.default_timer() >= stop_time: + pytest.fail(failure) + sleep(INSTANCE_STATUS_POLL_INTERVAL_SEC) @staticmethod def create_user(conn, username, password): diff --git a/tests/integration/container/utils/test_timings.py b/tests/integration/container/utils/test_timings.py index 7d25c3bf3..26d342859 100644 --- a/tests/integration/container/utils/test_timings.py +++ b/tests/integration/container/utils/test_timings.py @@ -60,6 +60,58 @@ WRITER_CHANGED_PROBE_CONNECT_TIMEOUT_SEC: int = 5 WRITER_CHANGED_PROBE_POLL_INTERVAL_SEC: float = 2.0 +# ───── Failover helper deadline ──────────────────────────────────────── +# ``RdsTestUtility.failover_cluster_and_wait_until_writer_changed`` waits +# for a new writer, for the initial writer to restart as a reader, for the +# cluster endpoint's DNS and for the other instances. Every wait shares one +# deadline, so a cluster that stops answering for minutes fails one test +# instead of running past pytest's 600 s ``--timeout``, which ends the +# whole session. This bounds one call to about 420 s (one RDS status read, +# and one connect attempt for each instance, can run past it); the setup +# hook's waits are separate. A normal failover takes 20 to 35 s. +FAILOVER_DEADLINE_SEC: float = 420 +# How long one failover request gets to produce a new writer before the +# helper checks whether the initial writer is still the writer. +WRITER_CHANGE_TIMEOUT_SEC: float = 180 +# Aurora can keep the initial writer as the writer, or make it the writer +# again. The helper then requests the failover again, at most this many times +# and only while this much of the deadline is left. +FAILOVER_MAX_REISSUES: int = 2 +FAILOVER_REISSUE_MIN_REMAINING_SEC: float = 120 +# After the failover the initial writer restarts and answers as a reader. +# If it keeps answering as the writer for this long without a break, it is +# still, or again, the writer. Before a normal restart it answers as the +# writer for well under a minute. +INITIAL_WRITER_REVERT_WINDOW_SEC: float = 60 +INITIAL_WRITER_POLL_INTERVAL_SEC: float = 1 +# How long ``RdsTestUtility`` waits for the cluster to reach a status when +# no timeout is passed in. +CLUSTER_STATUS_TIMEOUT_SEC: float = 600 +# How long ``make_sure_instances_up`` waits in all for the instances to +# reach the RDS status ``available`` and then accept a connection. An +# earlier deadline from the caller shortens it. +INSTANCE_UP_TIMEOUT_SEC: float = 300 +# How often ``make_sure_instances_up`` reads the instances' RDS status. +INSTANCE_STATUS_POLL_INTERVAL_SEC: float = 2 + +# ───── RDS events on a failed test ──────────────────────────────────── +# When a test fails on an Aurora or Multi-AZ DB cluster, the conftest logs +# the cluster's and its instances' RDS events from this far back, to show +# whether RDS restarted or failed over an instance around the failure. It covers one +# failover helper call plus the test's own work. Each RDS API call gets a +# short timeout and one attempt, the lookup stops at the first failed call, +# and it reads no more sources once its budget is spent, so it adds well +# under a minute to the failed test. +RDS_EVENTS_LOOKBACK_SEC: float = 900 +RDS_EVENTS_CALL_TIMEOUT_SEC: float = 5 +RDS_EVENTS_BUDGET_SEC: float = 20 + +# ───── Rerun after a cluster outage ─────────────────────────────────── +# On Aurora and Multi-AZ DB clusters, a test that failed because the +# cluster stopped accepting connections is run once more after this delay, +# so the instances can come back first. +CLUSTER_OUTAGE_RERUN_DELAY_SEC: float = 60 + # ───── Long-running failover-during-transaction test ─────────────────── # ``test_writer_fail_within_transaction_start_transaction`` exercises a # rare-but-realistic pathology: a writer instance failing mid-transaction diff --git a/tests/unit/test_aio_failover_plugin.py b/tests/unit/test_aio_failover_plugin.py index 0184bc9f8..59007e100 100644 --- a/tests/unit/test_aio_failover_plugin.py +++ b/tests/unit/test_aio_failover_plugin.py @@ -158,6 +158,42 @@ async def _raiser() -> Any: asyncio.run(_body()) +def test_connection_error_during_cursor_creation_starts_failover(): + # psycopg's Connection.cursor raises OperationalError('the connection is + # closed') on a connection a cut has already broken, and the async dialect + # lists cursor creation as network-bound, so failover must subscribe to it + # as sync failover does. + # Dispatch through the manager: only its chain filter reads the + # subscription, so plugin.execute alone passes without it. + import psycopg + + from aws_advanced_python_wrapper.aio.driver_dialect.psycopg import \ + AsyncPsycopgDriverDialect + from aws_advanced_python_wrapper.aio.plugin_manager import \ + AsyncPluginManager + from aws_advanced_python_wrapper.database_dialect import AuroraPgDialect + from aws_advanced_python_wrapper.pep249_methods import DbApiMethod + + async def _body() -> None: + props = Properties({"host": "cluster.example.com", "port": "5432"}) + svc = AsyncPluginServiceImpl(props, AsyncPsycopgDriverDialect()) + svc.database_dialect = AuroraPgDialect() + plugin = AsyncFailoverPlugin(svc, MagicMock(), props) + plugin._do_failover = AsyncMock() # type: ignore[method-assign] + mgr = AsyncPluginManager(plugin_service=svc, props=props, plugins=[plugin]) + svc.plugin_manager = mgr + + async def _create_cursor() -> None: + raise psycopg.OperationalError("the connection is closed") + + with pytest.raises(FailoverSuccessError): + await mgr.execute( + object(), DbApiMethod.CONNECTION_CURSOR, _create_cursor) + plugin._do_failover.assert_awaited_once() + + asyncio.run(_body()) + + def test_enabled_failover_picks_writer_by_default(): async def _body() -> None: plugin, svc, host_list_provider, driver_dialect = _build_plugin() @@ -199,6 +235,54 @@ async def _body() -> None: asyncio.run(_body()) +def test_writer_failover_uses_service_host_list_provider(): + # The wrapper hands the factory the provider built from the guessed + # dialect (a static one for an instance endpoint), and the plugin service + # replaces it once the dialect is confirmed. Writer failover must refresh + # through the service's provider, or it only ever sees the old writer. + w = HostInfo(host="writer.example.com", port=5432, role=HostRole.WRITER) + r = HostInfo(host="reader.example.com", port=5432, role=HostRole.READER) + # The factory's provider knows only the seed host, as a static one does. + plugin, svc, _static, driver_dialect = _build_plugin( + mode="strict_writer", timeout_sec=2.0, topology=(w,)) + conns = {w.host: MagicMock(name="conn-old-writer"), + r.host: MagicMock(name="conn-new-writer")} + svc.force_connect = AsyncMock(side_effect=lambda h, p, skip: conns[h.host]) + svc.get_host_role = AsyncMock( + side_effect=lambda c: HostRole.READER if c is conns[w.host] else HostRole.WRITER) + svc.set_current_connection = AsyncMock() + driver_dialect.abort_connection = AsyncMock() + aurora = MagicMock() + aurora.force_refresh = AsyncMock(return_value=( + HostInfo(host=w.host, port=5432, role=HostRole.READER), + HostInfo(host=r.host, port=5432, role=HostRole.WRITER))) + svc.host_list_provider = aurora + + async def _body() -> None: + deadline = asyncio.get_running_loop().time() + 2.0 + await plugin._failover_writer((w, r), driver_dialect, deadline, None) + + asyncio.run(_body()) + _, bound_host = svc.set_current_connection.call_args.args + assert bound_host.host == r.host + + +def test_reader_failover_uses_service_host_list_provider(): + w = HostInfo(host="writer.example.com", port=5432, role=HostRole.WRITER) + r = HostInfo(host="reader.example.com", port=5432, role=HostRole.READER) + # The factory's provider knows only the seed host, as a static one does. + plugin, svc, _static, driver_dialect = _build_plugin(mode="strict_reader", topology=(w,)) + aurora = MagicMock() + aurora.force_refresh = AsyncMock(return_value=(w, r)) + svc.host_list_provider = aurora + plugin._failover_reader = AsyncMock() # type: ignore[method-assign] + + asyncio.run(plugin._do_failover(driver_dialect=driver_dialect)) + + topology = plugin._failover_reader.call_args.args[0] + assert topology == (w, r) + + def test_enabled_failover_picks_reader_in_strict_reader_mode(): async def _body() -> None: plugin, svc, _hlp, driver_dialect = _build_plugin(mode="strict_reader") @@ -680,6 +764,61 @@ async def _open(target, _driver_dialect): assert attempts == ["r1", "w1"] +def test_reader_failover_leaves_unreachable_reader_candidates_available(): + """A reader candidate that fails to open is only dropped from the pass; + only the failed current host is marked UNAVAILABLE, as in sync + FailoverV2Plugin._failover_reader.""" + w = HostInfo(host="w1", port=5432, role=HostRole.WRITER) + r1 = HostInfo(host="r1", port=5432, role=HostRole.READER) + r2 = HostInfo(host="r2", port=5432, role=HostRole.READER) + plugin, svc, _hlp, driver_dialect = _build_plugin( + mode="reader-or-writer", topology=(w, r1, r2)) + svc._all_hosts = (w, r1, r2) + svc._current_host_info = r1 + # Select like the random selector: only readers marked available. + svc.get_host_info_by_strategy = ( # type: ignore[method-assign] + lambda role, strategy, hosts=None: next( + (h for h in hosts if h.role == role + and h.get_availability() == HostAvailability.AVAILABLE), None)) + + attempts = [] + + async def _open(target, _driver_dialect): + attempts.append(target.host) + if target.role == HostRole.READER: + raise OSError(f"{target.host} unreachable") + return MagicMock() + + plugin._open_connection = _open # type: ignore[method-assign] + + asyncio.run(plugin._do_failover(driver_dialect=driver_dialect)) + + assert attempts == ["r2", "w1"] + assert r1.get_availability() == HostAvailability.UNAVAILABLE + assert r2.get_availability() == HostAvailability.AVAILABLE + + +def test_reader_failover_leaves_unreachable_original_writer_available(): + """An original writer that fails to open is not marked UNAVAILABLE either, + as in sync FailoverV2Plugin._failover_reader: it may be restarting as a reader.""" + w = HostInfo(host="w1", port=5432, role=HostRole.WRITER) + r1 = HostInfo(host="r1", port=5432, role=HostRole.READER) + plugin, svc, _hlp, driver_dialect = _build_plugin( + mode="reader-or-writer", topology=(w, r1), timeout_sec=0.5) + svc._all_hosts = (w, r1) + svc._current_host_info = r1 + + async def _open(target, _driver_dialect): + raise OSError(f"{target.host} unreachable") + + plugin._open_connection = _open # type: ignore[method-assign] + + with pytest.raises(FailoverFailedError): + asyncio.run(plugin._do_failover(driver_dialect=driver_dialect)) + + assert w.get_availability() == HostAvailability.AVAILABLE + + def test_failover_falls_back_to_initial_host_when_topology_empty(): """If force_refresh returns empty topology, use initial_connection_host_info.""" plugin, svc, host_list_provider, driver_dialect = _build_plugin( diff --git a/tests/unit/test_aio_gdb_failover.py b/tests/unit/test_aio_gdb_failover.py index 68d3d468a..c4e3c737b 100644 --- a/tests/unit/test_aio_gdb_failover.py +++ b/tests/unit/test_aio_gdb_failover.py @@ -76,6 +76,8 @@ def _make_plugin(*, home_region="us-east-1", host=_W_EAST, overrides=None, hlp = MagicMock() hlp.force_refresh = AsyncMock(return_value=tuple(all_hosts)) + # The plugin refreshes through the service's provider. + svc.host_list_provider = hlp plugin = AsyncGdbFailoverPlugin(svc, hlp, props) return plugin, svc, hlp, conn diff --git a/tests/unit/test_aio_plugin_service_extras.py b/tests/unit/test_aio_plugin_service_extras.py index 837c2eeca..766744fa1 100644 --- a/tests/unit/test_aio_plugin_service_extras.py +++ b/tests/unit/test_aio_plugin_service_extras.py @@ -2,7 +2,7 @@ import asyncio from typing import Optional -from unittest.mock import AsyncMock, MagicMock +from unittest.mock import AsyncMock, MagicMock, patch import pytest @@ -1389,6 +1389,38 @@ async def _run(): asyncio.run(_run()) +def test_replacement_provider_is_armed_for_panic_mode(): + """The provider built from the guessed dialect can be a static one, which + has no probe to carry across. The replacement must still be armed, and + before its first refresh: that refresh builds the topology monitor, which + copies the probe when it is constructed.""" + from aws_advanced_python_wrapper.aio.host_list_provider import ( + AsyncAuroraHostListProvider, AsyncStaticHostListProvider) + from aws_advanced_python_wrapper.database_dialect import AuroraPgDialect + + props = Properties({"host": "h", "port": "5432"}) + svc = _service_with_manager(AuroraPgDialect(), None, props) + svc.host_list_provider = AsyncStaticHostListProvider(props) + probe_at_refresh = [] + + async def _refresh(_conn): + provider = svc.host_list_provider + assert isinstance(provider, AsyncAuroraHostListProvider) + probe_at_refresh.append(provider._probe_host) + + svc.force_refresh_host_list = AsyncMock(side_effect=_refresh) + probe = MagicMock(name="probe") + + async def _run(): + await svc._update_host_list_provider(MagicMock(name="conn")) + + with patch("aws_advanced_python_wrapper.aio.cluster_topology_monitor.build_probe_host", + return_value=probe) as build_probe_host: + asyncio.run(_run()) + build_probe_host.assert_called_once_with(svc, props) + assert probe_at_refresh == [probe] + + def test_is_static_host_list_provider_reflects_provider_type(): from aws_advanced_python_wrapper.aio.host_list_provider import \ AsyncStaticHostListProvider diff --git a/tests/unit/test_aio_read_write_splitting.py b/tests/unit/test_aio_read_write_splitting.py index fc8076395..d76d54d48 100644 --- a/tests/unit/test_aio_read_write_splitting.py +++ b/tests/unit/test_aio_read_write_splitting.py @@ -130,6 +130,61 @@ async def _work() -> None: asyncio.run(_body()) +def test_set_read_only_true_uses_service_host_list_provider(): + # The factory's provider was built from the guessed dialect and knows only + # the seed host; the plugin service replaces it once the dialect is + # confirmed. The plugin must refresh through the service's provider. + async def _body() -> None: + writer = HostInfo(host="writer.example", port=5432, role=HostRole.WRITER) + reader = HostInfo(host="reader.example", port=5432, role=HostRole.READER) + plugin, svc, *_ = _build(topology=(writer,)) + replacement = MagicMock() + replacement.refresh = AsyncMock(return_value=(writer, reader)) + svc.host_list_provider = replacement + + async def _work() -> None: + return None + + await plugin.execute( + object(), + DbApiMethod.CONNECTION_SET_READ_ONLY.method_name, + _work, + True, + ) + assert svc.current_host_info is not None + assert svc.current_host_info.host == "reader.example" + + asyncio.run(_body()) + + +def test_set_read_only_false_uses_service_host_list_provider(): + # After a failover the service's provider names the new writer, while the + # factory's provider still names the old one. + async def _body() -> None: + old_writer = HostInfo(host="writer.example", port=5432, role=HostRole.WRITER) + reader = HostInfo(host="reader.example", port=5432, role=HostRole.READER) + new_writer = HostInfo(host="new-writer.example", port=5432, role=HostRole.WRITER) + plugin, svc, *_ = _build(topology=(old_writer, reader)) + replacement = MagicMock() + replacement.refresh = AsyncMock(return_value=(new_writer, reader)) + svc.host_list_provider = replacement + + async def _work() -> None: + return None + + for read_only in (True, False): + await plugin.execute( + object(), + DbApiMethod.CONNECTION_SET_READ_ONLY.method_name, + _work, + read_only, + ) + assert svc.current_host_info is not None + assert svc.current_host_info.host == "new-writer.example" + + asyncio.run(_body()) + + def test_set_read_only_false_switches_back_to_writer(): async def _body() -> None: plugin, svc, hlp, dd, writer_conn = _build() diff --git a/tests/unit/test_aio_stale_dns_plugin.py b/tests/unit/test_aio_stale_dns_plugin.py index c58a4472d..a0cfd67b3 100644 --- a/tests/unit/test_aio_stale_dns_plugin.py +++ b/tests/unit/test_aio_stale_dns_plugin.py @@ -21,7 +21,8 @@ 3. Writer-cluster host + reader role -> force-refresh + swap. 4. Writer-cluster host + writer role + mismatched DNS -> swap. 5. Writer not in allowed topology -> raises AwsWrapperError. -6. ``notify_host_list_changed`` with ``CONVERTED_TO_READER`` resets cache. +6. ``notify_host_list_changed`` with ``CONVERTED_TO_READER`` or ``HOST_DELETED`` + resets cache. """ from __future__ import annotations @@ -374,6 +375,21 @@ def test_notify_host_list_changed_resets_on_converted_to_reader(): assert plugin._writer_host_address is None +def test_notify_host_list_changed_resets_on_host_deleted(): + plugin, _, _ = _build() + writer = _writer_instance() + plugin._writer_host_info = writer + plugin._writer_host_address = "10.0.0.99" + + changes = { + writer.url: {HostEvent.HOST_DELETED}, + } + plugin.notify_host_list_changed(changes) + + assert plugin._writer_host_info is None + assert plugin._writer_host_address is None + + def test_notify_host_list_changed_ignores_unrelated_events(): plugin, _, _ = _build() writer = _writer_instance() diff --git a/tests/unit/test_connection.py b/tests/unit/test_connection.py index 8e5f20684..c5b38c4b9 100644 --- a/tests/unit/test_connection.py +++ b/tests/unit/test_connection.py @@ -14,18 +14,33 @@ from __future__ import annotations -from typing import TYPE_CHECKING +import gc +from typing import TYPE_CHECKING, Any, Callable, Set from unittest.mock import MagicMock, patch import psycopg import pytest +from mysql.connector import MySQLConnection +from mysql.connector.cursor import MySQLCursor +from sqlalchemy.pool import QueuePool if TYPE_CHECKING: from aws_advanced_python_wrapper.pep249 import Connection +from aws_advanced_python_wrapper.driver_dialect import DriverDialect +from aws_advanced_python_wrapper.errors import (AwsWrapperError, + FailoverSuccessError) from aws_advanced_python_wrapper.hostinfo import HostInfo +from aws_advanced_python_wrapper.mysql_driver_dialect import MySQLDriverDialect +from aws_advanced_python_wrapper.pep249_methods import DbApiMethod +from aws_advanced_python_wrapper.plugin import Plugin from aws_advanced_python_wrapper.plugin_service import ( - PluginServiceImpl, PluginServiceManagerContainer) + PluginManager, PluginServiceImpl, PluginServiceManagerContainer) +from aws_advanced_python_wrapper.sqlalchemy_driver_dialect import \ + SqlAlchemyDriverDialect +from aws_advanced_python_wrapper.utils.properties import Properties +from aws_advanced_python_wrapper.utils.telemetry.null_telemetry import \ + NullTelemetryFactory from aws_advanced_python_wrapper.wrapper import (AwsWrapperConnection, AwsWrapperCursor) @@ -144,6 +159,84 @@ def test_cursor_getattr_delegates_driver_attrs_including_underscore(): _ = fresh._target_cursor +class _ReleaseInPipelinePlugin(Plugin): + def __init__(self, release: Callable[[], None]): + self._release = release + + @property + def subscribed_methods(self) -> Set[str]: + return {DbApiMethod.ALL.method_name} + + def execute(self, target: type, method_name: str, execute_func: Callable, *args: Any, **kwargs: Any) -> Any: + # Free the old connection after PluginManager.execute's pre-check, as a garbage + # collection during the call can, then let the call reach the driver. + self._release() + gc.collect() + return execute_func() + + +def _cursor_through_plugin_manager(driver_dialect, connection, driver_cursor, release): + container = PluginServiceManagerContainer() + plugin_service = MagicMock() + plugin_service.driver_dialect = driver_dialect + plugin_service.is_network_bound_method.return_value = False + plugin_service.current_connection = connection + container.plugin_service = plugin_service + plugin_manager = PluginManager(container, Properties({"plugins": ""}), NullTelemetryFactory()) + plugin_manager._plugins = [_ReleaseInPipelinePlugin(release), *plugin_manager._plugins] + cursor = AwsWrapperCursor(MagicMock(), plugin_service, plugin_manager, driver_cursor) + # Failover replaces the current connection. + plugin_service.current_connection = MySQLConnection() + return cursor + + +def _cursor_on_replaced_mysql_connection(): + # mysql-connector's cursor holds only a weak proxy to its connection, so after + # failover only `held` and the wrapper cursor can keep the old connection alive. + held = [MySQLConnection()] + cursor = _cursor_through_plugin_manager( + MySQLDriverDialect(Properties()), held[0], MySQLCursor(held[0]), held.clear) + return cursor, held + + +def test_cursor_close_after_failover(): + cursor, _ = _cursor_on_replaced_mysql_connection() + + cursor.close() + + +def test_cursor_with_block_keeps_failover_error(): + cursor, _ = _cursor_on_replaced_mysql_connection() + + with pytest.raises(FailoverSuccessError): + with cursor: + raise FailoverSuccessError("failover succeeded") + + +def test_cursor_execute_after_failover_raises_wrapper_error(): + cursor, held = _cursor_on_replaced_mysql_connection() + held.clear() + gc.collect() + + with pytest.raises(AwsWrapperError): + cursor.execute("SELECT 1") + + +def test_pooled_cursor_close_after_invalidate(): + # A pooled connection is SQLAlchemy's proxy, which drops its driver connection + # when invalidated; the driver cursor was made on that driver connection. + pool = QueuePool(MySQLConnection, pool_size=1, max_overflow=0) + pooled_conn = pool.connect() + driver_dialect = SqlAlchemyDriverDialect(MagicMock(spec=DriverDialect), Properties()) + cursor = _cursor_through_plugin_manager( + driver_dialect, pooled_conn, MySQLCursor(pooled_conn.driver_connection), pooled_conn.invalidate) + + try: + cursor.close() + finally: + pool.dispose() + + def _make_sync_conn(target=None): wrapper = AwsWrapperConnection.__new__(AwsWrapperConnection) plugin_service = MagicMock() diff --git a/tests/unit/test_rds_test_utility.py b/tests/unit/test_rds_test_utility.py new file mode 100644 index 000000000..4bf6c960a --- /dev/null +++ b/tests/unit/test_rds_test_utility.py @@ -0,0 +1,737 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import asyncio +import datetime +import socket + +import psycopg +import psycopg.errors +import pytest +from botocore.exceptions import ClientError, EndpointConnectionError +from mysql.connector.errors import \ + ConnectionTimeoutError as MySQLConnectionTimeoutError +from mysql.connector.errors import InterfaceError, OperationalError + +import tests.integration.container.utils.rds_test_utility as rds_test_utility +from aws_advanced_python_wrapper.errors import (AwsConnectError, + FailoverFailedError, + ReadWriteSplittingError) +from aws_advanced_python_wrapper.hostinfo import HostRole +from tests.integration.container.utils.database_engine import DatabaseEngine +from tests.integration.container.utils.database_engine_deployment import \ + DatabaseEngineDeployment +from tests.integration.container.utils.test_timings import ( + FAILOVER_DEADLINE_SEC, FAILOVER_MAX_REISSUES, + INITIAL_WRITER_POLL_INTERVAL_SEC, INITIAL_WRITER_REVERT_WINDOW_SEC, + INSTANCE_STATUS_POLL_INTERVAL_SEC, INSTANCE_UP_TIMEOUT_SEC, + WRITER_CHANGE_TIMEOUT_SEC) + +_START_SEC = 1000.0 + + +def _described_instances(instance_2_status): + return {"DBInstances": [ + {"DBInstanceIdentifier": "instance-1", "DBInstanceStatus": "available"}, + {"DBInstanceIdentifier": "instance-2", "DBInstanceStatus": instance_2_status}, + ]} + + +@pytest.fixture +def clock(mocker): + now = [_START_SEC] + + def _sleep(seconds): + now[0] += seconds + + mocker.patch.object(rds_test_utility, "sleep", side_effect=_sleep) + mocker.patch.object(rds_test_utility, "timeit").default_timer.side_effect = lambda: now[0] + return now + + +@pytest.fixture +def utility(mocker, clock): + mocker.patch.object(rds_test_utility.boto3, "client") + env = mocker.patch.object(rds_test_utility, "TestEnvironment").get_current.return_value + env.get_deployment.return_value = DatabaseEngineDeployment.AURORA + env.get_engine.return_value = DatabaseEngine.PG + mocker.patch.object(rds_test_utility, "socket").gethostbyname.side_effect = ["10.0.0.1", "10.0.0.2"] + + target = rds_test_utility.RdsTestUtility("us-east-2") + target._client.describe_db_instances.return_value = _described_instances("available") + mocker.patch.object(target, "writer_changed", return_value=True) + mocker.patch.object(target, "make_sure_instances_up") + mocker.patch.object(target, "failover_cluster") + mocker.patch.object(target, "wait_until_cluster_has_desired_status") + mocker.patch.object(target, "_open_connection") + mocker.patch.object(target, "query_host_role") + return target, env + + +def test_failover_waits_until_initial_writer_accepts_connections(utility, mocker): + target, env = utility + target._open_connection.side_effect = [ConnectionRefusedError("starting up"), mocker.MagicMock()] + target.query_host_role.return_value = HostRole.READER + + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster") + + assert target.failover_cluster.call_count == 1 + assert target._open_connection.call_count == 2 + env.get_database_info.return_value.get_instance.assert_called_with("instance-1") + target._open_connection.assert_called_with(env.get_database_info.return_value.get_instance.return_value) + + +def test_failover_initial_writer_stays_writer_reissued(utility): + target, _ = utility + target.query_host_role.side_effect = lambda conn, engine: ( + HostRole.WRITER if target.failover_cluster.call_count == 1 else HostRole.READER) + + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster") + + assert target.failover_cluster.call_count == 2 + target.failover_cluster.assert_called_with("cluster", None, FAILOVER_DEADLINE_SEC - INITIAL_WRITER_REVERT_WINDOW_SEC) + + +def test_initial_writer_kept_writer_role_skips_non_aurora(utility, clock): + target, env = utility + env.get_deployment.return_value = DatabaseEngineDeployment.RDS_MULTI_AZ_CLUSTER + + assert target._initial_writer_kept_writer_role("instance-1", clock[0] + FAILOVER_DEADLINE_SEC) is False + target._open_connection.assert_not_called() + + +def test_failover_waits_through_short_writer_phase(utility, mocker): + target, _ = utility + target._open_connection.side_effect = [mocker.MagicMock()] * 55 + [ConnectionRefusedError("restarting"), mocker.MagicMock()] + target.query_host_role.side_effect = [HostRole.WRITER] * 55 + [HostRole.READER] + + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster") + + assert target.failover_cluster.call_count == 1 + assert target._open_connection.call_count == 57 + + +def test_failover_waits_through_writer_phase_after_long_restart(utility, mocker): + target, _ = utility + target._open_connection.side_effect = [ConnectionRefusedError("restarting")] * 60 + [mocker.MagicMock()] * 2 + target.query_host_role.side_effect = [HostRole.WRITER, HostRole.READER] + + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster") + + assert target.failover_cluster.call_count == 1 + + +def test_failover_initial_writer_unreachable_returns_at_deadline(utility, clock, mocker): + target, _ = utility + + def _slow_new_writer(initial_writer_id, cluster_id, timeout_sec): + clock[0] += 200 + return True + + target.writer_changed.side_effect = _slow_new_writer + target._open_connection.side_effect = ConnectionRefusedError("starting up") + + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster") + + target.failover_cluster.assert_called_once_with("cluster", None, FAILOVER_DEADLINE_SEC) + target.make_sure_instances_up.assert_called_once_with(mocker.ANY, _START_SEC + FAILOVER_DEADLINE_SEC) + assert clock[0] - _START_SEC <= FAILOVER_DEADLINE_SEC + + +def test_failover_no_new_writer_fails_at_deadline(utility, clock): + target, _ = utility + + def _no_new_writer(initial_writer_id, cluster_id, timeout_sec): + clock[0] += timeout_sec + return False + + target.writer_changed.side_effect = _no_new_writer + target._open_connection.side_effect = ConnectionRefusedError("unreachable") + + with pytest.raises(pytest.fail.Exception, match="ConnectionRefusedError: unreachable") as excinfo: + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster") + + assert target.failover_cluster.call_count == 1 + assert clock[0] - _START_SEC <= FAILOVER_DEADLINE_SEC + assert rds_test_utility.RdsTestUtility.is_cluster_outage(excinfo.value, after_failover=True) is True + + +def test_failover_writer_unchanged_reissued(utility, clock): + target, _ = utility + + def _new_writer_after_reissue(initial_writer_id, cluster_id, timeout_sec): + if target.failover_cluster.call_count == 1: + clock[0] += timeout_sec + return False + return True + + target.writer_changed.side_effect = _new_writer_after_reissue + target.query_host_role.side_effect = lambda conn, engine: ( + HostRole.WRITER if target.failover_cluster.call_count == 1 else HostRole.READER) + + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster") + + assert target.failover_cluster.call_count == 2 + + +def test_failover_near_deadline_not_reissued(utility, clock): + target, _ = utility + + def _slow_new_writer(initial_writer_id, cluster_id, timeout_sec): + clock[0] += 300 + return True + + target.writer_changed.side_effect = _slow_new_writer + target.query_host_role.return_value = HostRole.WRITER + + with pytest.raises(Exception, match="not successful"): + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster") + + assert target.failover_cluster.call_count == 1 + + +def test_failover_writer_window_bounded_by_deadline(utility, clock): + target, _ = utility + + def _no_new_writer_until_late(initial_writer_id, cluster_id, timeout_sec): + # The first check uses up all but 30 s of the deadline + clock[0] = _START_SEC + FAILOVER_DEADLINE_SEC - 30 + return False + + target.writer_changed.side_effect = _no_new_writer_until_late + target.query_host_role.return_value = HostRole.WRITER + + with pytest.raises(pytest.fail.Exception, match="did not finish within"): + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster") + + assert clock[0] - _START_SEC <= FAILOVER_DEADLINE_SEC + 2 + + +def test_failover_dns_wait_bounded_by_deadline(utility, clock): + target, _ = utility + rds_test_utility.socket.gethostbyname.side_effect = None + rds_test_utility.socket.gethostbyname.return_value = "10.0.0.1" + target.query_host_role.return_value = HostRole.READER + + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster") + + assert clock[0] - _START_SEC <= FAILOVER_DEADLINE_SEC + 1 + + +def test_make_sure_instances_up_tries_once_after_deadline(utility, clock): + target, _ = utility + target._open_connection.side_effect = ConnectionRefusedError("starting up") + + with pytest.raises(pytest.fail.Exception, match="instance-2") as excinfo: + rds_test_utility.RdsTestUtility.make_sure_instances_up(target, ["instance-2"], clock[0] - 1) + + assert target._open_connection.call_count == 1 + assert rds_test_utility.RdsTestUtility.is_cluster_outage(excinfo.value, after_failover=True) is True + + +def test_failover_reissues_at_most_max_times(utility): + target, _ = utility + target.query_host_role.return_value = HostRole.WRITER + + with pytest.raises(Exception, match="not successful"): + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster") + + assert target.failover_cluster.call_count == 1 + FAILOVER_MAX_REISSUES + + +def test_failover_initial_writer_reader_not_reissued(utility, clock): + target, _ = utility + + def _new_writer_after_lag(initial_writer_id, cluster_id, timeout_sec): + if target.writer_changed.call_count == 1: + clock[0] += timeout_sec + return False + return True + + target.writer_changed.side_effect = _new_writer_after_lag + target.query_host_role.return_value = HostRole.READER + + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster") + + assert target.failover_cluster.call_count == 1 + + +def test_failover_writer_window_resets_after_restart(utility, mocker): + target, _ = utility + target._open_connection.side_effect = [mocker.MagicMock()] + [ConnectionRefusedError("restarting")] * 70 + [mocker.MagicMock()] * 2 + target.query_host_role.side_effect = [HostRole.WRITER, HostRole.WRITER, HostRole.READER] + + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster") + + assert target.failover_cluster.call_count == 1 + + +def test_failover_needs_writer_window_to_reissue(utility, clock): + target, _ = utility + + def _new_writer_after_lag(initial_writer_id, cluster_id, timeout_sec): + if target.writer_changed.call_count == 1: + clock[0] += timeout_sec + return False + return True + + target.writer_changed.side_effect = _new_writer_after_lag + target.query_host_role.side_effect = [HostRole.WRITER] * 10 + [HostRole.READER] * 5 + + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster") + + assert target.failover_cluster.call_count == 1 + + +def test_failover_initial_writer_down_waits_for_new_writer(utility, clock): + target, _ = utility + checked_at = [] + + def _new_writer_after_lag(initial_writer_id, cluster_id, timeout_sec): + checked_at.append(clock[0]) + if target.writer_changed.call_count == 1: + clock[0] += timeout_sec + return False + return True + + target.writer_changed.side_effect = _new_writer_after_lag + target._open_connection.side_effect = ConnectionRefusedError("down") + + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster") + + assert target.failover_cluster.call_count == 1 + assert checked_at[1] - checked_at[0] < WRITER_CHANGE_TIMEOUT_SEC + INITIAL_WRITER_POLL_INTERVAL_SEC + + +def test_failover_off_aurora_writer_unchanged_reissued(utility, clock): + target, env = utility + env.get_deployment.return_value = DatabaseEngineDeployment.RDS_MULTI_AZ_CLUSTER + + def _new_writer_after_reissue(initial_writer_id, cluster_id, timeout_sec): + if target.writer_changed.call_count == 1: + clock[0] += timeout_sec + return False + return True + + target.writer_changed.side_effect = _new_writer_after_reissue + + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster") + + assert target.failover_cluster.call_count == 2 + target._open_connection.assert_not_called() + + +def test_failover_cluster_passes_timeout_to_status_wait(utility, mocker): + target, _ = utility + target._client.failover_db_cluster.return_value = {"DBCluster": {}, "ResponseMetadata": {"HTTPStatusCode": 200}} + + rds_test_utility.RdsTestUtility.failover_cluster(target, "cluster", None, 100) + + target.wait_until_cluster_has_desired_status.assert_called_once_with("cluster", "available", 100) + + +def test_wait_until_cluster_has_desired_status_stops_at_timeout(utility, clock, mocker): + target, _ = utility + + class _ClockDatetime(datetime.datetime): + @classmethod + def now(cls, tz=None): + return datetime.datetime(2026, 1, 1) + datetime.timedelta(seconds=clock[0]) + + mocker.patch.object(rds_test_utility, "datetime", _ClockDatetime) + mocker.patch.object(target, "get_db_cluster", return_value={"Status": "failing-over"}) + + with pytest.raises(TimeoutError): + rds_test_utility.RdsTestUtility.wait_until_cluster_has_desired_status(target, "cluster", "available", 100) + + assert clock[0] - _START_SEC <= 110 + + +def test_failover_late_first_request_not_reissued(utility, clock): + target, _ = utility + + def _new_writer_after_lag(initial_writer_id, cluster_id, timeout_sec): + if target.writer_changed.call_count == 1: + clock[0] += timeout_sec + return False + return True + + target.writer_changed.side_effect = _new_writer_after_lag + target.query_host_role.side_effect = lambda conn, engine: ( + HostRole.READER if target.wait_until_cluster_has_desired_status.called else HostRole.WRITER) + + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster") + + assert target.failover_cluster.call_count == 1 + + +def test_failover_initial_writer_restart_rechecks_new_writer(utility, clock, mocker): + target, _ = utility + + def _new_writer_after_lag(initial_writer_id, cluster_id, timeout_sec): + if target.writer_changed.call_count == 1: + clock[0] += timeout_sec + return False + return True + + def _writer_then_restarting(instance_info): + if target._open_connection.call_count == 1: + return mocker.MagicMock() + raise ConnectionRefusedError("restarting") + + target.writer_changed.side_effect = _new_writer_after_lag + target._open_connection.side_effect = _writer_then_restarting + target.query_host_role.return_value = HostRole.WRITER + + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster") + + assert target.writer_changed.call_count == 2 + assert target.failover_cluster.call_count == 1 + + +def test_get_recent_events_merges_sources_oldest_first(utility): + target, _ = utility + paginator = target._client.get_paginator.return_value + paginator.paginate.side_effect = [ + [{"Events": [{"Date": datetime.datetime(2026, 1, 1, 0, 2), "SourceIdentifier": "cluster", "Message": "second"}]}], + [{"Events": [{"Date": datetime.datetime(2026, 1, 1, 0, 1), "SourceIdentifier": "instance-1", "Message": "first"}]}], + [{"Events": []}], + ] + + events = target.get_recent_events("cluster", ["instance-1", "instance-2"], 900, 20) + + assert [event["Message"] for event in events] == ["first", "second"] + target._client.get_paginator.assert_called_once_with("describe_events") + requests = [call.kwargs for call in paginator.paginate.call_args_list] + assert [request["SourceType"] for request in requests] == ["db-cluster", "db-instance", "db-instance"] + assert [request["SourceIdentifier"] for request in requests] == ["cluster", "instance-1", "instance-2"] + expected_start = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(seconds=900) + assert abs((requests[0]["StartTime"] - expected_start).total_seconds()) < 60 + + +def _raised_from(error, cause): + error.__cause__ = cause + return error + + +def _raised_while_handling(error, context): + error.__context__ = context + return error + + +def _cause_cycle(error, cause): + error.__cause__ = cause + cause.__cause__ = error + return error + + +_MYSQL_CONNECT_TIMEOUT = "2003: Can't connect to MySQL server on 'instance-1:3306' (timed out)" +_PG_CONNECT_TIMEOUT = "connection timeout expired" + + +@pytest.mark.parametrize("error, after_failover, expected", [ + pytest.param(MySQLConnectionTimeoutError(_MYSQL_CONNECT_TIMEOUT), False, True, id="mysql_connect_timeout"), + pytest.param(psycopg.OperationalError(_PG_CONNECT_TIMEOUT), False, True, id="pg_connect_timeout"), + pytest.param( + pytest.fail.Exception("Failover from instance-1 did not finish within 420 s. Last connect error: None"), + True, True, id="helper_deadline"), + pytest.param( + _raised_from(MySQLConnectionTimeoutError(_MYSQL_CONNECT_TIMEOUT), socket.timeout("timed out")), + False, True, id="connect_timeout_from_socket_timeout"), + pytest.param( + pytest.fail.Exception("Instance instance-2 did not accept a connection: OperationalError: timeout"), + True, True, id="instance_down"), + pytest.param( + pytest.fail.Exception("Instances did not become available: instance-2 is 'rebooting'"), + True, True, id="instance_not_available"), + pytest.param( + pytest.fail.Exception("Instances not in cluster 'cluster': instance-3"), + False, False, id="instance_not_in_cluster"), + pytest.param( + pytest.fail.Exception( + "Instance instance-2 did not accept a connection: DatabaseError: 1040 (08004): Too many connections"), + True, False, id="instance_full_mysql"), + pytest.param( + _cause_cycle(MySQLConnectionTimeoutError(_MYSQL_CONNECT_TIMEOUT), socket.timeout("timed out")), + False, True, id="connect_timeout_cause_cycle"), + pytest.param( + _raised_from(MySQLConnectionTimeoutError(_MYSQL_CONNECT_TIMEOUT), asyncio.TimeoutError()), + False, True, id="connect_timeout_from_asyncio_timeout"), + pytest.param( + _raised_from(psycopg.OperationalError(_PG_CONNECT_TIMEOUT), psycopg.errors.ConnectionTimeout(_PG_CONNECT_TIMEOUT)), + False, True, id="pg_connect_timeout_from_connection_timeout"), + pytest.param( + pytest.fail.Exception( + "The test setup step timed out while waiting for the test custom endpoint to become available: 'ep'."), + False, False, id="custom_endpoint_not_available"), + pytest.param( + pytest.fail.Exception("Could not read the RDS status of the instances: EndpointConnectionError: timeout"), + False, False, id="instance_status_unreadable"), + pytest.param(None, False, False, id="no_error"), + pytest.param(MySQLConnectionTimeoutError(_MYSQL_CONNECT_TIMEOUT), True, False, id="connect_timeout_after_failover"), + pytest.param( + pytest.fail.Exception("Instance instance-2 did not accept a connection: OperationalError: too many connections"), + True, False, id="instance_full"), + pytest.param( + InterfaceError("2003: Can't connect to MySQL server on 'instance-1:3306' (111 Connection refused)"), + False, False, id="mysql_refused"), + pytest.param( + OperationalError("2013: Lost connection to MySQL server during query (timed out)"), False, False, id="mysql_lost"), + pytest.param( + psycopg.OperationalError('connection failed: connection to server at "1.2.3.4", port 5432 failed: Connection refused'), + False, False, id="pg_refused"), + pytest.param(psycopg.OperationalError("FATAL: the database system is starting up"), False, False, id="pg_starting_up"), + pytest.param( + _raised_from(FailoverFailedError("writer failover failed"), MySQLConnectionTimeoutError(_MYSQL_CONNECT_TIMEOUT)), + False, False, id="failover_failed"), + pytest.param( + _raised_from(AwsConnectError("connect failed"), psycopg.OperationalError(_PG_CONNECT_TIMEOUT)), + False, False, id="wrapper_connect_error"), + pytest.param( + _raised_from(ReadWriteSplittingError("switch failed"), MySQLConnectionTimeoutError(_MYSQL_CONNECT_TIMEOUT)), + False, False, id="read_write_splitting_error"), + pytest.param( + _raised_while_handling( + ReferenceError("weakly-referenced object no longer exists"), + _raised_from(FailoverFailedError("writer failover failed"), MySQLConnectionTimeoutError(_MYSQL_CONNECT_TIMEOUT))), + False, False, id="with_exit_hides_failover_failed"), + pytest.param( + _raised_while_handling(KeyError("writer"), MySQLConnectionTimeoutError(_MYSQL_CONNECT_TIMEOUT)), + False, False, id="key_error_in_except"), + pytest.param( + _raised_while_handling( + RuntimeError("dictionary changed size during iteration"), psycopg.OperationalError(_PG_CONNECT_TIMEOUT)), + False, False, id="runtime_error_in_except"), + pytest.param( + _raised_while_handling(AssertionError("wrong writer"), psycopg.OperationalError(_PG_CONNECT_TIMEOUT)), + False, False, id="assert_in_except"), + pytest.param(AssertionError("assert 'instance-1' != 'instance-1'"), False, False, id="wrong_writer"), + pytest.param( + AssertionError("Instance instance-2 did not accept a connection"), False, False, id="helper_text_in_assert"), + pytest.param( + _raised_while_handling(MySQLConnectionTimeoutError(_MYSQL_CONNECT_TIMEOUT), FailoverFailedError("failover failed")), + False, False, id="connect_timeout_while_failover_failed"), + pytest.param( + _raised_from(psycopg.OperationalError(_PG_CONNECT_TIMEOUT), AwsConnectError("connect failed")), + False, False, id="connect_timeout_from_wrapper_error"), + pytest.param( + _raised_while_handling(MySQLConnectionTimeoutError(_MYSQL_CONNECT_TIMEOUT), AssertionError("wrong writer")), + False, False, id="cleanup_timeout_after_assert"), + pytest.param( + _raised_while_handling(psycopg.OperationalError(_PG_CONNECT_TIMEOUT), psycopg.ProgrammingError("bad query")), + False, False, id="cleanup_timeout_after_driver_error"), + pytest.param(AwsConnectError(_MYSQL_CONNECT_TIMEOUT), False, False, id="wrapper_error_with_timeout_text"), + pytest.param(FailoverFailedError(_PG_CONNECT_TIMEOUT), False, False, id="failover_error_with_timeout_text"), + pytest.param( + pytest.fail.Exception("Failover from instance-1 did not finish within 420 s. " + "Last connect error: OperationalError: FATAL: sorry, too many clients already"), + True, False, id="helper_deadline_server_full"), + pytest.param( + pytest.fail.Exception("Instance instance-2 did not accept a connection: OperationalError: FATAL: " + "remaining connection slots are reserved for roles with privileges of the rds_reserved role"), + True, False, id="instance_down_slots_reserved"), + pytest.param( + _raised_from(psycopg.OperationalError(_PG_CONNECT_TIMEOUT), + psycopg.OperationalError("FATAL: remaining connection slots are reserved for non-replication " + "superuser connections")), + False, False, id="connect_timeout_from_slots_reserved"), + pytest.param( + _raised_while_handling(psycopg.OperationalError(_PG_CONNECT_TIMEOUT), psycopg.errors.QueryCanceled("canceled")), + False, False, id="cleanup_timeout_after_query_canceled"), + pytest.param( + _raised_while_handling( + MySQLConnectionTimeoutError(_MYSQL_CONNECT_TIMEOUT), OperationalError("MySQL Connection not available")), + False, False, id="cleanup_timeout_after_connection_not_available"), + pytest.param( + _raised_while_handling( + MySQLConnectionTimeoutError(_MYSQL_CONNECT_TIMEOUT), + _raised_while_handling(socket.timeout("timed out"), AssertionError("wrong writer"))), + False, False, id="assert_two_links_down"), +]) +def test_is_cluster_outage(error, after_failover, expected): + assert rds_test_utility.RdsTestUtility.is_cluster_outage(error, after_failover) is expected + + +def test_get_recent_events_stops_at_budget(utility, clock): + target, _ = utility + paginator = target._client.get_paginator.return_value + + def _slow_pages(**kwargs): + clock[0] += 15 + return [{"Events": []}] + + paginator.paginate.side_effect = _slow_pages + + target.get_recent_events("cluster", ["instance-1", "instance-2"], 900, 20) + + assert paginator.paginate.call_count == 2 + + +def test_failover_cluster_marks_failover_requested(utility, mocker): + target, _ = utility + target._client.failover_db_cluster.return_value = {"DBCluster": {}, "ResponseMetadata": {"HTTPStatusCode": 200}} + mocker.patch.object(rds_test_utility.RdsTestUtility, "failover_requested", False) + + rds_test_utility.RdsTestUtility.failover_cluster(target, "cluster", None, 100) + + assert rds_test_utility.RdsTestUtility.failover_requested is True + + +def test_make_sure_instances_up_after_one_refusal(utility, mocker): + target, _ = utility + target._open_connection.side_effect = [ConnectionRefusedError("starting up"), mocker.MagicMock()] + + rds_test_utility.RdsTestUtility.make_sure_instances_up(target, ["instance-2"]) + + assert target._open_connection.call_count == 2 + + +def test_make_sure_instances_up_waits_until_available(utility, clock): + target, env = utility + env.get_cluster_name.return_value = "cluster" + target._client.describe_db_instances.side_effect = [ + _described_instances("rebooting"), _described_instances("available")] + + rds_test_utility.RdsTestUtility.make_sure_instances_up(target, ["instance-1", "instance-2"]) + + target._client.describe_db_instances.assert_called_with(Filters=[{"Name": "db-cluster-id", "Values": ["cluster"]}]) + assert target._client.describe_db_instances.call_count == 2 + assert clock[0] == _START_SEC + INSTANCE_STATUS_POLL_INTERVAL_SEC + assert target._open_connection.call_count == 2 + + +def test_make_sure_instances_up_not_available_fails_at_timeout(utility, clock): + target, _ = utility + target._client.describe_db_instances.return_value = _described_instances("rebooting") + + with pytest.raises(pytest.fail.Exception, match="instance-2 is 'rebooting'") as excinfo: + rds_test_utility.RdsTestUtility.make_sure_instances_up(target, ["instance-1", "instance-2"]) + + assert clock[0] == _START_SEC + INSTANCE_UP_TIMEOUT_SEC + target._open_connection.assert_not_called() + assert rds_test_utility.RdsTestUtility.is_cluster_outage(excinfo.value, after_failover=True) is True + + +def test_make_sure_instances_up_later_deadline_fails_at_timeout(utility, clock): + target, _ = utility + target._client.describe_db_instances.return_value = _described_instances("modifying") + + with pytest.raises(pytest.fail.Exception, match="instance-2 is 'modifying'"): + rds_test_utility.RdsTestUtility.make_sure_instances_up( + target, ["instance-2"], clock[0] + INSTANCE_UP_TIMEOUT_SEC + 100) + + assert clock[0] == _START_SEC + INSTANCE_UP_TIMEOUT_SEC + + +def test_make_sure_instances_up_status_and_connect_share_timeout(utility, clock): + target, _ = utility + target._client.describe_db_instances.side_effect = lambda **kwargs: _described_instances( + "rebooting" if clock[0] < _START_SEC + 100 else "available") + target._open_connection.side_effect = ConnectionRefusedError("starting up") + + with pytest.raises(pytest.fail.Exception, match="instance-2 did not accept a connection"): + rds_test_utility.RdsTestUtility.make_sure_instances_up(target, ["instance-2"]) + + assert clock[0] == _START_SEC + INSTANCE_UP_TIMEOUT_SEC + + +def test_make_sure_instances_up_ignores_other_instances(utility): + target, _ = utility + target._client.describe_db_instances.return_value = _described_instances("rebooting") + + rds_test_utility.RdsTestUtility.make_sure_instances_up(target, ["instance-1"]) + + assert target._client.describe_db_instances.call_count == 1 + assert target._open_connection.call_count == 1 + + +def test_make_sure_instances_up_checks_status_once_after_deadline(utility, clock): + target, _ = utility + target._client.describe_db_instances.return_value = _described_instances("rebooting") + + with pytest.raises(pytest.fail.Exception, match="instance-2 is 'rebooting'"): + rds_test_utility.RdsTestUtility.make_sure_instances_up(target, ["instance-2"], clock[0] - 1) + + assert target._client.describe_db_instances.call_count == 1 + + +def test_make_sure_instances_up_missing_instance_fails_at_once(utility, clock): + target, _ = utility + + with pytest.raises(pytest.fail.Exception, match="not in cluster .*: instance-3$") as excinfo: + rds_test_utility.RdsTestUtility.make_sure_instances_up(target, ["instance-3"]) + + assert clock[0] == _START_SEC + target._open_connection.assert_not_called() + assert rds_test_utility.RdsTestUtility.is_cluster_outage(excinfo.value, after_failover=True) is False + + +def test_make_sure_instances_up_missing_and_not_available_fails_at_once(utility, clock): + target, _ = utility + target._client.describe_db_instances.return_value = _described_instances("rebooting") + + with pytest.raises(pytest.fail.Exception, match="not in cluster .*: instance-3$") as excinfo: + rds_test_utility.RdsTestUtility.make_sure_instances_up(target, ["instance-2", "instance-3"]) + + assert clock[0] == _START_SEC + assert rds_test_utility.RdsTestUtility.is_cluster_outage(excinfo.value, after_failover=True) is False + + +def test_make_sure_instances_up_status_read_fails_at_deadline(utility, clock): + target, _ = utility + target._client.describe_db_instances.side_effect = EndpointConnectionError( + endpoint_url="https://rds.us-east-2.amazonaws.com") + + with pytest.raises(pytest.fail.Exception, match="Could not read the RDS status") as excinfo: + rds_test_utility.RdsTestUtility.make_sure_instances_up(target, ["instance-2"], clock[0] + 10) + + assert clock[0] == _START_SEC + 10 + target._open_connection.assert_not_called() + assert rds_test_utility.RdsTestUtility.is_cluster_outage(excinfo.value, after_failover=True) is False + + +def test_make_sure_instances_up_last_read_not_available_reruns(utility, clock): + target, _ = utility + target._client.describe_db_instances.side_effect = [ + EndpointConnectionError(endpoint_url="https://rds.us-east-2.amazonaws.com")] + [ + _described_instances("rebooting")] * 10 + + with pytest.raises(pytest.fail.Exception, match="did not become available") as excinfo: + rds_test_utility.RdsTestUtility.make_sure_instances_up(target, ["instance-2"], clock[0] + 10) + + assert rds_test_utility.RdsTestUtility.is_cluster_outage(excinfo.value, after_failover=True) is True + + +def test_make_sure_instances_up_last_read_failed_not_rerun(utility, clock): + target, _ = utility + target._client.describe_db_instances.side_effect = [_described_instances("rebooting")] * 5 + [ + EndpointConnectionError(endpoint_url="https://rds.us-east-2.amazonaws.com")] * 5 + + with pytest.raises(pytest.fail.Exception, match="Could not read the RDS status") as excinfo: + rds_test_utility.RdsTestUtility.make_sure_instances_up(target, ["instance-2"], clock[0] + 10) + + assert rds_test_utility.RdsTestUtility.is_cluster_outage(excinfo.value, after_failover=True) is False + + +def test_make_sure_instances_up_retries_status_after_api_error(utility): + target, _ = utility + throttled = ClientError({"Error": {"Code": "Throttling", "Message": "Rate exceeded"}}, "DescribeDBInstances") + target._client.describe_db_instances.side_effect = [throttled, _described_instances("available")] + + rds_test_utility.RdsTestUtility.make_sure_instances_up(target, ["instance-2"]) + + assert target._client.describe_db_instances.call_count == 2 + assert target._open_connection.call_count == 1 diff --git a/tests/unit/test_stale_dns_helper.py b/tests/unit/test_stale_dns_helper.py index b805b3616..a3dd4bd88 100644 --- a/tests/unit/test_stale_dns_helper.py +++ b/tests/unit/test_stale_dns_helper.py @@ -252,3 +252,15 @@ def test_notify_host_list_changed(plugin_service_mock, writer_instance): assert target._writer_host_info is None assert target._writer_host_address is None + + +def test_notify_host_list_changed__host_deleted(plugin_service_mock, writer_instance): + target = StaleDnsHelper(plugin_service_mock) + target._writer_host_info = writer_instance + target._writer_host_address = "5.5.5.5" + changes: Dict[str, Set[HostEvent]] = {writer_instance.url: {HostEvent.HOST_DELETED}} + + target.notify_host_list_changed(changes) + + assert target._writer_host_info is None + assert target._writer_host_address is None From d925ab11559e66ea3f18aebbceba7eb085e9bc87 Mon Sep 17 00:00:00 2001 From: Juan Lee Date: Wed, 18 Nov 2026 12:57:35 -0700 Subject: [PATCH 2/2] test: stop the async srw retry test from depending on timing 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. --- tests/unit/test_aio_simple_rws.py | 78 ++++++++++++++++++++----------- 1 file changed, 51 insertions(+), 27 deletions(-) diff --git a/tests/unit/test_aio_simple_rws.py b/tests/unit/test_aio_simple_rws.py index cb764cb42..36a9d7994 100644 --- a/tests/unit/test_aio_simple_rws.py +++ b/tests/unit/test_aio_simple_rws.py @@ -23,7 +23,7 @@ import asyncio from typing import Any, Optional -from unittest.mock import AsyncMock, MagicMock +from unittest.mock import AsyncMock, MagicMock, call import pytest @@ -213,43 +213,67 @@ async def _noop() -> None: # ---- Role-verification retry ---------------------------------------------- -def test_verify_retries_then_falls_back_when_role_mismatches_and_current_usable(): - """If get_host_role never matches, _verify_role exhausts retries and - _switch_to raises -- but set_read_only(True) then FALLS BACK to the - still-usable current connection (sync parity - read_write_splitting_plugin.py:209-221) rather than propagating. A - misconfigured read endpoint that resolves to a writer must not break - set_read_only(True) (test_incorrect_reader_endpoint).""" +def test_verify_retries_when_role_mismatches(): async def _body() -> None: - # Asked for a reader, but every probe says WRITER -> exhaust retries. - svc, dd = _build_plugin_service(role_returns=HostRole.WRITER) - # The budget has to outlast one slow attempt by a wide margin: the - # retry loop checks a wall-clock deadline, and at a 30ms budget a - # scheduling hiccup under the full suite left a single attempt and - # failed the await_count assertions below. - props = _base_props( - **{ - WrapperProperties.SRW_CONNECT_RETRY_TIMEOUT_MS.name: "250", - WrapperProperties.SRW_CONNECT_RETRY_INTERVAL_MS.name: "5", - } + svc, dd = _build_plugin_service() + first_writer_conn = MagicMock(name="first-writer-conn") + second_writer_conn = MagicMock(name="second-writer-conn") + reader_conn = MagicMock(name="reader-conn") + svc.connect = AsyncMock( + side_effect=[first_writer_conn, second_writer_conn, reader_conn]) + svc.get_host_role = AsyncMock( + side_effect=[HostRole.WRITER, HostRole.WRITER, HostRole.READER]) + # A budget the three attempts can't use up, so the role sequence alone + # sets the attempt count. + props = _base_props(**{ + WrapperProperties.SRW_CONNECT_RETRY_TIMEOUT_MS.name: "10000", + }) + plugin = AsyncSimpleReadWriteSplittingPlugin(svc, props) + + async def _noop() -> None: + return None + + await plugin.execute( + MagicMock(), + DbApiMethod.CONNECTION_SET_READ_ONLY.method_name, + _noop, True, ) + + assert svc.connect.await_count == 3 + assert dd.abort_connection.await_args_list == [ + call(first_writer_conn), call(second_writer_conn)] + svc.set_current_connection.assert_awaited_once_with( + reader_conn, + HostInfo(host="reader.example.com", port=5432, role=HostRole.READER)) + + asyncio.run(_body()) + + +def test_reader_switch_failure_falls_back_when_current_connection_usable(): + async def _body() -> None: + svc, dd = _build_plugin_service(role_returns=HostRole.WRITER) + writer_conn = MagicMock(name="writer-conn") + svc.connect = AsyncMock(return_value=writer_conn) + # A retry interval longer than the whole budget leaves exactly one + # attempt, however long that attempt takes. + props = _base_props(**{ + WrapperProperties.SRW_CONNECT_RETRY_TIMEOUT_MS.name: "1", + WrapperProperties.SRW_CONNECT_RETRY_INTERVAL_MS.name: "50", + }) plugin = AsyncSimpleReadWriteSplittingPlugin(svc, props) async def _noop() -> None: return None - # Must NOT raise -- the current connection is usable, so we fall back. await plugin.execute( MagicMock(), DbApiMethod.CONNECTION_SET_READ_ONLY.method_name, - _noop, True, # request reader + _noop, True, ) - # Multiple connect attempts made before giving up. - assert svc.connect.await_count >= 2 - # Each wrong-role connection was aborted. - assert dd.abort_connection.await_count >= 2 - # Stayed on the current connection -- no swap. - svc.set_current_connection.assert_not_called() + + assert svc.connect.await_count == 1 + dd.abort_connection.assert_awaited_once_with(writer_conn) + svc.set_current_connection.assert_not_awaited() asyncio.run(_body())