Skip to content

fix: keep asyncio primitives loop-local across the library (FDE-75) - #841

Open
vishal-bala wants to merge 5 commits into
mainfrom
fix/async-index-lock-event-loop
Open

vishal-bala wants to merge 5 commits into
mainfrom
fix/async-index-lock-event-loop

Conversation

@vishal-bala

@vishal-bala vishal-bala commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

Motivation

AsyncSearchIndex and RedisVLMCPServer each built an asyncio.Lock or asyncio.Event in __init__ and held it for the object's lifetime. An asyncio primitive records the loop that first makes it wait and raises RuntimeError: ... is bound to a different event loop when 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 calls asyncio.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 second run() 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, and Event.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.LoopLocal wraps a factory. Its get() 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.

# before
self._lock = asyncio.Lock()
async with self._lock: ...

# after
self._lock = LoopLocal(asyncio.Lock)
async with self._lock.get(): ...

Every long-lived primitive uses it

AsyncSearchIndex._lock guards lazy creation of the owned client in _get_client(), so it only matters while the index has no client: on first use, and after disconnect(). AsyncSearchIndex._sql_executors_lock guards lazy creation of SQL executors; it was created on first use through getattr, but once created it lived as long as the index, so it failed the same way, and the getattr setup is now a single line. BaseCache._async_client_lock already rebuilt itself per loop through a hand-rolled accessor, which LoopLocal replaces.

RedisVLMCPServer holds _transition_lock, _request_state_lock and the _active_requests_drained event. The event is rebuilt already set when no request is running, so shutdown() on a new loop does not wait for requests that cannot exist. _request_state_lock is never held across an await and so cannot be contended, but it moves to LoopLocal with 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. The AsyncSearchIndex reconnect 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 concurrent shutdown() 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 the RuntimeError above.

Notes

This covers RedisVL's own coordination primitives, not the Redis client. A redis.asyncio client 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 after disconnect().

Release Notes

An AsyncSearchIndex that manages its own connection can now reconnect after disconnect() on a new event loop, such as a later asyncio.run() or a fresh pytest-asyncio loop, and a stopped MCP server can run again on a new loop. Previously both could raise RuntimeError: ... is bound to a different event loop when concurrent calls raced to connect, or when a restarted server shut down while requests were still running.

Reviewer Brief

Start here: LoopLocal.get() in redisvl/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_requests is 0, so if a loop is discarded without asyncio.run's task cleanup while requests are still counted as running (the decrement is at line 364), the next loop's shutdown() waits forever; check the counter cannot be left non-zero.
  • redisvl/index/index.py:3618: the SQL executor lock is held across await create_async_executor(...), so it is the site most likely to be contended; check that disconnect() clearing _sql_executors is 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; with get() rebuilding on every call, the MCP test fails in under 2 s instead of hanging.

Since the last brief: 590ebb03 and 5e7d393a merge main. Neither changes a converted lock or event. main added a cluster initialize() call to _get_client(), after the client lock is released, and changed BaseCache disconnect ownership (#849) without touching the cache lock. The only conflict was in tests/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 on 5e7d393a.

Reviewed 863e4dc0, fixes in c4f7c459 · Claude Code (claude-opus-5-5) · lenses: correctness, security, design, tests, docs, Redis behaviour


Note

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 loop when long-lived objects are reused after disconnect() / adisconnect() or a second asyncio.run() (workers, pytest-asyncio, MCP stop/start).

Adds LoopLocal in redisvl.utils.utils, which rebuilds an asyncio primitive from a factory whenever get() 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 use LoopLocal instead 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.

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.
@vishal-bala vishal-bala added the auto:minor Increment the minor version when merged label Nov 19, 2026
…fix/async-index-lock-event-loop

# Conflicts:
#	tests/unit/test_mcp/test_server.py
@vishal-bala
vishal-bala marked this pull request as ready for review November 24, 2026 09:34
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-24T09:36:19.996401Z 5e7d393 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@codecov-commenter

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 80.55%. Comparing base (84c6188) to head (5e7d393).

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     
Flag Coverage Δ
core 79.23% <100.00%> (+0.04%) ⬆️
service 79.91% <100.00%> (+0.04%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

auto:minor Increment the minor version when merged

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants