Skip to content

Fix: <asyncio.locks.Semaphore object at 0xabcd [locked]> is bound to a different event loop - #15100

Merged
wangq8 merged 1 commit into
infiniflow:mainfrom
wangq8:bugfix/fix-asyncio-close-in-another-loop
May 21, 2026
Merged

wangq8 merged 1 commit into
infiniflow:mainfrom
wangq8:bugfix/fix-asyncio-close-in-another-loop

Conversation

@wangq8

@wangq8 wangq8 commented May 21, 2026

Copy link
Copy Markdown
Collaborator

Fix: <asyncio.locks.Semaphore object at 0xabcd [locked]> is bound to a different event loop

@coderabbitai

coderabbitai Bot commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: debe40df-d7af-490c-b7c2-c781b280ace7

📥 Commits

Reviewing files that changed from the base of the PR and between a252bb1 and d6dd593.

📒 Files selected for processing (3)
  • common/asyncio_utils.py
  • rag/graphrag/utils.py
  • rag/svr/task_executor.py

📝 Walkthrough

Walkthrough

This PR introduces LoopLocalSemaphore, an asyncio synchronization utility that caches semaphore instances per event loop using weak references, and integrates it to replace fixed semaphore instances in chat and task executor modules for safer multi-loop concurrency control.

Changes

Loop-Local Semaphore Implementation and Integration

Layer / File(s) Summary
LoopLocalSemaphore Class Definition
common/asyncio_utils.py
New module defines LoopLocalSemaphore with WeakKeyDictionary storage keyed by the running event loop. _get() lazily creates semaphores per loop and removes entries for closed loops. Exposes acquire() (async), release() (sync), and async context manager (__aenter__/__aexit__) that acquires on entry and releases on exit.
Chat Limiter Loop-Local Integration
rag/graphrag/utils.py
Imports LoopLocalSemaphore and replaces chat_limiter from asyncio.Semaphore(MAX_CONCURRENT_CHATS) to LoopLocalSemaphore(MAX_CONCURRENT_CHATS) to handle multi-loop chat scenarios safely.
Task Executor Loop-Local Limiters
rag/svr/task_executor.py
Imports LoopLocalSemaphore and replaces five concurrency limiters (task_limiter, chunk_limiter, embed_limiter, minio_limiter, kg_limiter) from asyncio.Semaphore to LoopLocalSemaphore, preserving all environment-driven limit values for chunk building, embedding, MinIO, and KG operations.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Suggested reviewers

  • Lynn-Inf

Poem

🐰 A Loop-Local Tale

Semaphores dance through event loops,
WeakKeyDict keeps them in hoops—
Per-thread they flourish, one at a time,
Chat and tasks sync in perfect rhyme! ✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is incomplete—it only repeats the title without explaining the problem, solution, or change type as required by the template. Expand the description to include: (1) What problem does this PR solve (background context), (2) Type of change checkbox selection (Bug Fix, New Feature, etc.).
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: fixing an asyncio Semaphore event loop binding issue by implementing LoopLocalSemaphore.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@wangq8 wangq8 added the ci Continue Integration label May 21, 2026
@wangq8
wangq8 marked this pull request as ready for review May 21, 2026 07:56
@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label May 21, 2026
@wangq8

wangq8 commented May 21, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai

@coderabbitai

coderabbitai Bot commented May 21, 2026

Copy link
Copy Markdown
Contributor

