From 835a14d9f9fe158b4b8ab9af1ed8fbfb67541103 Mon Sep 17 00:00:00 2001 From: Shengzhong Guan Date: Sun, 22 Mar 2026 15:40:16 -0400 Subject: [PATCH] fix(mcp-server): use double-checked locking to prevent race condition in _init() _init() previously checked 'if model is None' without any synchronisation. Under concurrent tool calls, multiple threads could observe model as None simultaneously and each create a separate SentenceTransformer instance, wasting memory and causing non-deterministic initialisation behaviour. Add a module-level threading.Lock() and apply the double-checked locking pattern: a fast unsynchronised check avoids lock contention on the hot path, while the inner check under the lock guarantees only one thread performs the actual initialisation. Closes #74 Signed-off-by: Shengzhong Guan Made-with: Cursor --- kagent-feast-mcp/mcp-server/server.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/kagent-feast-mcp/mcp-server/server.py b/kagent-feast-mcp/mcp-server/server.py index 44a9fcb..c0d5d8b 100644 --- a/kagent-feast-mcp/mcp-server/server.py +++ b/kagent-feast-mcp/mcp-server/server.py @@ -1,3 +1,5 @@ +import threading + from fastmcp import FastMCP from pymilvus import MilvusClient from sentence_transformers import SentenceTransformer @@ -13,14 +15,18 @@ model: SentenceTransformer = None client: MilvusClient = None +_init_lock = threading.Lock() def _init(): + """Initialize model and client using double-checked locking to prevent race conditions.""" global model, client - if model is None: - model = SentenceTransformer(EMBEDDING_MODEL) - if client is None: - client = MilvusClient(uri=MILVUS_URI, user=MILVUS_USER, password=MILVUS_PASSWORD) + if model is None or client is None: + with _init_lock: + if model is None: + model = SentenceTransformer(EMBEDDING_MODEL) + if client is None: + client = MilvusClient(uri=MILVUS_URI, user=MILVUS_USER, password=MILVUS_PASSWORD) @mcp.tool()