Skip to content

Socket.BeginConnect in .NET 6 throws an unobserved SocketException #61411

Closed

Description

@xPaw

Description

After updating to .NET 6 we started seeing (separate users and software) unobserved SocketException.

After analyzing the logs, I believe it is being triggered here:

https://github.com/SteamRE/SteamKit/blob/2.4.0-Alpha.3/SteamKit2/SteamKit2/Networking/Steam3/TcpConnection.cs#L158

However it is hard to tell because the stacktrace doesn't really have useful information which could pin point the exact code.

The code that uses AwaitableSocketAsyncEventArgs is in Socket.ConnectAsync

@yaakov-h pointed out this:

ValueTask.AsTask is the only code path to there, and I don’t think SK2 knows about ValueTask, so that’s gotta be a runtime bug.

https://source.dot.net/#System.Private.CoreLib/ValueTask.cs,638

Reproduction Steps

Expected behavior

Exception should be catchable, or not happen in this manner?

Actual behavior

Unhandled exception. System.AggregateException: A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread. (Operation canceled) (Operation canceled)
 ---> System.Net.Sockets.SocketException (125): Operation canceled
   at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
   at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult(Int16 token)
   at System.Threading.Tasks.ValueTask.ValueTaskSourceAsTask.<>c.<.cctor>b__4_0(Object state)
   --- End of inner exception stack trace ---
   at System.AggregateException.Handle(Func`2 predicate)
   at SteamDatabaseBackend.Bootstrapper.OnUnobservedTaskException(Object sender, UnobservedTaskExceptionEventArgs args) in /home/steamdb/deploy/Bootstrapper.cs:line 149
   at System.Threading.Tasks.TaskScheduler.PublishUnobservedTaskException(Object sender, UnobservedTaskExceptionEventArgs ueea)
   at System.Threading.Tasks.TaskExceptionHolder.Finalize()

Regression?

I did not get this on .NET 5.

Known Workarounds

No response

Configuration

Debian 11 x64.

Other information

No response

Activity

  1. ghost added
    untriaged
    on Nov 10, 2021
  2. JustArchi commented on Nov 10, 2021

    @JustArchi
    Contributor

    I've observed similar error in entirely different library, Discord.Net, that also didn't happen in .NET 5.0.

    However, I don't have much besides the stacktrace:

    ArchiBot|OnUnobservedTaskException() System.Net.Sockets.SocketException (125): Operation canceled
    at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
    at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult(Int16 token)
    at System.Threading.Tasks.ValueTask.ValueTaskSourceAsTask.<>c.<.cctor>b__4_0(Object state)
    

    Could be a coincidence, but I very much doubt that the first day after updating to .NET 6.0 I got networking issues that triggered a bug that I didn't see for the last year if not more, especially considering other people stumble upon the same. Some regression probably happened.

  3. JustArchi commented on Nov 10, 2021

    @JustArchi
    Contributor

    Just for the sake of completeness, I have this (another) unobserved task exception logged next to the bunch of operation canceled errors above:

    ArchiBot|OnUnobservedTaskException() System.Net.Http.HttpRequestException: Resource temporarily unavailable (discord.com:443)
    ---> System.Net.Sockets.SocketException (11): Resource temporarily unavailable
    at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
    at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult(Int16 token)
    at System.Net.Sockets.Socket.<ConnectAsync>g__WaitForConnectWithCancellation|277_0(AwaitableSocketAsyncEventArgs saea, ValueTask connectTask, CancellationToken cancellationToken)
    at System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken)
    --- End of inner exception stack trace ---
    at System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken)
    at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
    at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
    at System.Net.Http.HttpConnectionPool.AddHttp11ConnectionAsync(HttpRequestMessage request)
    at System.Threading.Tasks.TaskCompletionSourceWithCancellation`1.WaitWithCancellationAsync(CancellationToken cancellationToken)
    at System.Net.Http.HttpConnectionPool.GetHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
    at System.Net.Http.HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)
    at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
    at System.Net.Http.DecompressionHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
    at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
    at Discord.Net.Rest.DefaultRestClient.SendInternalAsync(HttpRequestMessage request, CancellationToken cancelToken, Boolean headerOnly)
    at Discord.Net.Rest.DefaultRestClient.SendAsync(String method, String endpoint, CancellationToken cancelToken, Boolean headerOnly, String reason)
    at Discord.Net.Queue.RestRequest.SendAsync()
    at Discord.Net.Queue.RequestBucket.SendAsync(RestRequest request)
    at Discord.Net.Queue.RequestQueue.SendAsync(RestRequest request)
    at Discord.API.DiscordRestApiClient.SendInternalAsync(String method, String endpoint, RestRequest request)
    at Discord.API.DiscordRestApiClient.SendAsync[TResponse](String method, String endpoint, BucketId bucketId, ClientBucketType clientBucket, RequestOptions options)
    at Discord.API.DiscordRestApiClient.GetBotGatewayAsync(RequestOptions options)
    at Discord.Rest.ClientHelper.GetBotGatewayAsync(BaseDiscordClient client, RequestOptions options)
    at Discord.WebSocket.DiscordShardedClient.OnLoginAsync(TokenType tokenType, String token)
    at Discord.Rest.BaseDiscordClient.LoginInternalAsync(TokenType tokenType, String token, Boolean validateToken)
    at Discord.Rest.BaseDiscordClient.LoginInternalAsync(TokenType tokenType, String token, Boolean validateToken)
    at Discord.Rest.BaseDiscordClient.LoginAsync(TokenType tokenType, String token, Boolean validateToken)
    at ArchiBot.Platform.Discord.DiscordBot.Start(String token)
    

    However, it might or might not be related to the above, so it shouldn't be blindly assumed that this is the culprit. It could help pinpoint the real culprit perhaps, and that's why I'm attaching it, maybe it gives a clue where the error is coming from - but I can't say for sure if it's directly tied to the original one reported in this issue, it could happen due to network issues alone and be something entirely different, but it looks close or related enough to me to post it.

  4. stephentoub commented on Nov 10, 2021

    @stephentoub
    Member

    By "unobserved SocketException" you mean the UnobservedTaskException event is being raised?

    That would make sense and be legit based on the code you shared. The code you linked to in SK2 Is ignoring the returned IAsyncResult in the case of a timeout, so if the operation times out, it's just dropping that IAsyncResult on the floor without ever joining with it and seeing whatever exception it might contain. In .NET 6, BeginConnect is just a thin wrapper for ConnectAsync, so by not joining with it, you're allowing a potentially faulted task to go unobserved. So the event is raised.

  5. xPaw commented on Nov 10, 2021

    @xPaw
    ContributorAuthor

    Why is the stacktrace so unhelpful, shouldn't it point to the code where BeginConnect was called?

    Documentation was updated to say that SocketException won't be thrown on NET 6, how come?

    SocketException
    .NET Framework and .NET 5 and earlier only: An error occurred when attempting to access the socket.

    https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.socket.beginconnect?view=net-5.0

  6. antonfirsov commented on Nov 10, 2021

    @antonfirsov
    Contributor

    Documentation was updated to say that SocketException won't be thrown on NET 6, how come?

    @xPaw it means that the exceptions we used to throw synchronously on Begin*** methods will be thrown asynchronously, thus only observed on EndConnect, I believe you are facing this change now.

  7. stephentoub commented on Nov 10, 2021

    @stephentoub
    Member

    shouldn't it point to the code where BeginConnect was called?

    Because it's asynchronous and the error isn't coming from BeginConnect (BeginConnect returned successfully, synchronously). The error is coming from the asynchronous completion, at which point BeginConnect on the stack is long gone. There are potential things that can be done to improve the exception stack to include the stack of BeginConnect, but they involve doing a stack walk even for the success cases, and thus aren't pay-for-play.

  8. xPaw commented on Nov 10, 2021

    @xPaw
    ContributorAuthor

    thus only observed on EndConnect, I believe you are facing this change now.

    In the code I linked EndConnect is wrapped in a try/catch.

    What is the correct fix for this then? I wrapped the BeginConnect in a try/catch (to catch the the other exceptions), but I'm not sure that will help with this particular issue.

    There are potential things that can be done to improve the exception stack to include the stack of BeginConnect

    As it stands, I just have to guess where the exception came from.

  9. stephentoub commented on Nov 10, 2021

    @stephentoub
    Member

    In the code I linked EndConnect is wrapped in a try/catch.

    The problem is that you're not always calling EndConnect. The code shared is:

                var asyncResult = socket!.BeginConnect(CurrentEndPoint, null, null );
                if ( WaitHandle.WaitAny( new WaitHandle[] { asyncResult.AsyncWaitHandle, cancellationToken.Token.WaitHandle }, timeout ) == 0 )
                {
                    try
                    {
                        socket.EndConnect( asyncResult );
                        ConnectCompleted( true );
                    }
                    catch ( Exception ex )
                    {
                        log.LogDebug( "TcpConnection", "Socket exception while completing connection request to {0}: {1}", CurrentEndPoint, ex );
                        ConnectCompleted( false );
                    }
                }
                else
                {
                    ConnectCompleted( false );
                }

    If that else block is taken, the asyncResult and thus any exceptions it might eventually fault with are ignored. This problem was always there, the code was always ignoring the exception in that case, it's just that now the UnobservedTaskException event is being raised to tell you about it.

  10. xPaw commented on Nov 10, 2021

    @xPaw
    ContributorAuthor

    Right, that's a good catch (I didn't write this code).

    So is this not a regression then? My problem with this is how unhelpful the exception is.

  11. willdean commented on Nov 10, 2021

    @willdean
    Contributor

    My problem with this is how unhelpful the exception is.

    +100 from me here on this. We're going through exactly the same misery trying to track this down here in an app which we've just moved from 5-6.

    I'm delighted if something new has drawn attention to a lurking latent defect. But highly undelighted that there is no connection, either temporal or "geographical" between the error message and the problem.

  12. yaakov-h commented on Nov 11, 2021

    @yaakov-h
    Member

    Same. I'm quite surprised that the stack trace of the unobserved exception ends at the implementation of ValueTask.ToTask(), missing the lower frames of BeginConnect(), the user code that called into the sockets stack, and even the program entry point or ThreadStart method.

    I'm not sure I've ever seen that before from an exception that has been thrown.

  13. stephentoub commented on Nov 11, 2021

    @stephentoub
    Member

    The exception here is going unhandled on stacks completely separate from the code that called BeginConnect. The exception isn't propagating out through code that would update its stack, as would happen if you were using await. Rather, the exception is being triggered in a callback, ignored, and then the UnobservedTaskException event is being raised.

  14. 14 remaining items

  15. added
    enhancement
    and removed
    untriaged
    on Dec 9, 2021
  16. xPaw commented on Dec 10, 2021

    @xPaw
    ContributorAuthor

    Worth mentioning that it is common to do a connect timeout, which would involve not calling EndConnect, like this: https://stackoverflow.com/a/4708790

  17. antonfirsov commented on Dec 10, 2021

    @antonfirsov
    Contributor

    In case we remove the disposed check, it will be possible to can call EndConnect after socket.Close() to observe the exception. I understand this is not ideal, but the APM (Begin*/End*) methods are really legacy compatibility API-s today.

    It's preferred to migrate to task-based overloads when going async is an option. When not, SocketAsyncEventArgs methods provide much better performance (especially when the SocketAsyncEventArgs is cached by the user) and no weird side effects. To handle timeouts, one can use CancelConnectAsync with them.

  18. modified the milestones: Future, 7.0.0 on Feb 7, 2022
  19. self-assigned this
    on Jun 2, 2022
  20. ghost added
    in-pr
    on Aug 3, 2022
  21. added a commit that references this issue on Aug 5, 2022
    5d4526d
  22. ghost removed
    in-pr
    on Aug 5, 2022
  23. mikhail-barg commented on Aug 8, 2022

    @mikhail-barg

    Great to see this is finally fixed! Could you please clarify which runtime version would get the fix? Will it be available in net6 considering it's LTS status?

  24. stianeklund commented on Aug 16, 2022

    @stianeklund

    Any news as to when these changes will be available in net7? I don't see any new changes in System.Net.Sockets, might just be in daily builds (I haven't gone that far to test that yet). Also curious whether or not this will be back ported to net6?

  25. stephentoub commented on Aug 16, 2022

    @stephentoub
    Member

    It's already in daily builds and will be in RC1 of .NET 7. There are no plans to backport it.

  26. ghost locked as resolved and limited conversation to collaborators on Sep 15, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area-System.Net.Socketsenhancement

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions