Skip to content

fix(mcp-server): use double-checked locking to prevent race condition in _init()#170

Open
zong0728 wants to merge 1 commit intokubeflow:mainfrom
zong0728:fix/mcp-server-init-race-condition
Open

fix(mcp-server): use double-checked locking to prevent race condition in _init()#170
zong0728 wants to merge 1 commit intokubeflow:mainfrom
zong0728:fix/mcp-server-init-race-condition

Conversation

@zong0728
Copy link
Copy Markdown

@zong0728 zong0728 commented Mar 22, 2026

Fixes #169

_init() 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, wasting memory and causing non-deterministic initialisation behaviour.

Root Cause

The check-then-act on the global has no lock. Two threads arriving before the first load completes both pass the if model is None guard and each run SentenceTransformer(EMBEDDING_MODEL), doubling memory usage.

Fix

Add a module-level threading.Lock() and apply double-checked locking: fast unsynchronised check on the hot path, safe initialisation under the lock. Only one thread ever runs the constructor.

Testing

  • Single-threaded path behaviour unchanged
  • Concurrent calls can no longer double-initialise the model

Checklist

… 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 kubeflow#74

Signed-off-by: Shengzhong Guan <guan@cmu.edu>
Made-with: Cursor
@google-oss-prow
Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:
Once this PR has been reviewed and has the lgtm label, please assign franciscojavierarceo for approval. For more information see the Kubernetes Code Review Process.

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug(mcp-server): race condition in _init() allows multiple threads to initialize model and client simultaneously

1 participant