Skip to content

fix deadlock sendTransport #474

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

tosolveit
Copy link

@tosolveit tosolveit commented Jul 6, 2025

Description

Fixes #463

This PR improves the reliability of the Stdio transport by:

  • Introducing a background goroutine in spawnCommand to monitor subprocess exit and automatically close the done channel.
  • Adding an IsClosed method to detect if the subprocess has terminated.
  • Enhancing SendRequest with:
    1. Early checks using IsClosed() to prevent sending requests after subprocess exit.
    2. Additional <-c.done case in the select to return meaningful errors if the subprocess exits while awaiting a response.

Tests

  • Added TestStdio_DoneClosedWhenSubcommandExits to verify done is closed when subprocess exits.
  • Added SendRequestFailsIfSubprocessExited test to ensure SendRequest fails cleanly when the subprocess is no longer running.
  • Added TestStdio_IsClosed Unit test to ensure IsClosed() returns correct state before and after subprocess termination.

These changes address potential deadlocks and improve fault tolerance when subprocesses exit unexpectedly (e.g., very quickly or due to crash), making the transport more robust for real-world usage scenarios.

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • MCP spec compatibility implementation
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Code refactoring (no functional changes)
  • Performance improvement
  • Tests only (no functional changes)
  • Other (please describe):

Checklist

  • My code follows the code style of this project
  • I have performed a self-review of my own code
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the documentation accordingly

MCP Spec Compliance

  • This PR implements a feature defined in the MCP specification
  • Link to relevant spec section: Link text
  • Implementation follows the specification exactly

Additional Information

Summary by CodeRabbit

  • New Features

    • Improved detection and handling of subprocess termination, providing immediate feedback if actions are attempted after a subprocess has exited.
  • Bug Fixes

    • Enhanced error handling to prevent requests from being sent to closed subprocesses.
  • Tests

    • Added new tests to verify subprocess lifecycle handling and the accuracy of subprocess status reporting.

Copy link
Contributor

coderabbitai bot commented Jul 6, 2025

Walkthrough

Enhancements were made to the subprocess lifecycle management in the Stdio transport. A background goroutine now monitors subprocess termination, and an IsClosed method was introduced. The request-sending logic now checks for subprocess exit, and new tests were added to verify subprocess exit detection and the new lifecycle methods.

Changes

Files Change Summary
client/transport/stdio.go Added subprocess exit goroutine, IsClosed method, and improved error handling in request/response logic.
client/transport/stdio_test.go Added tests for subprocess exit detection, IsClosed behavior, and error handling after subprocess termination.

Possibly related PRs

Suggested reviewers

  • ezynda3

📜 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 656a7b4 and 79af76f.

📒 Files selected for processing (2)
  • client/transport/stdio.go (5 hunks)
  • client/transport/stdio_test.go (3 hunks)
🧰 Additional context used
🧠 Learnings (1)
client/transport/stdio_test.go (1)
Learnt from: octo
PR: mark3labs/mcp-go#149
File: mcptest/mcptest.go:0-0
Timestamp: 2025-04-21T21:26:32.945Z
Learning: In the mcptest package, prefer returning errors from helper functions rather than calling t.Fatalf() directly, giving callers flexibility in how to handle errors.
🔇 Additional comments (8)
client/transport/stdio.go (5)

126-127: Documentation enhancement accurately reflects new functionality.

The added comment clearly describes the new background goroutine behavior for subprocess monitoring.


168-176: Excellent implementation of subprocess exit monitoring.

The background goroutine correctly handles subprocess termination by:

  • Waiting for the subprocess to complete with cmd.Wait()
  • Using a non-blocking select to check if the done channel is already closed
  • Only closing the channel if not already closed, preventing double-close panics

This prevents race conditions between explicit Close() calls and subprocess termination.


206-214: Clean and efficient implementation of subprocess state checking.

The IsClosed() method uses a non-blocking select pattern to safely check if the subprocess has exited without blocking the caller. This is the correct approach for this type of status check.


318-321: Proper early exit handling prevents unnecessary work.

The early check using IsClosed() before sending requests is well-implemented:

  • Prevents sending requests to dead subprocess
  • Includes proper cleanup of the response channel
  • Returns a meaningful error message

This optimization avoids wasted work and provides immediate feedback to callers.


333-335: Comprehensive handling of subprocess exit during request processing.

The addition of the done channel case in the select statement correctly handles the scenario where the subprocess exits while waiting for a response. The implementation:

  • Properly cleans up the response channel
  • Returns a descriptive error message
  • Prevents potential deadlocks

This completes the deadlock prevention mechanism for all phases of request processing.

client/transport/stdio_test.go (3)

388-410: Thorough test coverage for subprocess exit scenario.

This test case effectively verifies the new error handling behavior:

  • Uses a subprocess that exits immediately (sh -c "exit 0")
  • Properly waits for subprocess termination using require.Eventually
  • Verifies that SendRequest returns an error containing "subprocess"
  • Follows good testing practices with proper error assertions

The test ensures that the early exit check in SendRequest works correctly.


637-661: Excellent validation of the background goroutine functionality.

This test specifically validates that the background goroutine correctly closes the done channel when the subprocess exits:

  • Creates a subprocess that exits immediately
  • Uses require.Eventually with appropriate timeout and polling interval
  • Includes proper cleanup logic to kill the process if still running
  • Directly tests the core functionality added in the spawnCommand method

The test provides confidence that the subprocess monitoring mechanism works as intended.


675-698: Comprehensive test coverage of the IsClosed method.

This test suite thoroughly validates the IsClosed() method behavior across all relevant states:

  • Before subprocess start (should return false)
  • After subprocess start but before exit (should return false)
  • After subprocess exit (should return true)

The test cases use appropriate subprocess commands and include proper cleanup. The use of require.Eventually for the async termination check is correct.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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.

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.

bug: if sub command exited somehow, later SendTransport will hang forever
1 participant