Skip to content

Dustin/138 deadlock remove global mutex #139

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged

Conversation

StarpTech
Copy link
Contributor

@StarpTech StarpTech commented Apr 13, 2025

This PR addresses #138. With the previous implementation the new tests will timeout due to the deadlock with the global mutex.

Summary by CodeRabbit

  • Refactor
    • Enhanced concurrency management by implementing multiple mutexes for different resource types, improving performance during simultaneous operations.
  • Tests
    • Added comprehensive tests to identify race conditions and deadlocks, ensuring reliable performance during concurrent usage.

Copy link
Contributor

coderabbitai bot commented Apr 13, 2025

Walkthrough

The pull request refactors the concurrency control in the MCPServer by replacing a single mutex with multiple dedicated sync.RWMutex fields for different resource types (resources, prompts, tools, middleware, notification handlers, and capabilities). Related methods now lock and unlock the appropriate mutex instead of the general one. Additionally, a new test file has been introduced to validate concurrent operations, specifically checking for race conditions and deadlocks through tests such as TestRaceConditions and TestConcurrentPromptAdd, along with a helper function to orchestrate concurrent operations.

Changes

File Change Summary
server/server.go Replaced a single mutex with multiple dedicated mutexes (resourcesMu, promptsMu, toolsMu, middlewareMu, notificationHandlersMu, capabilitiesMu) in the MCPServer struct. Updated methods to lock/unlock the respective mutexes when accessing shared resources.
server/server_race_test.go Introduced a new test suite to detect race conditions and deadlocks. Added test functions (TestRaceConditions, TestConcurrentPromptAdd) and a helper (runConcurrentOperation) to execute concurrent operations and validate the absence of concurrency issues.

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8d5b20c and 8815f14.

📒 Files selected for processing (1)
  • server/server_race_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • server/server_race_test.go

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🔭 Outside diff range comments (1)
server/server_race_test.go (1)

139-182: ⚠️ Potential issue

Deadlock-specific test scenario in TestConcurrentPromptAdd.

  1. Adding a prompt from within another prompt’s handler is a classic scenario that can surface deadlocks.
  2. Using a goroutine within the handler to add a new prompt is an apt demonstration of nested concurrency.
  3. The test relies on assert.Eventually to confirm the operation completes within a timeout, preventing indefinite hang.
  4. Note that the error from srv.handleGetPrompt remains unchecked in test code (line 168).
- srv.handleGetPrompt(ctx, "123", req)
+ if _, err := srv.handleGetPrompt(ctx, "123", req); err != nil {
+   t.Errorf("handleGetPrompt error: %v", err)
+ }
🧰 Tools
🪛 golangci-lint (1.64.8)

168-168: Error return value of srv.handleGetPrompt is not checked

(errcheck)

🧹 Nitpick comments (2)
server/server_race_test.go (1)

32-33: Test duration consideration.
A 300ms duration may be enough to catch short-lived races, but occasionally concurrency issues might show up under heavier load or longer runs. Consider parameterizing this duration or increasing it if race conditions persist in CI.

server/server.go (1)

803-820: Thread-safe listing of tools in handleListTools.
Using toolsMu.RLock/RUnlock is crucial. Sorting tool names outside of the lock’s scope is acceptable for large lists, but consider carefully if there's any risk of concurrent map modifications once you release the lock.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c509bf9 and 8d5b20c.

📒 Files selected for processing (2)
  • server/server.go (18 hunks)
  • server/server_race_test.go (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
server/server_race_test.go (3)
server/server.go (7)
  • NewMCPServer (375-401)
  • WithPromptCapabilities (341-348)
  • WithToolCapabilities (351-358)
  • WithLogging (361-365)
  • WithRecovery (318-329)
  • ToolHandlerFunc (42-42)
  • WithToolHandlerMiddleware (307-315)
mcp/prompts.go (3)
  • Prompt (43-51)
  • GetPromptRequest (20-28)
  • GetPromptResult (32-37)
mcp/tools.go (4)
  • Description (175-179)
  • Tool (69-78)
  • CallToolRequest (44-59)
  • CallToolResult (34-41)
🪛 golangci-lint (1.64.8)
server/server_race_test.go

78-78: Error return value of srv.handleListTools is not checked

(errcheck)


82-82: Error return value of srv.handleListPrompts is not checked

(errcheck)


97-97: Error return value of srv.handleToolCall is not checked

(errcheck)


168-168: Error return value of srv.handleGetPrompt is not checked

(errcheck)

🔇 Additional comments (18)
server/server_race_test.go (11)

14-16: Good test documentation.
Clear explanation of the intent behind triggering race conditions. This helps future maintainers understand the purpose.


17-24: Solid approach to initializing the server with all capabilities.
This comprehensive setup ensures a broad coverage of concurrency interactions across all features.


26-30: Use of WaitGroup for concurrency is appropriate.
Combining a WaitGroup with separate goroutines is a standard concurrency pattern and should work well for this test.


36-44: Concurrent addition of prompts.
Adding prompts while simultaneously performing other operations is a key scenario for verifying concurrency safety. The usage of a unique name for each prompt is a good way to avoid collisions.


46-54: Concurrent addition of tools.
This tests a parallel path analogous to prompt addition. Looks good and consistent overall.


56-66: Concurrent deletion of tools after addition.
Exercise thorough coverage by pairing add/delete operations. This is well-structured for testing potential race conditions with ephemeral entries.


68-75: Middleware addition in a concurrent context.
Testing concurrent modifications of the toolHandlerMiddlewares slice is crucial for verifying the separate middlewareMu. Good approach.


85-91: Persistent tool addition.
A persistent tool is a helpful test fixture for ensuring repeated calls remain valid. This approach is beneficial for real concurrency checks.


100-114: Concurrent resource addition.
Ensuring multiple resource additions do not cause data races is a good stress test for the newly introduced resource locks.


116-119: Final wait and log.
No race conditions detected” logging is a clear test outcome indicator. Great finishing touch to summarize the test result.


121-137: Helper function runConcurrentOperation.
This is a clean abstraction, reducing duplication. Ensures each operation runs for the test duration, returning upon timeout.

server/server.go (7)

144-151: Introduction of dedicated RWMutex fields.
Replacing a single global mutex with specialized locks is a solid concurrency design decision, reducing contention and lowering the risk of deadlocks. Great improvement.


311-315: Proper locking in WithToolHandlerMiddleware.
By locking middlewareMu before appending to toolHandlerMiddlewares, you avoid data races and preserve concurrency safety.


408-420: Granular locking in AddResource.

  1. Locking capabilitiesMu before checking resource capabilities handles concurrency changes in capabilities.
  2. Locking resourcesMu ensures thread-safe access to the resources map.

427-439: Granular locking in AddResourceTemplate.
Similar pattern of locking for capabilities, followed by locking the resources map. This is consistent and safe.


443-453: Granular locking in AddPrompt.
This ensures safe concurrent registration of prompts and their handlers without blocking unrelated resource or tool operations.


462-476: Granular locking in AddTools.
Utilizes both capabilitiesMu and toolsMu to safely register multiple tools concurrently. Sending a broadcast notification afterward is also a nice touch.


883-885: Thread-safe notification handlers.
Applying notificationHandlersMu.RLock()/RUnlock() ensures simultaneous reads are safe. This finalizes the replacement of the global mutex with scoped locks.

@ezynda3 ezynda3 merged commit 8cdb6c6 into mark3labs:main Apr 14, 2025
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants