From 6d3e5b3eb1e5b3125e036a3688f9c25229f2850a Mon Sep 17 00:00:00 2001 From: AhmadMasry Date: Tue, 6 Oct 2026 23:11:09 +0300 Subject: [PATCH 1/2] fix(aio): keep host_monitoring_v2 monitors per event loop Every monitored statement ran _cleanup_idle_monitors, which stopped any monitor that wasn't is_usable(), and is_usable() was False whenever the monitor ran on a different loop from the caller's. With one event loop per thread, each loop stopped the other loops' monitors on every statement: monitors and their monitoring connections were recreated continuously, and in-flight statements on the other loop lost failure detection. Key the registry by monitor key and event loop, so each loop reuses its own monitor, and treat a monitor as unusable only when it is stopped, its task has finished, or its loop is closed. Guard the registry with a lock, as sync's monitor service does. Fixes #1287 --- .../aio/host_monitoring_plugin.py | 97 +++++++++++-------- tests/unit/test_aio_host_monitoring_plugin.py | 61 ++++++++++++ 2 files changed, 118 insertions(+), 40 deletions(-) diff --git a/aws_advanced_python_wrapper/aio/host_monitoring_plugin.py b/aws_advanced_python_wrapper/aio/host_monitoring_plugin.py index c26fc7e10..f09c537cc 100644 --- a/aws_advanced_python_wrapper/aio/host_monitoring_plugin.py +++ b/aws_advanced_python_wrapper/aio/host_monitoring_plugin.py @@ -22,7 +22,8 @@ ``plugin_service.force_connect`` and probes THAT (never the in-band application connection). Sync ref: ``HostMonitorV2.check_connection_status``. * **Shared monitors.** One monitor per ``"{time}:{interval}:{count}:{url}"`` key - is shared across every connection with the same parameters, held in a + and event loop is shared across every connection with the same parameters on + that loop, held in a module-level registry with sliding idle expiry. Sync ref: ``MonitorServiceV2.get_monitor`` + ``_CACHE_CLEANUP_NANO``. * **Execute-window-bounded monitoring.** Each network-bound execute registers a @@ -51,6 +52,7 @@ from __future__ import annotations import asyncio +import threading import time import weakref from typing import (TYPE_CHECKING, Any, Awaitable, Callable, Dict, List, @@ -97,12 +99,21 @@ # connects to an unreachable host hang without a bound, so always supply one. _DEFAULT_MONITORING_CONNECT_TIMEOUT_SEC = 10 -# Module-level shared-monitor registry, keyed "{time}:{interval}:{count}:{url}". +# Module-level shared-monitor registry, keyed by "{time}:{interval}:{count}:{url}" +# and event loop. # Holds monitors (which reference the plugin service, NOT the plugin), so a # closed connection's plugin stays collectable. Sliding-expiry disposal is # opportunistic (on next monitor request) + on host-deleted notifications + # via the single module shutdown hook. -_monitors: Dict[str, AsyncHostMonitorV2] = {} +# +# The key also holds the event loop the monitor runs on: an asyncio task only +# runs on the loop that started it, so an application with one loop per thread +# gets one monitor per loop, and a loop never stops another live loop's +# monitors (#1287). The lock guards the registry across those threads, like +# the RLock in sync's monitor service. +_RegistryKey = Tuple[str, asyncio.AbstractEventLoop] +_monitors: Dict[_RegistryKey, AsyncHostMonitorV2] = {} +_monitors_lock = threading.RLock() _shutdown_hook_registered: bool = False @@ -143,11 +154,12 @@ def _cleanup_idle_monitors() -> None: task/loop is no longer usable. Opportunistic: called on each monitor request so cleanup piggybacks on activity rather than a standing task.""" now = time.monotonic() - for key, monitor in list(_monitors.items()): - if not monitor.is_usable() or ( - monitor.can_dispose and now - monitor.last_used >= _MONITOR_EXPIRATION_SEC): - monitor.stop() - _monitors.pop(key, None) + with _monitors_lock: + for key, monitor in list(_monitors.items()): + if not monitor.is_usable() or ( + monitor.can_dispose and now - monitor.last_used >= _MONITOR_EXPIRATION_SEC): + monitor.stop() + _monitors.pop(key, None) def _get_or_create_monitor( @@ -158,34 +170,37 @@ def _get_or_create_monitor( failure_detection_interval_ms: int, failure_detection_count: int, aborted_counter: Optional[TelemetryCounter]) -> AsyncHostMonitorV2: - _cleanup_idle_monitors() key = _monitor_key( failure_detection_time_ms, failure_detection_interval_ms, failure_detection_count, host_info.url) - existing = _monitors.get(key) - if existing is not None and existing.is_usable(): - existing.touch() - return existing - if existing is not None: - # Stale (task done or bound to a closed loop): replace it. - existing.stop() - monitor = AsyncHostMonitorV2( - plugin_service, host_info, props, failure_detection_time_ms, - failure_detection_interval_ms, failure_detection_count, - aborted_counter, key) - monitor.start() - _monitors[key] = monitor - _register_shutdown_hook_once() - return monitor + registry_key = (key, asyncio.get_running_loop()) + with _monitors_lock: + _cleanup_idle_monitors() + existing = _monitors.get(registry_key) + if existing is not None and existing.is_usable(): + existing.touch() + return existing + if existing is not None: + # Stale (task done or loop closed): replace it. + existing.stop() + monitor = AsyncHostMonitorV2( + plugin_service, host_info, props, failure_detection_time_ms, + failure_detection_interval_ms, failure_detection_count, + aborted_counter, key) + monitor.start() + _monitors[registry_key] = monitor + _register_shutdown_hook_once() + return monitor def _stop_monitors_for_hosts(host_urls: Set[str]) -> None: """Stop + drop shared monitors whose host was deleted from the topology.""" - for key, monitor in list(_monitors.items()): - if monitor.host_url in host_urls: - logger.debug("HostMonitorV2.StopMonitoringThread", monitor.host) - monitor.stop() - _monitors.pop(key, None) + with _monitors_lock: + for key, monitor in list(_monitors.items()): + if monitor.host_url in host_urls: + logger.debug("HostMonitorV2.StopMonitoringThread", monitor.host) + monitor.stop() + _monitors.pop(key, None) async def _stop_all_monitors() -> None: @@ -195,9 +210,10 @@ async def _stop_all_monitors() -> None: plugin or connection. Idempotent. """ global _shutdown_hook_registered - monitors = list(_monitors.values()) - _monitors.clear() - _shutdown_hook_registered = False + with _monitors_lock: + monitors = list(_monitors.values()) + _monitors.clear() + _shutdown_hook_registered = False for monitor in monitors: monitor.stop() if monitors: @@ -212,10 +228,11 @@ def _reset_monitor_registry() -> None: creates a fresh loop), so cancelling and forgetting them is sufficient. """ global _shutdown_hook_registered - for monitor in list(_monitors.values()): - monitor.stop() - _monitors.clear() - _shutdown_hook_registered = False + with _monitors_lock: + for monitor in list(_monitors.values()): + monitor.stop() + _monitors.clear() + _shutdown_hook_registered = False class _AsyncMonitoringContext: @@ -319,12 +336,12 @@ def can_dispose(self) -> bool: return not self._active_contexts and not self._new_contexts def is_usable(self) -> bool: + # Usable from the loop that owns it; other loops get their own monitor + # (registry key), so a different running loop isn't a reason to stop + # this one (#1287). Only a closed loop is. if self._stopped or self._task is None or self._task.done(): return False - try: - return self._loop is asyncio.get_running_loop() - except RuntimeError: - return False + return self._loop is not None and not self._loop.is_closed() def stop(self) -> None: """Signal the monitor to stop (sync, fire-and-forget). The task drains diff --git a/tests/unit/test_aio_host_monitoring_plugin.py b/tests/unit/test_aio_host_monitoring_plugin.py index 34392d170..7cdc40d76 100644 --- a/tests/unit/test_aio_host_monitoring_plugin.py +++ b/tests/unit/test_aio_host_monitoring_plugin.py @@ -26,6 +26,7 @@ import asyncio import gc import socket as socket_mod +import threading import time import weakref from unittest.mock import AsyncMock, MagicMock @@ -666,3 +667,63 @@ def test_async_dialects_support_abort_connection(): assert AsyncPsycopgDriverDialect().supports_abort_connection() is True assert AsyncAiomysqlDriverDialect().supports_abort_connection() is True + + +# ---- Multiple event loops (#1287) -------------------------------------- + + +class _LoopThread: + """An event loop running forever on its own thread, like one loop per + worker thread in an application.""" + + def __init__(self) -> None: + self.loop = asyncio.new_event_loop() + self._thread = threading.Thread(target=self.loop.run_forever, daemon=True) + self._thread.start() + + def run(self, coro): + return asyncio.run_coroutine_threadsafe(coro, self.loop).result(timeout=5) + + def close(self) -> None: + self.loop.call_soon_threadsafe(self.loop.stop) + self._thread.join(timeout=5) + self.loop.close() + + +def test_event_loops_do_not_stop_each_others_monitors(): + """A statement on one loop must not stop another live loop's monitor for + the same host, and each loop keeps reusing its own monitor.""" + other = _LoopThread() + try: + p_other, svc_other, *_ = _build(grace_ms=100000) + svc_other.force_connect = AsyncMock() + + async def _body(): + p_here, svc_here, *_ = _build(grace_ms=100000) + svc_here.force_connect = AsyncMock() + seen = set() + for _ in range(3): + other.run(_execute_once(p_other)) + await _execute_once(p_here) + seen.update(id(m) for m in list(_monitors.values())) + assert len(_monitors) == 2 + assert len(seen) == 2 + assert all(not m._stopped for m in list(_monitors.values())) + + asyncio.run(_body()) + finally: + efm._reset_monitor_registry() + other.close() + + +def test_monitor_whose_loop_closed_is_replaced(): + plugin, svc, *_ = _build(grace_ms=100000) + svc.force_connect = AsyncMock() + + asyncio.run(_execute_once(plugin)) + (old,) = list(_monitors.values()) + + asyncio.run(_execute_once(plugin)) + (new,) = list(_monitors.values()) + assert new is not old + assert old._stopped is True From e7300efdf06873ad7fb1bab0e9c823dcffce5706 Mon Sep 17 00:00:00 2001 From: AhmadMasry Date: Wed, 4 Nov 2026 22:04:33 -0700 Subject: [PATCH 2/2] fix: pin the instance a cluster-endpoint connection landed on --- .../aio/aurora_connection_tracker.py | 18 ++- .../test_aio_aurora_connection_tracker.py | 134 ++++++++++++++++++ 2 files changed, 147 insertions(+), 5 deletions(-) diff --git a/aws_advanced_python_wrapper/aio/aurora_connection_tracker.py b/aws_advanced_python_wrapper/aio/aurora_connection_tracker.py index c338b574a..beb23486f 100644 --- a/aws_advanced_python_wrapper/aio/aurora_connection_tracker.py +++ b/aws_advanced_python_wrapper/aio/aurora_connection_tracker.py @@ -327,13 +327,21 @@ async def _pin_current_writer(self, host_info: HostInfo, conn: Any) -> None: # missed invalidation entirely). Ground truth is a live is_reader # probe of THIS connection: if it says WRITER, pin the # connection's own host over whatever topology claimed. + # + # ``host_info`` is the host the connection landed on, resolved by + # _identify_connection_host, NOT plugin_service.current_host_info: + # this runs inside the connect pipeline, before the wrapper takes + # the routed host (aio/wrapper.py take_routed_host_info), so the + # service still reports the endpoint the caller dialled. Pinning + # a cluster endpoint there made the first execute compare it with + # the topology writer (an instance), read that as a writer change + # and invalidate the connection about to run its statement + # (#1276). role = await self._plugin_service.get_host_role(conn) if role == HostRole.WRITER: - host = self._plugin_service.current_host_info - if host is not None and ( - self._current_writer is None - or not self._same_host(host, self._current_writer)): - self._current_writer = host + if (self._current_writer is None + or not self._same_host(host_info, self._current_writer)): + self._current_writer = host_info except Exception: # noqa: BLE001 - writer pinning is best-effort pass diff --git a/tests/unit/test_aio_aurora_connection_tracker.py b/tests/unit/test_aio_aurora_connection_tracker.py index 5b31e9397..563ae1c23 100644 --- a/tests/unit/test_aio_aurora_connection_tracker.py +++ b/tests/unit/test_aio_aurora_connection_tracker.py @@ -1026,3 +1026,137 @@ async def _raising(): assert plugin._current_writer.host == new_writer.host asyncio.run(_run()) + + +def test_cluster_endpoint_connection_survives_its_first_execute(): + """Issue #1276: the connect-time live-probe pin used + ``current_host_info``, which for a cluster-endpoint connection is the + cluster endpoint. The first execute compared that pin against the + topology writer (an instance endpoint), saw a writer change, and + ``invalidate_all`` closed the connection about to run its statement.""" + plugin, svc, driver_dialect, tracker = _build() + cluster = "mydb.cluster-xyz.us-east-1.rds.amazonaws.com" + instance = "inst-1.xyz.us-east-1.rds.amazonaws.com" + writer = HostInfo(host=instance, port=5432, role=HostRole.WRITER) + + async def _refresh(*a, **k): + svc._all_hosts = (writer,) + svc.refresh_host_list = AsyncMock(side_effect=_refresh) + svc.identify_connection = AsyncMock( + return_value=HostInfo(host=instance, port=5432)) + svc.get_host_role = AsyncMock(return_value=HostRole.WRITER) + + conn = _plain_conn("conn") + + async def _connect_func(): + return conn + + async def _run(): + svc._current_host_info = HostInfo(host=cluster, port=5432) + await plugin.connect( + target_driver_func=MagicMock(), driver_dialect=driver_dialect, + host_info=HostInfo(host=cluster, port=5432), props=svc.props, + is_initial_connection=True, connect_func=_connect_func) + assert plugin._current_writer is not None + assert plugin._current_writer.host == instance + + result = await plugin.execute( + MagicMock(), "Cursor.execute", AsyncMock(return_value="ok")) + assert result == "ok" + conn.close.assert_not_called() + + asyncio.run(_run()) + + +async def _connect_via(plugin, svc, driver_dialect, endpoint, conn): + """Connect through the plugin and then adopt the routed host, the way + AsyncAwsWrapperConnection does once the connect pipeline returns + (aio/wrapper.py, take_routed_host_info).""" + async def _connect_func(): + return conn + + host_info = HostInfo(host=endpoint, port=5432) + svc._current_host_info = host_info + svc.routed_host_info = None + result = await plugin.connect( + target_driver_func=MagicMock(), driver_dialect=driver_dialect, + host_info=host_info, props=svc.props, + is_initial_connection=True, connect_func=_connect_func) + routed = svc.routed_host_info + if routed is not None: + svc._current_host_info = routed + svc.routed_host_info = None + return result + + +def test_failover_invalidates_departed_instance_of_cluster_endpoint_connection(): + """A cluster-endpoint connection departs the INSTANCE it landed on, not + the cluster endpoint. With topology still lagged (old writer named), the + departed-host path must resolve the cluster endpoint to that instance so + idle connections to the demoted writer are closed.""" + plugin, svc, driver_dialect, tracker = _build() + cluster = "mydb.cluster-xyz.us-east-1.rds.amazonaws.com" + old = "inst-1.xyz.us-east-1.rds.amazonaws.com" + new = "inst-2.xyz.us-east-1.rds.amazonaws.com" + lagged = (HostInfo(old, 5432, role=HostRole.WRITER), + HostInfo(new, 5432, role=HostRole.READER)) + + async def _refresh(*a, **k): + svc._all_hosts = lagged + svc.refresh_host_list = AsyncMock(side_effect=_refresh) + svc.force_refresh_host_list = AsyncMock(side_effect=_refresh) + svc.identify_connection = AsyncMock(return_value=HostInfo(old, 5432)) + svc.get_host_role = AsyncMock(return_value=HostRole.WRITER) + + idle_conn = _plain_conn("idle") + active_conn = _plain_conn("active") + + async def _run(): + await _connect_via(plugin, svc, driver_dialect, cluster, idle_conn) + await _connect_via(plugin, svc, driver_dialect, cluster, active_conn) + + async def _raising(): + svc._current_host_info = HostInfo(new, 5432, role=HostRole.WRITER) + raise FailoverSuccessError("failover") + with pytest.raises(FailoverSuccessError): + await plugin.execute(MagicMock(), "Cursor.execute", _raising) + idle_conn.close.assert_called() + + asyncio.run(_run()) + + +def test_reader_endpoint_failover_does_not_invalidate_the_writer(): + """A reader-endpoint connection that fails over between readers departs + a reader, so writer connections must survive.""" + plugin, svc, driver_dialect, tracker = _build() + reader_ep = "mydb.cluster-ro-xyz.us-east-1.rds.amazonaws.com" + writer = "inst-1.xyz.us-east-1.rds.amazonaws.com" + reader_1 = "inst-2.xyz.us-east-1.rds.amazonaws.com" + reader_2 = "inst-3.xyz.us-east-1.rds.amazonaws.com" + topology = (HostInfo(writer, 5432, role=HostRole.WRITER), + HostInfo(reader_1, 5432, role=HostRole.READER), + HostInfo(reader_2, 5432, role=HostRole.READER)) + + async def _refresh(*a, **k): + svc._all_hosts = topology + svc.refresh_host_list = AsyncMock(side_effect=_refresh) + svc.force_refresh_host_list = AsyncMock(side_effect=_refresh) + svc.identify_connection = AsyncMock(return_value=HostInfo(reader_1, 5432)) + svc.get_host_role = AsyncMock(return_value=HostRole.READER) + + writer_conn = _plain_conn("writer") + reader_conn = _plain_conn("reader") + + async def _run(): + tracker.track(HostInfo(writer, 5432), writer_conn) + await _connect_via(plugin, svc, driver_dialect, reader_ep, reader_conn) + assert plugin._current_writer.host == writer + + async def _raising(): + svc._current_host_info = HostInfo(reader_2, 5432, role=HostRole.READER) + raise FailoverSuccessError("failover") + with pytest.raises(FailoverSuccessError): + await plugin.execute(MagicMock(), "Cursor.execute", _raising) + writer_conn.close.assert_not_called() + + asyncio.run(_run())