From 34b76570060fa15ebe326b8f59f24864ac3bad22 Mon Sep 17 00:00:00 2001 From: Vishal Bala Date: Fri, 2 Oct 2026 14:57:44 +0200 Subject: [PATCH 1/3] fix: keep asyncio primitives loop-local across the library asyncio.Lock, Event, Semaphore and Condition record the loop that first makes them wait and raise RuntimeError if awaited from any other. Several objects built one in __init__ and held it for their lifetime, so using them on a second loop -- another asyncio.run, a fresh pytest-asyncio loop, a notebook cell, a reconnect after disconnect(), a second MCP server run() -- failed instead of working. Add LoopLocal, which rebuilds its primitive when the running loop changes, and use it at every such site: - AsyncSearchIndex._lock (lazy client creation) - AsyncSearchIndex._sql_executors_lock (lazy SQL executor creation), replacing a getattr-based lazy init that had the same flaw - BaseCache._async_client_lock, replacing its hand-rolled accessor - RedisVLMCPServer._transition_lock, _request_state_lock and _active_requests_drained; the event is rebuilt set when no request is in flight Only the contended path checks the loop, so each regression test races callers on two loops; an uncontended version passes either way. --- redisvl/extensions/cache/base.py | 29 +++----------- redisvl/index/index.py | 20 ++++------ redisvl/mcp/server.py | 44 +++++++++++++-------- redisvl/utils/utils.py | 34 +++++++++++++++- tests/unit/test_connection_normalization.py | 37 +++++++++++++++++ tests/unit/test_mcp/test_server.py | 39 ++++++++++++++++++ tests/unit/test_utils.py | 27 +++++++++++++ 7 files changed, 175 insertions(+), 55 deletions(-) diff --git a/redisvl/extensions/cache/base.py b/redisvl/extensions/cache/base.py index 872e789dc..67eca11f2 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. @@ -77,10 +77,9 @@ def __init__( self._async_redis_client = async_redis_client 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 the cache + # survives a change of 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 @@ -147,24 +146,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. @@ -173,7 +154,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 6a2451fcb..a62f4b765 100644 --- a/redisvl/index/index.py +++ b/redisvl/index/index.py @@ -42,7 +42,7 @@ make_dict, ) 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 @@ -2497,8 +2497,11 @@ 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 the index survives a change of 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 @@ -2619,7 +2622,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 @@ -3550,16 +3553,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 4568482ce..2452d3e03 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,15 @@ 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 + # 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 +203,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 +220,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 +344,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 +354,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 +849,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 +859,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 +880,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 0e0ec28de..b0c1f0681 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,38 @@ 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``, + a fresh pytest-asyncio loop, a notebook cell. 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 the contended path performs the loop check, so code that never + waits on the primitive will not show the bug; test with racing callers. + """ + + __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 71b893cf5..0c51abd16 100644 --- a/tests/unit/test_connection_normalization.py +++ b/tests/unit/test_connection_normalization.py @@ -467,6 +467,43 @@ 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 lock guarding lazy client creation used to live for the index's + lifetime; an ``asyncio.Lock`` rejects any loop but the one that first + contended it. Two racing callers per loop force the lock's slow path, + the only one that checks the loop -- 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 race(): + await asyncio.gather(index._get_client(), index._get_client()) + + async def connect_then_disconnect(): + await race() + await index.disconnect() + + with 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 394ffe656..b38140e69 100644 --- a/tests/unit/test_mcp/test_server.py +++ b/tests/unit/test_mcp/test_server.py @@ -478,3 +478,42 @@ async def test_shutdown_after_stop_is_idempotent(): await server.shutdown() 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() + await asyncio.gather(*shutdowns) + return await asyncio.gather(*requests) + + assert asyncio.run(serve_then_stop()) == ["ok", "ok"] + assert asyncio.run(serve_then_stop()) == ["ok", "ok"] diff --git a/tests/unit/test_utils.py b/tests/unit/test_utils.py index e0754c81f..c3367492f 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, @@ -946,3 +948,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 From 863e4dc0a889126bd6a2f3ea04168b5021a41abd Mon Sep 17 00:00:00 2001 From: Vishal Bala Date: Tue, 3 Nov 2026 09:56:59 +0100 Subject: [PATCH 2/3] docs: drop the notebook example from the loop-binding explanations Notebook cells share the kernel's single event loop, so a notebook does not move an object to a new loop on its own. Name the cases that do: a worker that starts an asyncio.run per job, and a fresh pytest-asyncio loop per test. --- redisvl/utils/utils.py | 11 ++++++----- tests/unit/test_connection_normalization.py | 4 ++-- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/redisvl/utils/utils.py b/redisvl/utils/utils.py index b0c1f0681..e60425467 100644 --- a/redisvl/utils/utils.py +++ b/redisvl/utils/utils.py @@ -283,11 +283,12 @@ class LoopLocal(Generic[T]): ``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``, - a fresh pytest-asyncio loop, a notebook cell. 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. + 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 the contended path performs the loop check, so code that never waits on the primitive will not show the bug; test with racing callers. diff --git a/tests/unit/test_connection_normalization.py b/tests/unit/test_connection_normalization.py index 0c51abd16..30c8279c8 100644 --- a/tests/unit/test_connection_normalization.py +++ b/tests/unit/test_connection_normalization.py @@ -433,8 +433,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 = [] From c4f7c4592c4386f09c7b29513169a8424192dc30 Mon Sep 17 00:00:00 2001 From: Vishal Bala Date: Tue, 3 Nov 2026 10:11:05 +0100 Subject: [PATCH 3/3] test: cover the SQL executor lock and bound the MCP restart test Pre-PR review fixes. The index reconnect test now races two SQL queries per loop instead of two bare client fetches. Each query fetches the client first, so the race contends both the client lock and the SQL executor lock, which no test covered before: pinning either to one long-lived lock now fails it. The MCP restart test bounds its shutdowns with a one-second timeout, so a lost wakeup on the drained event fails the test instead of hanging the run. Comments no longer say the index and cache survive any change of event loop; what works is a reconnect after disconnect() or adisconnect(). The LoopLocal docstring now says the loop check runs on any call that actually waits, which is the accurate rule for Event and Condition. --- redisvl/extensions/cache/base.py | 4 +-- redisvl/index/index.py | 3 ++- redisvl/mcp/server.py | 5 ++-- redisvl/utils/utils.py | 5 ++-- tests/unit/test_connection_normalization.py | 29 +++++++++++++++------ tests/unit/test_mcp/test_server.py | 3 ++- 6 files changed, 33 insertions(+), 16 deletions(-) diff --git a/redisvl/extensions/cache/base.py b/redisvl/extensions/cache/base.py index 67eca11f2..c14ae0c9d 100644 --- a/redisvl/extensions/cache/base.py +++ b/redisvl/extensions/cache/base.py @@ -77,8 +77,8 @@ def __init__( self._async_redis_client = async_redis_client 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. Loop-local so the cache - # survives a change of event loop. + # 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 diff --git a/redisvl/index/index.py b/redisvl/index/index.py index a62f4b765..798e942ef 100644 --- a/redisvl/index/index.py +++ b/redisvl/index/index.py @@ -2498,7 +2498,8 @@ def __init__( self._redis_url = redis_url self._connection_kwargs = connection_kwargs or {} # Guard lazy client and SQL executor creation, which suspend on an - # await. Loop-local so the index survives a change of event loop. + # 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) diff --git a/redisvl/mcp/server.py b/redisvl/mcp/server.py index 2452d3e03..cc330d31a 100644 --- a/redisvl/mcp/server.py +++ b/redisvl/mcp/server.py @@ -120,8 +120,9 @@ def __init__(self, settings: MCPSettings): # Lifecycle management self._lifecycle_state = _LifecycleState.INITIAL # Server lifecycle - # Loop-local, so a server stopped on one event loop can start again - # on another (a second ``run()``, a fresh test loop). + # 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 diff --git a/redisvl/utils/utils.py b/redisvl/utils/utils.py index e60425467..a77de4ddd 100644 --- a/redisvl/utils/utils.py +++ b/redisvl/utils/utils.py @@ -290,8 +290,9 @@ class LoopLocal(Generic[T]): from ``factory`` whenever it is called from a loop other than the one the current primitive was built on. - Only the contended path performs the loop check, so code that never - waits on the primitive will not show the bug; test with racing callers. + 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") diff --git a/tests/unit/test_connection_normalization.py b/tests/unit/test_connection_normalization.py index 30c8279c8..766e591a7 100644 --- a/tests/unit/test_connection_normalization.py +++ b/tests/unit/test_connection_normalization.py @@ -470,10 +470,11 @@ async def connect_then_disconnect(): def test_async_search_index_reconnects_on_a_second_event_loop(): """Reconnecting after ``disconnect`` must work on a fresh event loop. - The lock guarding lazy client creation used to live for the index's - lifetime; an ``asyncio.Lock`` rejects any loop but the one that first - contended it. Two racing callers per loop force the lock's slow path, - the only one that checks the loop -- a single caller passes either way. + 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")), @@ -487,16 +488,28 @@ async def factory(*args, **kwargs): 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._get_client(), index._get_client()) + await asyncio.gather(index._sql_query(query), index._sql_query(query)) async def connect_then_disconnect(): await race() await index.disconnect() - with patch( - "redisvl.index.index.RedisConnectionFactory._get_aredis_connection", - new=factory, + 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()) diff --git a/tests/unit/test_mcp/test_server.py b/tests/unit/test_mcp/test_server.py index b38140e69..ccc151571 100644 --- a/tests/unit/test_mcp/test_server.py +++ b/tests/unit/test_mcp/test_server.py @@ -512,7 +512,8 @@ async def request(): shutdowns = [asyncio.create_task(server.shutdown()) for _ in range(2)] await asyncio.sleep(0) # both shutdowns now block, one per primitive release.set() - await asyncio.gather(*shutdowns) + # 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"]