@wangq8 It looks like you tagged me without a specific request. I'll go ahead and review the PR for you!

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@common/asyncio_utils.py`:
- Around line 33-42: Update the _get method in asyncio_utils.py to emit debug
logs for the semaphore lifecycle: log a debug message when you prune closed
event loop entries from self._semaphores (including which loop object was
removed) and log a debug message when you create a new per-loop semaphore
(including the loop and semaphore value). Use the module logger used elsewhere
in this file (e.g., logger = logging.getLogger(__name__)) to emit these messages
from the _get function so the actions are visible in debug traces.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: db38f9a7-8e79-4321-9819-5c894dce2a3f

📥 Commits

Reviewing files that changed from the base of the PR and between 111cdc7 and c5d6316.

📒 Files selected for processing (3)
  • common/asyncio_utils.py
  • rag/graphrag/utils.py
  • rag/svr/task_executor.py

Comment thread common/asyncio_utils.py
Comment on lines +33 to +42
def _get(self) -> asyncio.Semaphore:
loop = asyncio.get_running_loop()
for cached_loop in list(self._semaphores):
if cached_loop.is_closed():
self._semaphores.pop(cached_loop, None)
sem = self._semaphores.get(loop)
if sem is None:
sem = asyncio.Semaphore(self._value)
self._semaphores[loop] = sem
return sem

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Add debug logging for semaphore lifecycle in the new loop-local flow.

Please emit debug logs when closed-loop entries are pruned and when a new per-loop semaphore is created.

Proposed patch
 import asyncio
+import logging
 import weakref
 
+logger = logging.getLogger(__name__)
+
 
 class LoopLocalSemaphore:
@@
     def _get(self) -> asyncio.Semaphore:
         loop = asyncio.get_running_loop()
         for cached_loop in list(self._semaphores):
             if cached_loop.is_closed():
                 self._semaphores.pop(cached_loop, None)
+                logger.debug("LoopLocalSemaphore pruned closed loop: loop_id=%s", id(cached_loop))
         sem = self._semaphores.get(loop)
         if sem is None:
             sem = asyncio.Semaphore(self._value)
             self._semaphores[loop] = sem
+            logger.debug("LoopLocalSemaphore created semaphore: loop_id=%s value=%d", id(loop), self._value)
         return sem

As per coding guidelines, **/*.py: Add logging for new flows.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def _get(self) -> asyncio.Semaphore:
loop = asyncio.get_running_loop()
for cached_loop in list(self._semaphores):
if cached_loop.is_closed():
self._semaphores.pop(cached_loop, None)
sem = self._semaphores.get(loop)
if sem is None:
sem = asyncio.Semaphore(self._value)
self._semaphores[loop] = sem
return sem
import asyncio
import logging
import weakref
logger = logging.getLogger(__name__)
class LoopLocalSemaphore:
def _get(self) -> asyncio.Semaphore:
loop = asyncio.get_running_loop()
for cached_loop in list(self._semaphores):
if cached_loop.is_closed():
self._semaphores.pop(cached_loop, None)
logger.debug("LoopLocalSemaphore pruned closed loop: loop_id=%s", id(cached_loop))
sem = self._semaphores.get(loop)
if sem is None:
sem = asyncio.Semaphore(self._value)
self._semaphores[loop] = sem
logger.debug("LoopLocalSemaphore created semaphore: loop_id=%s value=%d", id(loop), self._value)
return sem
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@common/asyncio_utils.py` around lines 33 - 42, Update the _get method in
asyncio_utils.py to emit debug logs for the semaphore lifecycle: log a debug
message when you prune closed event loop entries from self._semaphores
(including which loop object was removed) and log a debug message when you
create a new per-loop semaphore (including the loop and semaphore value). Use
the module logger used elsewhere in this file (e.g., logger =
logging.getLogger(__name__)) to emit these messages from the _get function so
the actions are visible in debug traces.

@wangq8 wangq8 closed this May 21, 2026
@wangq8
wangq8 force-pushed the bugfix/fix-asyncio-close-in-another-loop branch from a252bb1 to 440153c Compare May 21, 2026 10:48
@dosubot dosubot Bot added size:XS This PR changes 0-9 lines, ignoring generated files. and removed size:M This PR changes 30-99 lines, ignoring generated files. labels May 21, 2026
@wangq8 wangq8 reopened this May 21, 2026
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:XS This PR changes 0-9 lines, ignoring generated files. labels May 21, 2026
@codecov

codecov Bot commented May 21, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.12%. Comparing base (440153c) to head (d6dd593).
⚠️ Report is 19 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15100   +/-   ##
=======================================
  Coverage   93.12%   93.12%           
=======================================
  Files          10       10           
  Lines         713      713           
  Branches      116      116           
=======================================
  Hits          664      664           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@wangq8
wangq8 merged commit c5a46fd into infiniflow:main May 21, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant