Repository navigation
Fix leaks of undisposed async SafeFileHandle and PipeStream instances on Windows - #137507
Conversation
…dows Reproduces dotnet#137501: after async reads of redirected stdout/stderr, the parent pipe handles are never finalized unless the readers are disposed. Co-authored-by: Copilot <[email protected]> Copilot-Session: 8cfdacb8-9380-470b-83d0-2598d9255b9b
…ndows The cached OverlappedValueTaskSource is rooted by its PreAllocatedOverlapped until SafeFileHandle.ReleaseHandle disposes it. Its reference back to the SafeFileHandle prevented the handle from ever being finalized when it was not disposed explicitly. Clear the reference while the instance is cached and set it again when it's rented. Fixes dotnet#137501 Co-authored-by: Copilot <[email protected]> Copilot-Session: 8cfdacb8-9380-470b-83d0-2598d9255b9b
Co-authored-by: Copilot <[email protected]> Copilot-Session: 8cfdacb8-9380-470b-83d0-2598d9255b9b
|
Azure Pipelines: Successfully started running 3 pipeline(s). 12 pipeline(s) were filtered out due to trigger conditions. There may be pipelines that require an authorized user to comment /azp run to run. |
|
Tagging subscribers to this area: @dotnet/area-system-io |
…e same ValueTask twice Co-authored-by: Copilot <[email protected]> Copilot-Session: 8cfdacb8-9380-470b-83d0-2598d9255b9b
The cached PipeValueTaskSource is rooted by its PreAllocatedOverlapped. Its reference back to the PipeStream prevented the stream and its SafePipeHandle from ever being collected when the stream was not disposed explicitly. Clear the reference while the instance is cached and set it again when it's rented. Co-authored-by: Copilot <[email protected]> Copilot-Session: 8cfdacb8-9380-470b-83d0-2598d9255b9b
…n test Windows-only On Unix, the continuation of the async write can run inline on the thread pool thread that performed the write, so GC.Collect can happen while that work item is still on the stack and keeps the write handle alive. Co-authored-by: Copilot <[email protected]> Copilot-Session: 8cfdacb8-9380-470b-83d0-2598d9255b9b
There was a problem hiding this comment.
🟡 Changes recommended
The regression test can pass despite the leak because synchronous EOF disposes the rented source, so it must deterministically leave a source cached to verify the fix.
1 open issue
What changed in this PR
Fixes Windows async I/O reference cycles that prevent undisposed file and pipe handles from being finalized, addressing the redirected-process-output leak reported in #137501.
Changes:
- Clears owner references while reusable async operation sources are cached, restoring them when rented.
- Preserves
InvalidOperationExceptionfor repeated result retrieval from the same source-backedValueTask. - Adds regression tests for handle finalization and repeated result retrieval.
| File | Description |
|---|---|
| src/libraries/System.Runtime/tests/System.IO.FileSystem.Tests/RandomAccess/ReadAsync.cs | Tests repeated ValueTask result retrieval. |
| src/libraries/System.Runtime/tests/System.IO.FileSystem.Tests/FileStream/Dispose.cs | Tests finalization of undisposed file handles wrapping pipes. |
| src/libraries/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeFileHandle.OverlappedValueTaskSource.Windows.cs | Breaks cached sources’ references to file handles. |
| src/libraries/System.IO.Pipes/tests/NamedPipeTests/NamedPipeTest.Specific.cs | Tests finalization of undisposed named-pipe handles. |
| src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Windows.cs | Restores stream references for rented read/write sources. |
| src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.ValueTaskSource.cs | Clears stream references before caching completed sources. |
| src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.Windows.cs | Restores the stream reference for rented connection sources. |
| src/libraries/System.Diagnostics.Process/tests/ProcessTests.Windows.cs | Tests redirected-output handle finalization after async reads. |
Review effort: Balanced
…leted operation Getting a stale result (when the instance may already be used by another operation) or the result of an operation that is still in progress must not return the instance to the cache, as clearing its owner reference while an operation is in flight would crash the process in the IO completion callback. Such calls keep throwing InvalidOperationException. Co-authored-by: Copilot <[email protected]> Copilot-Session: 8cfdacb8-9380-470b-83d0-2598d9255b9b
Co-authored-by: Copilot <[email protected]> Copilot-Session: 8cfdacb8-9380-470b-83d0-2598d9255b9b
…ource The cached value task source kept the disposed CancellationTokenRegistration, which references the CancellationTokenSource and all of its other registrations. A registration that references the stream made the stream and its handle reachable again. Clear the registration when returning the instance for reuse. Co-authored-by: Copilot <[email protected]> Copilot-Session: 8cfdacb8-9380-470b-83d0-2598d9255b9b
The ExecutionContext captured when the reusable PipeValueTaskSource was created was kept alive for as long as the instance, together with all AsyncLocal values, and used to run every completion callback. The completion callback does not need it, as ManualResetValueTaskSourceCore flows the awaiter's context to the continuation. Use PreAllocatedOverlapped.UnsafeCreate, like SafeFileHandle does. Co-authored-by: Copilot <[email protected]> Copilot-Session: 8cfdacb8-9380-470b-83d0-2598d9255b9b
…source is reused Co-authored-by: Copilot <[email protected]> Copilot-Session: 8cfdacb8-9380-470b-83d0-2598d9255b9b
There was a problem hiding this comment.
🟡 Changes recommended
The test can fail spuriously because an inline continuation may reach the GC assertion before the helper’s captured ExecutionContext is cleared, even when UnsafeCreate is used.
1 open issue
1 resolved since last review
Review effort: Balanced
…t test When the async helper completed, the test continuation could run (inline or on another thread) before the helper's state machine and captured ExecutionContext were cleared, keeping the AsyncLocal value alive during the GC. Co-authored-by: Copilot <[email protected]> Copilot-Session: 8cfdacb8-9380-470b-83d0-2598d9255b9b
…finalized The cached instances are rooted by their PreAllocatedOverlapped. Now that they don't reference the stream, the stream can be finalized, but DisposeCore disposed them only when disposing explicitly, so they stayed rooted forever. Co-authored-by: Copilot <[email protected]> Copilot-Session: 8cfdacb8-9380-470b-83d0-2598d9255b9b
|
/ba-g the test failure is unrelated (it happened on Azure Linux and here we have touched only Windows-specific part of the product) |
|
/backport to release/11.0 |
|
Started backporting to |
|
@adamsitnik backporting to git am output$ git cherry-pick e86329518cd865bfe4e57fe0528bb812e6c9453a
Auto-merging src/libraries/System.Runtime/tests/System.IO.FileSystem.Tests/FileStream/Dispose.cs
CONFLICT (content): Merge conflict in src/libraries/System.Runtime/tests/System.IO.FileSystem.Tests/FileStream/Dispose.cs
error: could not apply e86329518cd... Fix leaks of undisposed async SafeFileHandle and PipeStream instances on Windows (#137507)
hint: After resolving the conflicts, mark them with
hint: "git add/rm <pathspec>", then run
hint: "git cherry-pick --continue".
hint: You can instead skip this commit with "git cherry-pick --skip".
hint: To abort and get back to the state before "git cherry-pick",
hint: run "git cherry-pick --abort".
hint: Disable this message with "git config set advice.mergeConflict false"
$ git am --3way --empty=keep --ignore-whitespace --keep-non-patch changes.patch
Applying: Add test for redirected pipe handles leaking after async reads on Windows
Applying: Don't root SafeFileHandle from cached OverlappedValueTaskSource on Windows
Applying: Add FileStream regression test for undisposed async pipe handles
Applying: Keep throwing InvalidOperationException when getting the result of the same ValueTask twice
Applying: Don't root PipeStream from cached PipeValueTaskSource on Windows
Applying: Test all sync/async pipe combinations and make FileStream finalization test Windows-only
Applying: Reuse the value task source only after consuming the result of a completed operation
Applying: Add test for getting the result of the same PipeStream ValueTask twice
Applying: Don't root the cancellation token source from the cached value task source
Using index info to reconstruct a base tree...
M src/libraries/System.Runtime/tests/System.IO.FileSystem.Tests/FileStream/Dispose.cs
Falling back to patching base and 3-way merge...
Auto-merging src/libraries/System.Runtime/tests/System.IO.FileSystem.Tests/FileStream/Dispose.cs
CONFLICT (content): Merge conflict in src/libraries/System.Runtime/tests/System.IO.FileSystem.Tests/FileStream/Dispose.cs
error: Failed to merge in the changes.
hint: Use 'git am --show-current-patch=diff' to see the failed patch
hint: When you have resolved this problem, run "git am --continue".
hint: If you prefer to skip this patch, run "git am --skip" instead.
hint: To restore the original branch and stop patching, run "git am --abort".
hint: Disable this message with "git config set advice.mergeConflict false"
Patch failed at 0009 Don't root the cancellation token source from the cached value task source
Error: The process '/usr/bin/git' failed with exit code 128 |

On Windows, an async
SafeFileHandlethat is not disposed explicitly can never be finalized after it has performed an async operation that completed through the IO completion callback. The same applies to asyncPipeStreams and theirSafePipeHandle.The handle caches a reusable
OverlappedValueTaskSource, which is rooted by itsPreAllocatedOverlapped(a strongGCHandlefor the portable thread pool, the statics_dataArrayfor the Windows thread pool) untilSafeFileHandle.ReleaseHandledisposes it. The cached instance kept a reference back to theSafeFileHandle, so the handle stayed reachable andReleaseHandlenever ran. The problem has existed since .NET 6, but #125643 made it common: the parent end of redirected stdout/stderr is now opened for async IO, andProcessdoesn't dispose readers handed out to the caller. See #137501 (comment) for the details.PipeStreamon Windows has the same cycle: the cachedPipeValueTaskSource(read, write and connection) is rooted by itsPreAllocatedOverlappedand referenced thePipeStream, so aPipeStreamthat was not disposed, together with itsSafePipeHandle, could never be collected.Changes
OverlappedValueTaskSourceandPipeValueTaskSourceno longer reference theSafeFileHandle/PipeStreamwhile they are cached. The reference is set again when the instance is rented. There is no extra allocation.PipeValueTaskSourceinstances are now disposed also when the pipe stream is finalized (NamedPipeServerStream,NamedPipeClientStreamand the anonymous pipe streams have finalizers that callDispose(false)). Previously,PipeStream.DisposeCoredisposed them only when disposing explicitly, so once the stream could be finalized, they would stay rooted by theirPreAllocatedOverlappedforever.NamedPipeServerStreamalready disposed its cached connection source on both paths. An instance used by an in-flight operation references the stream, so the finalizer can only dispose idle instances.CancellationTokenRegistrationof its last operation. The registration references theCancellationTokenSourceand all of its other registrations, so a registration that references the stream (for exampletoken.Register(() => stream.Dispose())) kept the stream and its handle reachable. The registration is cleared when the instance is returned for reuse, not earlier, soOperationCanceledExceptionstill carries the token.GetResultreturns the instance for reuse only when it consumed the result of a completed operation (token == _source.Version && _source.GetStatus(token) != ValueTaskSourceStatus.Pending). Getting a stale result (when the instance may already be used by another operation, for example a concurrentRandomAccesscall on the same handle) or getting the result of an operation that is still in progress (for exampleValueTask.Resulton a pending operation) keeps throwing the sameInvalidOperationException, and no longer resets or clears an instance used by an in-flight operation (which, after clearing the back-reference, would throwNullReferenceExceptionin the IO completion callback).PipeValueTaskSourceusesPreAllocatedOverlapped.UnsafeCreate, likeSafeFileHandledoes. Previously, theExecutionContextcaptured when the instance was created (including allAsyncLocalvalues) was kept alive for as long as the instance and used to run every completion callback. Continuations still flow the awaiter'sExecutionContextthroughManualResetValueTaskSourceCore.Tests
ProcessTests.RedirectedOutputHandlesAreFinalizedAfterAsyncReads(Windows): reads redirected stdout/stderr of a child process asynchronously without disposing the readers, and verifies that both handles get finalized.FileStream_Dispose.PipeHandlesAreFinalizedWhenNotDisposed(Windows): performs IO withReadAsync/WriteAsynconFileStreams wrapping a pipe created withSafeFileHandle.CreateAnonymousPipe, without disposing them, and verifies that both handles get finalized.NamedPipeTest_Specific.PipeHandlesAreFinalizedWhenNotDisposed(Windows): the same for a connectedNamedPipeServerStream/NamedPipeClientStreampair.RandomAccess_ReadAsync.GettingResultOfPendingOrConsumedValueTaskThrowsInvalidOperationExceptionandNamedPipeTest_Specific.GettingResultOfPendingOrConsumedValueTaskThrowsInvalidOperationException(Windows): verify that getting the result of a pendingValueTask, and of an already consumedValueTaskwhose source is used by another pending read, throwsInvalidOperationException, and that both reads complete successfully.NamedPipeTest_Specific.AsyncOperationsDoNotRetainExecutionContext(Windows): verifies that anAsyncLocalvalue present when the first async read and write were performed is not kept alive by the pipe streams.Both
PipeHandlesAreFinalizedWhenNotDisposedtheories cover all combinations of sync and async reads and writes, with and without aCancellationTokenthat has another registration capturing the stream. TheFileStreamtest is Windows-only, because on Unix the continuation of the write can run inline on the thread pool thread that performed it, soGC.Collectcan run while that work item still keeps the write handle alive.Validation (Windows x64, Release)
Each regression test was run against a build with and without the corresponding product change, using
dotnet build <test project> -c release /t:Test /p:XunitMethodName=<test>:ProcessTests.RedirectedOutputHandlesAreFinalizedAfterAsyncReadsFileStream_Dispose.PipeHandlesAreFinalizedWhenNotDisposed(async read and write)NamedPipeTest_Specific.PipeHandlesAreFinalizedWhenNotDisposed(async read and write)PipeHandlesAreFinalizedWhenNotDisposedtheoriesExecutionContextNamedPipeTest_Specific.AsyncOperationsDoNotRetainExecutionContextThe two
GettingResultOfPendingOrConsumedValueTaskThrowsInvalidOperationExceptiontests passed with all the changes; they were not run without them. The change that disposes the cachedPipeValueTaskSourceinstances on finalization has no dedicated test, as observing the cached instances would require reflection over private fields; the fullSystem.IO.Pipestest suite passed with it (1390 total, 0 failed, 2 skipped).Full test suites:
dotnet build src\libraries\System.IO.Pipes\tests\System.IO.Pipes.Tests.csproj -c release /t:Testdotnet build src\libraries\System.Runtime\tests\System.IO.FileSystem.Tests\System.IO.FileSystem.Tests.csproj -c release /t:TestJunctionstests (the machine can't create symbolic links) andMountVolumetests (require admin) (before theUnsafeCreatechange and the last test changes)Resolves #137501
Note
This PR description was generated with the help of GitHub Copilot.