@@ -743,6 +743,56 @@ def string
743743 assert stream_b . closed?
744744 end
745745
746+ test "store_stream_for_session closes a refused stream outside the mutex" do
747+ session_id = initialize_test_session
748+ @transport . send ( :store_stream_for_session , session_id , StringIO . new )
749+
750+ mutex = @transport . instance_variable_get ( :@mutex )
751+ closed_outside_mutex = false
752+ refused = Object . new
753+ refused . define_singleton_method ( :close ) do
754+ if mutex . try_lock
755+ closed_outside_mutex = true
756+ mutex . unlock
757+ end
758+ end
759+
760+ assert_nil @transport . send ( :store_stream_for_session , session_id , refused )
761+ assert closed_outside_mutex , "the refused stream was closed while the mutex was held"
762+ end
763+
764+ test "store_stream_for_session swallows an error from closing a refused stream" do
765+ session_id = initialize_test_session
766+ @transport . send ( :store_stream_for_session , session_id , StringIO . new )
767+
768+ failing = Object . new
769+ failing . define_singleton_method ( :close ) { raise IOError , "already closed by the peer" }
770+
771+ assert_nil @transport . send ( :store_stream_for_session , session_id , failing )
772+ assert_equal 200 , @transport . handle_request ( create_rack_request (
773+ "POST" ,
774+ "/" ,
775+ { "CONTENT_TYPE" => "application/json" , "HTTP_MCP_SESSION_ID" => session_id } ,
776+ { jsonrpc : "2.0" , method : "ping" , id : "ping-1" } . to_json ,
777+ ) ) [ 0 ]
778+ end
779+
780+ test "store_stream_for_session closes the stream outside the mutex when the session is gone" do
781+ # The session was removed between the GET's checks and its body running, so there is nothing to attach to.
782+ mutex = @transport . instance_variable_get ( :@mutex )
783+ closed_outside_mutex = false
784+ orphan = Object . new
785+ orphan . define_singleton_method ( :close ) do
786+ if mutex . try_lock
787+ closed_outside_mutex = true
788+ mutex . unlock
789+ end
790+ end
791+
792+ assert_nil @transport . send ( :store_stream_for_session , "no-such-session" , orphan )
793+ assert closed_outside_mutex , "the orphaned stream was closed while the mutex was held"
794+ end
795+
746796 test "handles GET request with invalid session ID" do
747797 request = create_rack_request (
748798 "GET" ,
0 commit comments