Repository navigation
Closed
Labels
area-System.Net.SocketsenhancementProduct code improvement that does NOT require public API changes/additions
Milestone
Description
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:
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.
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
Reacted by Łukasz Domeradzki, Sander Saares, Adam Caviness and Alex Ehrnschwender
Reacted by Łukasz Domeradzki
Metadata
Metadata
Assignees
Labels
area-System.Net.SocketsenhancementProduct code improvement that does NOT require public API changes/additions
Activity
JustArchi commentedon Nov 10, 2021
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:
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.
JustArchi commentedon Nov 10, 2021
Just for the sake of completeness, I have this (another) unobserved task exception logged next to the bunch of operation canceled errors above:
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.
stephentoub commentedon Nov 10, 2021
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.
xPaw commentedon Nov 10, 2021
Why is the stacktrace so unhelpful, shouldn't it point to the code where BeginConnect was called?
Documentation was updated to say that
SocketExceptionwon't be thrown on NET 6, how come?https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.socket.beginconnect?view=net-5.0
antonfirsov commentedon Nov 10, 2021
@xPaw it means that the exceptions we used to throw synchronously on
Begin***methods will be thrown asynchronously, thus only observed onEndConnect, I believe you are facing this change now.stephentoub commentedon Nov 10, 2021
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.
xPaw commentedon Nov 10, 2021
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.
As it stands, I just have to guess where the exception came from.
stephentoub commentedon Nov 10, 2021
The problem is that you're not always calling EndConnect. The code shared is:
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.
xPaw commentedon Nov 10, 2021
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.
willdean commentedon Nov 10, 2021
+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.
yaakov-h commentedon Nov 11, 2021
Same. I'm quite surprised that the stack trace of the unobserved exception ends at the implementation of
ValueTask.ToTask(), missing the lower frames ofBeginConnect(), the user code that called into the sockets stack, and even the program entry point orThreadStartmethod.I'm not sure I've ever seen that before from an exception that has been thrown.
stephentoub commentedon Nov 11, 2021
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 remaining items
xPaw commentedon Dec 10, 2021
Worth mentioning that it is common to do a connect timeout, which would involve not calling EndConnect, like this: https://stackoverflow.com/a/4708790
antonfirsov commentedon Dec 10, 2021
In case we remove the disposed check, it will be possible to can call
EndConnectaftersocket.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
asyncis an option. When not,SocketAsyncEventArgsmethods provide much better performance (especially when theSocketAsyncEventArgsis cached by the user) and no weird side effects. To handle timeouts, one can useCancelConnectAsyncwith them.Do not throw ObjectDisposeException from Socket.EndXyz methods (#73335)
mikhail-barg commentedon Aug 8, 2022
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?
stianeklund commentedon Aug 16, 2022
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?stephentoub commentedon Aug 16, 2022
It's already in daily builds and will be in RC1 of .NET 7. There are no plans to backport it.