Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions aws_advanced_python_wrapper/aio/aurora_connection_tracker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
97 changes: 57 additions & 40 deletions aws_advanced_python_wrapper/aio/host_monitoring_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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(
Expand All @@ -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:
Expand All @@ -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:
Expand All @@ -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:
Expand Down Expand Up @@ -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
Expand Down
134 changes: 134 additions & 0 deletions tests/unit/test_aio_aurora_connection_tracker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Loading
Loading