Repository navigation
Description
This issue comes from investigating test failures on this Roslyn PR dotnet/roslyn#46510
At the conclusion of running the unit tests for VBCSCompiler server the xUnit process will refuse to exit. The xUnit output will indicate that the tests have completed running but the process itself will not exit. Attaching the debugger to the xUnit process and there are two threads of note that are still running:
GC Finalizer
System.Private.CoreLib.dll!System.Threading.SpinWait.SpinOnceCore(int sleep1Threshold) (Unknown Source:0)
System.Net.Sockets.dll!System.Net.Sockets.SafeSocketHandle.CloseAsIs(bool abortive) (Unknown Source:0)
System.Net.Sockets.dll!System.Net.Sockets.Socket.Dispose(bool disposing) (Unknown Source:0)
System.Net.Sockets.dll!System.Net.Sockets.Socket.~Socket() (Unknown Source:0)
[Native to Managed Transition] (Unknown Source:0)
.NET Sockets
System.Net.Sockets.dll!System.Net.Sockets.SocketAsyncEngine.EventLoop() (Unknown Source:0)
System.Net.Sockets.dll!System.Net.Sockets.SocketAsyncEngine..ctor.AnonymousMethod__14_0(object s) (Unknown Source:0)
System.Private.CoreLib.dll!System.Threading.ThreadHelper.ThreadStart(object obj) (Unknown Source:0)
[Native to Managed Transition] (Unknown Source:0)
The VBCSCompiler server makes heavy use of named pipes. Looking through the Socket on the finalizer thread I can confirm it's a Unix Domain socket related to the named pipes the compiler is creating (the path in the end point matches the paths we create in the tests).
Unfortunately after a day of debugging I have not been able to narrow this problem down any further:
- The problem only repros when running the entire test assembly. I ran each test class in the assembly and none of them individually reproduce the issue. Have to run them as a group.
- Went through a cycle of causing the hang, identifying the test which created the socket that was hung in the finalizer, disable that test, re-run the assembly. Did this for about five different tests and it had no impact on the hang.
- Thought this may be related to WaitForConnectionAsync does not respond to cancellation #40289 so I tried aggressively calling
NamedPipeServerStream.Disposeon any instance that was hung in aWaitForConnectionAsynccall.
None of these has had any impact though. I've also been unsuccessful in constructing a more concise repro. 😦
More than happy to provide any info to make tracking this down easier.
Repro Information:
- Runtime: .NET 5 Preview 7
- OS: Ubuntu 18.04, Ubuntu 18.04 via WSL2, OSX
Activity
stephentoub commentedon Aug 4, 2020
cc: @tmds
Smaller repro
jaredpar commentedon Aug 6, 2020
Did my best to narrow this down to a smaller problem. Created a branch where you can see the delta between our unit tests passing and hanging. This commit shows that it's simply enabling one new test to run on Linux that causes this hang.
To repro this do the following:
Couple notes:
A brief description of what this particular test is doing:
NamedPipeServerStreaminstances on the same pipe nameNamedPipeClientStreaminstance that fully connectsNamedPipeServerStreaminstances, does not dispose the connected oneNamedPipeClientStreamNamedPipeServerStreaminstances remains undisposed and it appears this is the one that ends up stuck in the finalizer thread.tmds commentedon Aug 24, 2020
Since .NET 5,
SafeHandlesare ref'ed for on-goingSocketoperations (instead of callingDangerousGetHandle). If we are spinning here, there is a on-going operation against theSocketthat keeps the handle from being released. It would be interesting to identify the operation that is on-going on some other thread. It may help put together a reproducer.Aborting the on-going
Socketoperations is attempted by theTryUnblockSocket. If theSocketdoesn't haveCLOEXECthis method no-ops. This method is best-effort. There are tests that verify abortive behavior for UDP/TCP, but no tests for domain sockets.runtime/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SafeSocketHandle.Unix.cs
Lines 196 to 235 in be197ad
Note that async
Socketoperations always nicely abort because there are no on-goingSocketoperations that keep theSafeHandleref'ed.antonfirsov commentedon Aug 24, 2020
I'm currently trying to figure that out, but my gut feel is that spinning in the finalizer thread is a bad idea in any case, and we should probably rethink the way
CloseAsIsworks, regardless of the outcome of the investigation.jaredpar commentedon Aug 24, 2020
@tmds
Really wish I could've found a simpler repro here that would more clearly identify the operation occurring. Spent several hours on this but was unable to do so.
More than happy to help out with any questions on the current repro.
antonfirsov commentedon Aug 26, 2020
Looks like the issue is not caused by outstanding blocking calls. I have a smaller repro now:
https://gist.github.com/antonfirsov/ce0cb4992e115bb4d6e8dd6862fd6780
Here is what is happening in my understanding:
SafePipeHandle.Unixincreases the reference counter onSocketSafeHandle:runtime/src/libraries/System.IO.Pipes/src/Microsoft/Win32/SafeHandles/SafePipeHandle.Unix.cs
Line 36 in c6da68c
NamedPipeClientConnectionHostseems to leak (= not dispose) someNamedPipeServerStreaminstances. (@jaredpar I'm wondering if this only happens in the repro branch or is this a bug in the compiler server?)Socketfinalizer is called before the finalizers of the "owner"SafePipeHandleandNamedPipeServerStream.SocketSafeHandleis not released.CloseAsIswill keep spinning, blocking the finalizer thread, preventing the finalization ofSafePipeHandle(therefore the release ofSocketSafeHandle):runtime/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SafeSocketHandle.cs
Lines 106 to 114 in c6da68c
I have an idea for a PR that would remove the spinning.
For some reason the issue does not happen with 3.1.
jaredpar commentedon Aug 26, 2020
This should not be happening in the product anymore. After filing the bug I was able to find a few other places these were leaking, made a push to get rid of them, and I believe I got them all at this point. It's possible it's still happening in the tests though.
2 remaining items
tmds commentedon Aug 27, 2020
When the
Socketgets closed (by the user explicitly, or on the finalizer thread) we want all threads that are performing a blocking operation on theSocketto unblock (and return something likeSocketError.OperationAborted).tmds commentedon Aug 27, 2020
Anton, I think we could
duptheSafeSocketHandleso theSafePipeHandlehas its own kernel-level reference. wdyt?antonfirsov commentedon Aug 27, 2020
@tmds what will happen to those ongoing operations if we close the underlying handle?
I think we really need to distinguish between the finalizer and a normal Dispose. It already indicates a user bug, if a finalizer is being executed. Instead of being 100% correct handling blocking operations I would only aim for preventing handle leak in those cases.
I believe the way
CloseAsIsworks now in a very unsafe way:!_releasedindicates an ongoing blocking operation. This is not always true.DangerousReleasein a finalizer is risking to block the finalizer thread (a fatal bug!)I would prefer to find a way to solve this in Sockets instead of just changing the way NamedPipes are utilizing sockets. As an alternative, we can document that user code should never
DangerousAddRef/DangerousReleaseonsocket.SafeHandle, but that sounds weird to me.tmds commentedon Aug 27, 2020
With 3.1 on-going operations didn't ref the
SafeHandle. With 5.0 they do, and as a consequence they prevent theSafeHandlefrom getting released (that is: actually closing). So we need something to unblock the operations.In case of a finalizer, we may assume there are no on-going operations, because those would prevent the
SafeHandlefrom being finalized, right? So we may skip theTryUnblockSocketand prevent blocking the finalizer thread.antonfirsov commentedon Aug 27, 2020
What I mean is that in a finalizer (instead of waiting for the handle to be released) we may want force-close the handle, independently of the ref-count/release mechanism.
Unfortunately, this is not true. In this particular case we are in the finalizer of the
Socketinstance, so ongoing P/Invoke-s have no effect on whether it's executed or not.Edit: on the other hand, this should be a very rare corner-case. We expect blocking socket operations to be triggered from managed
Socketcalls, I think it's unlikely the Socket gets finalized in the meanwhile.antonfirsov commentedon Aug 27, 2020
I just noticed this comment in
TryUnblockSocket:What does "indefinitely" mean here? Is it only for the time the blocking socket call is executing? Is it guaranteed to eventually return? Since it's a rare corner-case, in a finalizer it might be acceptable to wait for a blocking call. (As an alternative of of keeping the behavior whereSafeSocketHandle.DangerousAddRefis risking a finalizer thread hang.)Edit: I found #37873 now, which answers my question. Still hoping we can find a way to remove the spinning instead of working around this in
SafePipeHandle. It's not good that we don't distinguish between blocking syscalls, and other operations changingSocketSafeHandle's refcount.For example, we can set/unset a flag on
SafeSocketHandlewhen doing blocking syscalls.antonfirsov commentedon Aug 27, 2020
~Socket()was a NOP before the following PR:dotnet/corefx#38499
I wonder if the concern of indefinite spinning (or blocking
close) was discussed in that PR?SafeSocketHandle.DangerousAddRefwas probably safe before that./cc @wfurt
antonfirsov commentedon Aug 27, 2020
Just an illustration of the bigger issue we have here. It's this easy to create a finalizer thread hang now:
geoffkizer commentedon Aug 28, 2020
This is definitely related to the fix we made in dotnet/corefx#38499. Before that we didn't really have a socket finalizer, so we would not have hit this issue.
That said, we cannot undo the change in dotnet/corefx#38499 (at least not without making other, extensive changes). The reasoning is explained here: #29327 (comment)
I think the best fix for 5.0 is to simply not try to cancel outstanding operations when the Socket finalizer is called, as was suggested above. It's possible that this could lead to some unexpected behavior in weird corner cases, but I think those corner cases are restricted to the case where you do a DangerousAddRef without a corresponding DangerousRelease. Since we are currently hanging the finalizer thread in that case, we can probably live with a few quirky corner cases for now.
I do think we should revisit all of this in the future. Ideally we shouldn't need to have a finalizer on Socket. But changing that would take some effort and research etc.
tmds commentedon Aug 28, 2020
The spinning was introduced as part of dotnet/corefx#38804. In that PR,
SocketPInvoke changed to useSafeHandlesinstead ofDangerousAddRef.Because previously there were no out-standing references, the handle was released as soon as the
Socketgot Closed. On Windows, this caused on-going operations to abort, but on Linux those operations would just keep on blocking.Due to the use of
SafeHandle, the handle release no longer occurs onClosewhen there are on-going operations. That became the responsibility ofTryUnblockSocket.The spinning was added to deal with the race described in #40301 (comment). But I did not consider someone other than
Socketoperations couldDangerousAddRef, which leads to infinite spinning.Based on what was said I think we are safe to not call
TryUnblockSocketwhen Closing on a finalizer thread, because there should be no on-goingSocketoperations that need to be aborted.jaredpar commentedon Sep 1, 2020
🎉
karelz commentedon Sep 10, 2020
Fixed also in 5.0 in RC1 (PR #41688) and in RC2 (PR #41747)