Skip to content

fix: add mutex to SSEServer to avoid data race between Start and Shutdown; fix test error on Windows (#166 #172) #170

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
merged 5 commits into from
Apr 19, 2025

Conversation

Wood-Q
Copy link
Contributor

@Wood-Q Wood-Q commented Apr 18, 2025

What this PR does

  1. This PR fixes a data race issue between SSEServer.Start and SSEServer.Shutdown by adding a sync.RWMutex to the SSEServer struct.
  2. Fix test error on Windows
  • Start uses mu.Lock when setting s.srv
  • Shutdown uses mu.RLock when accessing s.srv
  • Add '.exe' to mockServerPath

Related Issue

Closes #166
Closes #172

Summary by CodeRabbit

Summary by CodeRabbit

  • Bug Fixes
    • Improved server shutdown reliability by ensuring all active sessions are properly closed.
    • Enhanced thread safety to prevent potential issues during server start and shutdown.
    • Fixed test compatibility for Windows by correctly handling mock server executable filenames.

Copy link
Contributor

coderabbitai bot commented Apr 18, 2025

"""

Walkthrough

This change introduces a read-write mutex to the SSEServer struct in server/sse.go to ensure thread-safe access to the internal HTTP server instance and the sessions map. The mutex is used in the Start, Shutdown, and handleMessage methods to protect concurrent access and modification of these fields. The shutdown logic is updated to close all active sessions and clear the sessions map before shutting down the server, further preventing race conditions during concurrent operations. Additionally, the test code in client/transport/stdio_test.go was modified to support Windows by appending ".exe" to the mock server executable filename and importing the runtime package for OS detection.

Changes

File(s) Change Summary
server/sse.go Added a read-write mutex to SSEServer and updated Start, Shutdown, and handleMessage methods to use locking for thread-safe access to srv and sessions. Enhanced shutdown to close all sessions and clear the map before server shutdown.
client/transport/stdio_test.go Added platform-specific handling for mock server executable filename by appending ".exe" on Windows in test functions. Imported runtime package to enable OS detection. No logic changes made.

Assessment against linked issues

Objective Addressed Explanation
Prevent data race between Start and Shutdown methods accessing srv in SSEServer (#166)
Make tests runnable on Windows by handling executable filename correctly (#172)

Possibly related PRs

  • fix race conditions #31: Also addresses race conditions in server/sse.go by adding synchronization to protect shared state in SSEServer.
    """

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 fceedb6 and ea1e930.

📒 Files selected for processing (1)
  • client/transport/stdio_test.go (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • client/transport/stdio_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 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.

@Wood-Q Wood-Q changed the title Add mutex to avoid data race bewteen Start and Shutdown in SSEServer fix: add mutex to SSEServer to avoid data race between Start and Shutdown (#166) Apr 18, 2025
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: 1

🧹 Nitpick comments (2)
server/sse.go (2)

212-212: Translate the Chinese comment to English

The comment "关闭所有会话" should be translated to English (it means "close all sessions") to maintain consistency with the rest of the codebase.

-		// 关闭所有会话
+		// Close all active sessions

348-350: Unnecessary mutex usage with sync.Map

The sync.Map type is already designed to be safe for concurrent use without additional synchronization. The RLock/RUnlock around the sessions.Load call is unnecessary and could impact performance.

-	s.mu.RLock()
	sessionI, ok := s.sessions.Load(sessionID)
-	s.mu.RUnlock()
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 71b910b and 21882fa.

📒 Files selected for processing (1)
  • server/sse.go (4 hunks)
🔇 Additional comments (3)
server/sse.go (3)

69-69: Good addition of a mutex to prevent race conditions

Adding a sync.RWMutex to the SSEServer struct is an appropriate solution to protect the shared srv field from concurrent access between Start and Shutdown methods.


194-199: Proper mutex usage in Start method

The write lock is correctly applied when assigning a new HTTP server instance to s.srv. This prevents other goroutines from accessing or modifying the server during initialization.


207-211: Good implementation of read locking and local variable copy

The read lock is correctly used when accessing s.srv and the pattern of copying to a local variable before unlocking is a best practice. This minimizes the lock duration while ensuring thread safety.

Comment on lines 67 to +69
keepAliveInterval time.Duration

mu sync.RWMutex
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Inconsistent protection pattern for the sessions map

While you've added mutex protection for the sessions map in the handleMessage method, the same protection is not applied in other methods that access this map (e.g., handleSSE, SendEventToSession). Either remove the mutex usage for sessions.Load (as sync.Map is already thread-safe) or consistently apply the protection pattern across all methods.

Also applies to: 212-219


🏁 Script executed:

#!/bin/bash
# Find all places where sessions map is accessed without mutex protection

echo "Checking for access to sessions map without mutex protection..."
rg -n "sessions\.(Load|Store|Delete|Range)" --type go server/sse.go | grep -v "mu\.(RLock|Lock)"

Length of output: 502


Ensure consistent synchronization for the sessions map

We’ve found multiple s.sessions accesses that aren’t wrapped by your mu lock, yet you’ve also added locking in only some methods. Since you’re using a sync.Map (which is already safe for concurrent use), you should either:

• Remove the mu entirely and drop the extra locking around handleMessage, relying solely on sync.Map.
• Or keep mu and wrap all sessions.Load/Store/Delete/Range calls under mu.RLock/mu.Lock.

Unprotected accesses in server/sse.go:

  • Line 213: s.sessions.Range(...)
  • Line 217: s.sessions.Delete(key)
  • Line 255: s.sessions.Store(sessionID, session)
  • Line 256: defer s.sessions.Delete(sessionID)
  • Line 349: sessionI, ok := s.sessions.Load(sessionID)
  • Line 416: sessionI, ok := s.sessions.Load(sessionID)

Please pick one synchronization pattern and apply it consistently to avoid races.

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: 0

🧹 Nitpick comments (3)
client/transport/stdio_test.go (3)

310-310: Chinese comment should be translated to English.

There is a Chinese comment in the codebase that should be translated to English for consistency throughout the codebase.

- // 创建一个新的 Stdio 实例但不调用 Start 方法
+ // Create a new Stdio instance without calling the Start method

323-323: Chinese comment should be translated to English.

There is another Chinese comment that should be translated to English for consistency.

- // 准备一个请求
+ // Prepare a request

35-38: Consider refactoring repeated platform-specific code.

The same pattern for adding the ".exe" suffix on Windows is duplicated three times in the code. Consider extracting this logic into a helper function to improve maintainability and follow the DRY principle.

+// getPlatformExecutablePath appends the .exe suffix when running on Windows
+func getPlatformExecutablePath(basePath string) string {
+    if runtime.GOOS == "windows" {
+        return basePath + ".exe"
+    }
+    return basePath
+}

Then, use this helper function in each location:

- mockServerPath := filepath.Join(os.TempDir(), "mockstdio_server")
- // Add .exe suffix on Windows
- if runtime.GOOS == "windows" {
-     mockServerPath += ".exe"
- }
+ mockServerPath := getPlatformExecutablePath(filepath.Join(os.TempDir(), "mockstdio_server"))

Also applies to: 312-315, 343-346

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ef892e3 and 31c2eb9.

📒 Files selected for processing (1)
  • client/transport/stdio_test.go (4 hunks)
🔇 Additional comments (4)
client/transport/stdio_test.go (4)

10-10: Runtime package import added for OS detection.

The runtime package was added to enable the detection of the operating system, which is necessary for the platform-specific handling of executable filenames in this file.


35-38: Platform-specific handling for executable filename.

These changes correctly add the ".exe" suffix to the executable filename when running on Windows, which is necessary for cross-platform compatibility.


312-315: Platform-specific handling for executable filename.

These changes correctly add the ".exe" suffix to the executable filename when running on Windows.


343-346: Platform-specific handling for executable filename.

These changes correctly add the ".exe" suffix to the executable filename when running on Windows.

@Wood-Q Wood-Q changed the title fix: add mutex to SSEServer to avoid data race between Start and Shutdown (#166) fix: add mutex to SSEServer to avoid data race between Start and Shutdown; fix test error on Windows (#166 #172) Apr 18, 2025
server/sse.go Outdated
s.mu.RUnlock()

if srv != nil {
// 关闭所有会话
Copy link
Contributor

Choose a reason for hiding this comment

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

Translate to English please :)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

sorry, I have deleted the annotation :)

@ezynda3 ezynda3 merged commit d3c77df into mark3labs:main Apr 19, 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.

There are some errors when I run tests on Windows Data race between Start and Shutdown in SSEServer struct
2 participants