diff --git a/redisvl/extensions/cache/base.py b/redisvl/extensions/cache/base.py index 0209b2c9..fcc8143d 100644 --- a/redisvl/extensions/cache/base.py +++ b/redisvl/extensions/cache/base.py @@ -12,7 +12,7 @@ from redisvl.redis.connection import RedisConnectionFactory from redisvl.types import AsyncRedisClient, SyncRedisClient -from redisvl.utils.utils import match_pattern +from redisvl.utils.utils import LoopLocal, match_pattern # Keys deleted per DEL when clearing. Also the SCAN count hint, so one page of # keys maps to one delete round-trip. @@ -78,10 +78,9 @@ def __init__( self._owns_async_redis_client = False self._redis_client = redis_client # Guards lazy async client creation, which suspends on an await and so - # cannot rely on a bare check-then-set. Rebuilt whenever the running - # loop changes -- see _get_async_client_lock. - self._async_client_lock: asyncio.Lock | None = None - self._async_client_lock_loop: asyncio.AbstractEventLoop | None = None + # cannot rely on a bare check-then-set. Loop-local so a reconnect + # after adisconnect() works on a new event loop. + self._async_client_lock = LoopLocal(asyncio.Lock) # Caches never close a caller-supplied client and register no GC # finalizer, so the index's owns_client handover has no cache @@ -148,24 +147,6 @@ def _get_redis_client(self) -> SyncRedisClient: ) return self._redis_client - def _get_async_client_lock(self) -> asyncio.Lock: - """Return the client-creation lock, bound to the running loop. - - An ``asyncio.Lock`` records the loop that first contends it and raises - ``RuntimeError`` if awaited from any other, so one long-lived lock - would break a reconnect that lands on a second loop -- a later - ``asyncio.run``, a fresh pytest-asyncio loop, a notebook cell. The - lock only has to serialise tasks within a single loop, so discarding - it when the loop changes is both sufficient and cheap. - """ - loop = asyncio.get_running_loop() - lock = self._async_client_lock - if lock is None or self._async_client_lock_loop is not loop: - lock = asyncio.Lock() - self._async_client_lock = lock - self._async_client_lock_loop = loop - return lock - async def _get_async_redis_client(self) -> AsyncRedisClient: """Get or create an async Redis client. @@ -174,7 +155,7 @@ async def _get_async_redis_client(self) -> AsyncRedisClient: """ client = getattr(self, "_async_redis_client", None) if client is None: - async with self._get_async_client_lock(): + async with self._async_client_lock.get(): # Double-check: another task may have created the client while # this one waited on the lock or on the factory's round trip. client = getattr(self, "_async_redis_client", None) diff --git a/redisvl/index/index.py b/redisvl/index/index.py index fe249b69..89ff42b2 100644 --- a/redisvl/index/index.py +++ b/redisvl/index/index.py @@ -43,7 +43,7 @@ to_search_result, ) from redisvl.types import AsyncRedisClient, SyncRedisClient, SyncRedisCluster -from redisvl.utils.utils import deprecated_argument, sync_wrapper +from redisvl.utils.utils import LoopLocal, deprecated_argument, sync_wrapper if TYPE_CHECKING: from redis.commands.search.aggregation import AggregateResult @@ -2537,8 +2537,12 @@ def __init__( self._redis_client = redis_client self._redis_url = redis_url self._connection_kwargs = connection_kwargs or {} - self._lock = asyncio.Lock() + # Guard lazy client and SQL executor creation, which suspend on an + # await. Loop-local so a reconnect after disconnect() works on a new + # event loop. + self._lock = LoopLocal(asyncio.Lock) self._sql_executors: dict[str, Any] = {} + self._sql_executors_lock = LoopLocal(asyncio.Lock) self._validated_client = kwargs.pop("_client_validated", False) # Must be assigned before _register_client_finalizer, which gates on @@ -2659,7 +2663,7 @@ async def _get_client(self) -> AsyncRedisClient: "Build a new index, or pass redis_url so the index can " "manage its own connection." ) - async with self._lock: + async with self._lock.get(): # Double-check to protect against concurrent access if self._redis_client is None: # Pass lib_name to connection factory @@ -3611,16 +3615,7 @@ async def _sql_query(self, sql_query: SQLQuery) -> list[dict[str, Any]]: sql_redis_options = _get_sql_redis_options(sql_query) cache_key = _sql_executor_cache_key(sql_redis_options) - sql_executors_lock = getattr(self, "_sql_executors_lock", None) - if sql_executors_lock is None: - sql_executors_lock = asyncio.Lock() - existing_sql_executors_lock = getattr(self, "_sql_executors_lock", None) - if existing_sql_executors_lock is None: - self._sql_executors_lock = sql_executors_lock - else: - sql_executors_lock = existing_sql_executors_lock - - async with sql_executors_lock: + async with self._sql_executors_lock.get(): executor = self._sql_executors.get(cache_key) if executor is None: executor = await create_async_executor(client, **sql_redis_options) diff --git a/redisvl/mcp/server.py b/redisvl/mcp/server.py index 66130920..b0424c1f 100644 --- a/redisvl/mcp/server.py +++ b/redisvl/mcp/server.py @@ -37,6 +37,7 @@ ) from redisvl.redis.connection import RedisConnectionFactory, is_version_gte from redisvl.schema import IndexSchema +from redisvl.utils.utils import LoopLocal logger = logging.getLogger(__name__) @@ -119,13 +120,16 @@ def __init__(self, settings: MCPSettings): # Lifecycle management self._lifecycle_state = _LifecycleState.INITIAL # Server lifecycle - self._transition_lock = asyncio.Lock() # Prevents overlapping startup/shutdown - self._request_state_lock = asyncio.Lock() # Guards request admission state + # The two locks and the drained event below are loop-local, so a + # server stopped on one event loop can start again on another (a + # second ``run()``, a fresh test loop). + # Prevents overlapping startup/shutdown + self._transition_lock = LoopLocal(asyncio.Lock) + # Guards request admission state + self._request_state_lock = LoopLocal(asyncio.Lock) self._active_requests = 0 - self._active_requests_drained = ( - asyncio.Event() - ) # Set when no requests are active - self._active_requests_drained.set() + # Set when no requests are active + self._active_requests_drained = LoopLocal(self._new_drained_event) self._fastmcp_lifespan = self._server_lifespan # FastMCP startup/shutdown hook # Resolve the config path to an absolute path so a later working-directory @@ -200,7 +204,7 @@ async def run_async( async def startup(self) -> None: """Load config, inspect the configured index, and initialize dependencies.""" - async with self._transition_lock: + async with self._transition_lock.get(): await self._begin_startup() try: await self._initialize_runtime_resources() @@ -217,7 +221,7 @@ async def startup(self) -> None: async def shutdown(self) -> None: """Release owned vectorizer and Redis resources.""" - async with self._transition_lock: + async with self._transition_lock.get(): if await self._begin_shutdown(): # _begin_shutdown() returns True when startup never finished or teardown already ran. return @@ -341,7 +345,7 @@ async def run_guarded( raise try: - async with self._request_state_lock: + async with self._request_state_lock.get(): if self._lifecycle_state is not _LifecycleState.RUNNING: self._close_awaitable(awaitable) raise RuntimeError("MCP server is not running") @@ -351,15 +355,15 @@ async def run_guarded( raise RuntimeError("MCP server is not running") self._active_requests += 1 - self._active_requests_drained.clear() + self._active_requests_drained.get().clear() try: return await asyncio.wait_for(awaitable, timeout=timeout_seconds) finally: - async with self._request_state_lock: + async with self._request_state_lock.get(): self._active_requests -= 1 if self._active_requests == 0: - self._active_requests_drained.set() + self._active_requests_drained.get().set() finally: semaphore.release() @@ -846,7 +850,7 @@ def _close_awaitable(awaitable: Awaitable[Any]) -> None: async def _begin_startup(self) -> None: """Move the server into STARTING or fail on invalid transitions.""" - async with self._request_state_lock: + async with self._request_state_lock.get(): if self._lifecycle_state in ( _LifecycleState.STARTING, _LifecycleState.RUNNING, @@ -856,12 +860,12 @@ async def _begin_startup(self) -> None: async def _mark_running(self) -> None: """Mark the server as fully initialized and ready to admit requests.""" - async with self._request_state_lock: + async with self._request_state_lock.get(): self._lifecycle_state = _LifecycleState.RUNNING async def _begin_shutdown(self) -> bool: """Move the server into STOPPING unless it is already stopped.""" - async with self._request_state_lock: + async with self._request_state_lock.get(): if self._lifecycle_state in ( _LifecycleState.INITIAL, _LifecycleState.STOPPED, @@ -877,12 +881,19 @@ async def _begin_shutdown(self) -> bool: async def _mark_stopped(self) -> None: """Mark the server as fully stopped.""" - async with self._request_state_lock: + async with self._request_state_lock.get(): self._lifecycle_state = _LifecycleState.STOPPED + def _new_drained_event(self) -> asyncio.Event: + """Build the drained event for a new loop, set if nothing is in flight.""" + event = asyncio.Event() + if self._active_requests == 0: + event.set() + return event + async def _wait_for_active_requests(self) -> None: """Wait for already-admitted guarded requests to finish.""" - await self._active_requests_drained.wait() + await self._active_requests_drained.get().wait() def _verify_auth_not_stale(self) -> None: """Fail closed if startup-time auth disagrees with what was wired. diff --git a/redisvl/utils/utils.py b/redisvl/utils/utils.py index 32cdcd2a..dae5d6a8 100644 --- a/redisvl/utils/utils.py +++ b/redisvl/utils/utils.py @@ -8,7 +8,7 @@ from enum import Enum from functools import wraps from time import time -from typing import Any, Callable, Coroutine, ParamSpec, Sequence, TypeVar, cast +from typing import Any, Callable, Coroutine, Generic, ParamSpec, Sequence, TypeVar, cast from warnings import warn from pydantic import BaseModel @@ -277,6 +277,40 @@ def wrapper(): return wrapper +class LoopLocal(Generic[T]): + """An asyncio primitive that is rebuilt whenever the running loop changes. + + ``asyncio.Lock``, ``Event``, ``Semaphore`` and ``Condition`` record the + loop that first makes them wait and raise ``RuntimeError`` if awaited from + any other. An object that holds one for its whole lifetime therefore + breaks as soon as it is used on a second loop -- a later ``asyncio.run`` + in a worker that starts one per job, or a fresh pytest-asyncio loop per + test. A primitive that only has to coordinate tasks within one loop can + be discarded when the loop changes, so :meth:`get` builds a fresh one + from ``factory`` whenever it is called from a loop other than the one the + current primitive was built on. + + Only a call that actually waits performs the loop check: an uncontended + ``Lock.acquire()`` or an ``Event.wait()`` on a set event returns without + it, so tests need callers that really wait. + """ + + __slots__ = ("_factory", "_value", "_loop") + + def __init__(self, factory: Callable[[], T]) -> None: + self._factory = factory + self._value: T | None = None + self._loop: asyncio.AbstractEventLoop | None = None + + def get(self) -> T: + """Return the primitive for the running loop, building it if needed.""" + loop = asyncio.get_running_loop() + if self._value is None or self._loop is not loop: + self._value = self._factory() + self._loop = loop + return self._value + + def norm_cosine_distance(value: float) -> float: """ Normalize a cosine distance to a similarity score between 0 and 1. diff --git a/tests/unit/test_connection_normalization.py b/tests/unit/test_connection_normalization.py index 1bd44fc4..feafa9b4 100644 --- a/tests/unit/test_connection_normalization.py +++ b/tests/unit/test_connection_normalization.py @@ -435,8 +435,8 @@ def test_base_cache_async_client_reconnects_on_a_second_event_loop(): An ``asyncio.Lock`` records the loop that first contends it and rejects every other, so a lock held for the cache's lifetime turned the documented reconnect into a ``RuntimeError`` whenever it landed on a new - loop -- a second ``asyncio.run``, a fresh pytest-asyncio loop, a notebook - cell. Driven from a sync test because it needs two real loops. + loop -- a second ``asyncio.run`` or a fresh pytest-asyncio loop. Driven + from a sync test because it needs two real loops. """ cache = EmbeddingsCache(redis_url="redis://localhost:6379") created = [] @@ -469,6 +469,56 @@ async def connect_then_disconnect(): assert len(created) == 2, "each loop should get exactly one client" +def test_async_search_index_reconnects_on_a_second_event_loop(): + """Reconnecting after ``disconnect`` must work on a fresh event loop. + + The locks guarding lazy client and SQL executor creation used to live for + the index's lifetime; an ``asyncio.Lock`` rejects any loop but the one + that first contended it. Two racing SQL queries per loop contend both + locks, since each query fetches the client first -- a single caller + passes either way. + """ + index = AsyncSearchIndex( + IndexSchema.from_dict(_schema_dict("async-index")), + redis_url="redis://localhost:6379", + ) + created = [] + + async def factory(*args, **kwargs): + await asyncio.sleep(0) # the suspension the real factory introduces + client = AsyncMock(name=f"client{len(created)}") + created.append(client) + return client + + async def create_async_executor(client, **kwargs): + await asyncio.sleep(0) # suspends while holding the executor lock + executor = MagicMock() + executor.execute = AsyncMock(return_value=SimpleNamespace(rows=[])) + return executor + + sql_redis = SimpleNamespace(create_async_executor=create_async_executor) + query = SQLQuery("SELECT * FROM idx") + + async def race(): + await asyncio.gather(index._sql_query(query), index._sql_query(query)) + + async def connect_then_disconnect(): + await race() + await index.disconnect() + + with ( + patch.dict("sys.modules", {"sql_redis": sql_redis}), + patch( + "redisvl.index.index.RedisConnectionFactory._get_aredis_connection", + new=factory, + ), + ): + asyncio.run(connect_then_disconnect()) + asyncio.run(race()) + + assert len(created) == 2, "each loop should get exactly one client" + + def test_sql_query_uses_connection_factory_for_redis_url(): """Build SQL query helper connections through the shared connection factory.""" fake_sql_redis_module = _fake_sql_redis_module() diff --git a/tests/unit/test_mcp/test_server.py b/tests/unit/test_mcp/test_server.py index e9918c8a..a329edec 100644 --- a/tests/unit/test_mcp/test_server.py +++ b/tests/unit/test_mcp/test_server.py @@ -480,6 +480,46 @@ async def test_shutdown_after_stop_is_idempotent(): assert server._lifecycle_state.name == "STOPPED" +def test_server_restarts_on_a_second_event_loop(): + """A server stopped on one loop must serve and stop again on another. + + Shutdown waits on the drained event while requests are in flight, and a + second concurrent shutdown waits on the transition lock; both are the + contended paths that bind an asyncio primitive to its loop. The server + supports stop/start, and a second ``run()`` brings a new loop. + """ + server = RedisVLMCPServer(_dummy_settings()) + + async def serve_then_stop(): + # What startup() leaves behind, without loading a real config. + server._semaphore = asyncio.Semaphore(2) + server.config = _startup_config() + server._lifecycle_state = server._LifecycleState.RUNNING + + release = asyncio.Event() + + async def request(): + await release.wait() + return "ok" + + requests = [ + asyncio.create_task( + server.run_guarded("test", request(), timeout_seconds=1) + ) + for _ in range(2) + ] + await asyncio.sleep(0) # admit both requests + shutdowns = [asyncio.create_task(server.shutdown()) for _ in range(2)] + await asyncio.sleep(0) # both shutdowns now block, one per primitive + release.set() + # Bounded so a lost wakeup fails the test instead of hanging the run. + await asyncio.wait_for(asyncio.gather(*shutdowns), timeout=1) + return await asyncio.gather(*requests) + + assert asyncio.run(serve_then_stop()) == ["ok", "ok"] + assert asyncio.run(serve_then_stop()) == ["ok", "ok"] + + class _SlowInfoClient: def __init__(self, info_delay: float): self.info_delay = info_delay diff --git a/tests/unit/test_utils.py b/tests/unit/test_utils.py index bf8dd29b..4de6ed93 100644 --- a/tests/unit/test_utils.py +++ b/tests/unit/test_utils.py @@ -1,3 +1,4 @@ +import asyncio import re import sys from functools import wraps @@ -13,6 +14,7 @@ make_dict, ) from redisvl.utils.utils import ( + LoopLocal, assert_no_warnings, denorm_cosine_distance, deprecated_argument, @@ -955,3 +957,28 @@ def test_keys_share_hash_tag_multiple_braces(): ) def test_match_pattern(segments, expected): assert match_pattern(*segments) == expected + + +def test_loop_local_rebuilds_its_primitive_on_a_new_loop(): + """One primitive per loop, so a contended lock never meets a foreign loop. + + The contention matters: only a lock's slow path binds it to a loop, so an + uncontended version of this test would pass on a bare ``asyncio.Lock``. + """ + holder = LoopLocal(asyncio.Lock) + + async def contend(): + lock = holder.get() + assert holder.get() is lock + + async def hold(): + async with holder.get(): + await asyncio.sleep(0) + + await asyncio.gather(hold(), hold()) + return lock + + first = asyncio.run(contend()) + second = asyncio.run(contend()) + + assert first is not second