Repository navigation
fix: keep asyncio primitives loop-local across the library (FDE-75) - #841
Open
vishal-bala wants to merge 5 commits into
Open
vishal-bala wants to merge 5 commits into
vishal-bala wants to merge 5 commits into
Conversation
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.
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.
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.
…fix/async-index-lock-event-loop # Conflicts: # tests/unit/test_mcp/test_server.py
vishal-bala
marked this pull request as ready for review
November 24, 2026 09:34
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #841 +/- ##
==========================================
+ Coverage 80.23% 80.55% +0.32%
==========================================
Files 121 121
Lines 14862 14864 +2
Branches 2600 2599 -1
==========================================
+ Hits 11924 11974 +50
+ Misses 2219 2216 -3
+ Partials 719 674 -45
Flags with carried forward coverage won't be shown. Click here to find out more. 🚀 New features to boost your workflow:
|
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Motivation
AsyncSearchIndexandRedisVLMCPServereach built anasyncio.Lockorasyncio.Eventin__init__and held it for the object's lifetime. An asyncio primitive records the loop that first makes it wait and raisesRuntimeError: ... is bound to a different event loopwhen awaited from any other, so using one of these objects on a second loop failed instead of working. For an index, the failure needs a reconnect: the index owns its client, is disconnected, and is used again under a new loop, as in a worker that callsasyncio.run()once per job and disconnects a shared index between jobs, or a test suite with a fresh pytest-asyncio loop per test. For the MCP server, it needs a secondrun()of a stopped server, which the server explicitly supports.Only a call that actually waits checks the loop:
Lock.acquire()returns early when the lock is free, andEvent.wait()returns early when the event is set. The failure therefore needs two tasks to contend on one loop and then contend again on another, which makes it intermittent in use and invisible to a single-caller test.Changes
A loop-local holder for asyncio primitives
redisvl.utils.utils.LoopLocalwraps a factory. Itsget()returns the primitive built for the running loop and builds a fresh one whenever it is called from a different loop. These primitives only coordinate tasks within one loop, so discarding the old one when the loop changes is sufficient.Every long-lived primitive uses it
AsyncSearchIndex._lockguards lazy creation of the owned client in_get_client(), so it only matters while the index has no client: on first use, and afterdisconnect().AsyncSearchIndex._sql_executors_lockguards lazy creation of SQL executors; it was created on first use throughgetattr, but once created it lived as long as the index, so it failed the same way, and thegetattrsetup is now a single line.BaseCache._async_client_lockalready rebuilt itself per loop through a hand-rolled accessor, whichLoopLocalreplaces.RedisVLMCPServerholds_transition_lock,_request_state_lockand the_active_requests_drainedevent. The event is rebuilt already set when no request is running, soshutdown()on a new loop does not wait for requests that cannot exist._request_state_lockis never held across anawaitand so cannot be contended, but it moves toLoopLocalwith the others so that no bare primitive is left for a later edit to make contended.Regression tests
Each test runs two real loops with
asyncio.run()and races callers on both, because an uncontended version passes with or without the fix. TheAsyncSearchIndexreconnect test races two SQL queries per loop; each query fetches the client first, so the one race contends both the client lock and the SQL executor lock. The MCP test holds its requests open until both concurrentshutdown()calls are blocked, so it reaches the drained event and the transition lock, and it bounds the shutdowns with a timeout so a regression fails rather than hangs. The index and MCP tests both fail on the previous code with theRuntimeErrorabove.Notes
This covers RedisVL's own coordination primitives, not the Redis client. A
redis.asyncioclient is bound to the loop it connected on, so an index given a caller's client still cannot be moved to a new loop. What now works is the case where RedisVL owns the client and reconnects afterdisconnect().Release Notes
An
AsyncSearchIndexthat manages its own connection can now reconnect afterdisconnect()on a new event loop, such as a laterasyncio.run()or a fresh pytest-asyncio loop, and a stopped MCP server can run again on a new loop. Previously both could raiseRuntimeError: ... is bound to a different event loopwhen concurrent calls raced to connect, or when a restarted server shut down while requests were still running.Reviewer Brief
Start here:
LoopLocal.get()inredisvl/utils/utils.py:305. Every converted lock and event now comes from it, so its rule for when to rebuild decides whether each site behaves.Where it could fail
redisvl/mcp/server.py:887: the drained event is rebuilt set only when_active_requestsis 0, so if a loop is discarded withoutasyncio.run's task cleanup while requests are still counted as running (the decrement is at line 364), the next loop'sshutdown()waits forever; check the counter cannot be left non-zero.redisvl/index/index.py:3618: the SQL executor lock is held acrossawait create_async_executor(...), so it is the site most likely to be contended; check thatdisconnect()clearing_sql_executorsis what keeps a cached executor from outliving its client.Not verified: a real worker or MCP transport driven across two
asyncio.run()calls against a live Redis; the tests stand in for the client and the SQL executor. Hermetic runs were on Python 3.14 only.Beyond CI: both regression tests fail on the pre-fix code with
RuntimeError: ... is bound to a different event loop; pinning either the client lock or the SQL executor lock to one long-lived lock fails the index test; withget()rebuilding on every call, the MCP test fails in under 2 s instead of hanging.Since the last brief:
590ebb03and5e7d393amergemain. Neither changes a converted lock or event.mainadded a clusterinitialize()call to_get_client(), after the client lock is released, and changedBaseCachedisconnect ownership (#849) without touching the cache lock. The only conflict was intests/unit/test_mcp/test_server.py, where both sides had added tests; I kept both. The MCP server, connection-normalisation and utils unit tests (136) and mypy pass on5e7d393a.Reviewed
863e4dc0, fixes inc4f7c459· Claude Code (claude-opus-5-5) · lenses: correctness, security, design, tests, docs, Redis behaviourNote
Medium Risk
Changes async lifecycle and locking for client reconnect and MCP shutdown; mis-handling loop switches (e.g. drained event vs
_active_requests) could hang or race, but scope is coordination only—not auth or data paths.Overview
Fixes
RuntimeError: ... is bound to a different event loopwhen long-lived objects are reused afterdisconnect()/adisconnect()or a secondasyncio.run()(workers, pytest-asyncio, MCP stop/start).Adds
LoopLocalinredisvl.utils.utils, which rebuilds an asyncio primitive from a factory wheneverget()runs on a different loop than the one that last created it. Base cache async client creation, AsyncSearchIndex client and SQL executor locks, and MCP server transition/request locks plus the active-request drained Event now useLoopLocalinstead of a single long-lived lock or hand-rolled loop tracking.Regression tests exercise two real event loops with contended paths (cache reconnect, index SQL races, MCP shutdown with in-flight requests).
Reviewed by Cursor Bugbot for commit 5e7d393. Bugbot is set up for automated code reviews on this repo. Configure here.