fix: make MCPManager singleton thread-safe with double-checked locking#813
Open
voidborne-d wants to merge 1 commit intoQwenLM:mainfrom
Open
fix: make MCPManager singleton thread-safe with double-checked locking#813voidborne-d wants to merge 1 commit intoQwenLM:mainfrom
voidborne-d wants to merge 1 commit intoQwenLM:mainfrom
Conversation
The MCPManager.__new__ method uses a singleton pattern that is not thread-safe. In multi-threaded environments (e.g., Gradio WebUI or ASGI servers), concurrent threads can both evaluate _instance is None as True, creating duplicate instances. This leads to duplicated MCP server connections, inconsistent state, or resource leaks. Fix: Add a class-level threading.Lock with double-checked locking pattern - the fast path (instance already exists) remains lock-free, while the slow path (first creation) is protected by the lock. Fixes QwenLM#812
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.
Summary
Fixes #812 — Makes the
MCPManagersingleton pattern thread-safe.Problem
The
MCPManager.__new__method uses a singleton pattern that is not thread-safe:In multi-threaded environments (e.g., when serving multiple users via Gradio WebUI or any ASGI server), two threads can both evaluate
cls._instance is NoneasTruesimultaneously, creating duplicate instances. This breaks the singleton guarantee and can lead to:Solution
Add a class-level
threading.Lockwith double-checked locking:Why double-checked locking?
threadingis already imported in the module — zero new dependenciesNote: While Python's GIL prevents true parallel execution of bytecode, the GIL can release between the
is Nonecheck andsuper().__new__()call (e.g., during I/O or C extension calls), making this race condition possible in practice.