Skip to content

Fix leaks of undisposed async SafeFileHandle and PipeStream instances on Windows - #137507

Merged
adamsitnik merged 13 commits into
dotnet:mainfrom
adamsitnik:repro-137501-async-pipe-leak
Nov 16, 2026
Merged

adamsitnik merged 13 commits into
dotnet:mainfrom
adamsitnik:repro-137501-async-pipe-leak

Conversation

@adamsitnik

@adamsitnik adamsitnik commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

On Windows, an async SafeFileHandle that 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 async PipeStreams and their SafePipeHandle.

The handle caches a reusable OverlappedValueTaskSource, which is rooted by its PreAllocatedOverlapped (a strong GCHandle for the portable thread pool, the static s_dataArray for the Windows thread pool) until SafeFileHandle.ReleaseHandle disposes it. The cached instance kept a reference back to the SafeFileHandle, so the handle stayed reachable and ReleaseHandle never 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, and Process doesn't dispose readers handed out to the caller. See #137501 (comment) for the details.

PipeStream on Windows has the same cycle: the cached PipeValueTaskSource (read, write and connection) is rooted by its PreAllocatedOverlapped and referenced the PipeStream, so a PipeStream that was not disposed, together with its SafePipeHandle, could never be collected.

Changes

  • OverlappedValueTaskSource and PipeValueTaskSource no longer reference the SafeFileHandle/PipeStream while they are cached. The reference is set again when the instance is rented. There is no extra allocation.
  • The cached read and write PipeValueTaskSource instances are now disposed also when the pipe stream is finalized (NamedPipeServerStream, NamedPipeClientStream and the anonymous pipe streams have finalizers that call Dispose(false)). Previously, PipeStream.DisposeCore disposed them only when disposing explicitly, so once the stream could be finalized, they would stay rooted by their PreAllocatedOverlapped forever. NamedPipeServerStream already 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.
  • The cached instance no longer keeps the disposed CancellationTokenRegistration of its last operation. The registration references the CancellationTokenSource and all of its other registrations, so a registration that references the stream (for example token.Register(() => stream.Dispose())) kept the stream and its handle reachable. The registration is cleared when the instance is returned for reuse, not earlier, so OperationCanceledException still carries the token.
  • GetResult returns 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 concurrent RandomAccess call on the same handle) or getting the result of an operation that is still in progress (for example ValueTask.Result on a pending operation) keeps throwing the same InvalidOperationException, and no longer resets or clears an instance used by an in-flight operation (which, after clearing the back-reference, would throw NullReferenceException in the IO completion callback).
  • PipeValueTaskSource uses PreAllocatedOverlapped.UnsafeCreate, like SafeFileHandle does. Previously, the ExecutionContext captured when the instance was created (including all AsyncLocal values) was kept alive for as long as the instance and used to run every completion callback. Continuations still flow the awaiter's ExecutionContext through ManualResetValueTaskSourceCore.

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 with ReadAsync/WriteAsync on FileStreams wrapping a pipe created with SafeFileHandle.CreateAnonymousPipe, without disposing them, and verifies that both handles get finalized.
  • NamedPipeTest_Specific.PipeHandlesAreFinalizedWhenNotDisposed (Windows): the same for a connected NamedPipeServerStream/NamedPipeClientStream pair.
  • RandomAccess_ReadAsync.GettingResultOfPendingOrConsumedValueTaskThrowsInvalidOperationException and NamedPipeTest_Specific.GettingResultOfPendingOrConsumedValueTaskThrowsInvalidOperationException (Windows): verify that getting the result of a pending ValueTask, and of an already consumed ValueTask whose source is used by another pending read, throws InvalidOperationException, and that both reads complete successfully.
  • NamedPipeTest_Specific.AsyncOperationsDoNotRetainExecutionContext (Windows): verifies that an AsyncLocal value present when the first async read and write were performed is not kept alive by the pipe streams.

Both PipeHandlesAreFinalizedWhenNotDisposed theories cover all combinations of sync and async reads and writes, with and without a CancellationToken that has another registration capturing the stream. The FileStream test is Windows-only, because on Unix the continuation of the write can run inline on the thread pool thread that performed it, so GC.Collect can 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>:

Product change Test Without the change With the change
Don't reference the handle/stream while cached ProcessTests.RedirectedOutputHandlesAreFinalizedAfterAsyncReads failed (7/7 runs) passed
FileStream_Dispose.PipeHandlesAreFinalizedWhenNotDisposed (async read and write) failed passed
NamedPipeTest_Specific.PipeHandlesAreFinalizedWhenNotDisposed (async read and write) failed passed
Don't keep the cancellation registration both PipeHandlesAreFinalizedWhenNotDisposed theories the 2 async read + cancellable cases failed in each theory all 8 cases passed in each theory
Don't capture ExecutionContext NamedPipeTest_Specific.AsyncOperationsDoNotRetainExecutionContext failed passed

The two GettingResultOfPendingOrConsumedValueTaskThrowsInvalidOperationException tests passed with all the changes; they were not run without them. The change that disposes the cached PipeValueTaskSource instances on finalization has no dedicated test, as observing the cached instances would require reflection over private fields; the full System.IO.Pipes test suite passed with it (1390 total, 0 failed, 2 skipped).

Full test suites:

Command Result
dotnet build src\libraries\System.IO.Pipes\tests\System.IO.Pipes.Tests.csproj -c release /t:Test 1390 total, 0 failed, 2 skipped (before the last test changes)
dotnet build src\libraries\System.Runtime\tests\System.IO.FileSystem.Tests\System.IO.FileSystem.Tests.csproj -c release /t:Test 9885 total, 24 failed: Junctions tests (the machine can't create symbolic links) and MountVolume tests (require admin) (before the UnsafeCreate change and the last test changes)

Resolves #137501

Note

This PR description was generated with the help of GitHub Copilot.

…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

Copy link
Copy Markdown
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.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/area-system-io
See info in area-owners.md if you want to be subscribed.

@adamsitnik adamsitnik added this to the 12.0.0 milestone Nov 13, 2026
@adamsitnik
adamsitnik requested a review from jozkee November 13, 2026 20:26
…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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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 InvalidOperationException for repeated result retrieval from the same source-backed ValueTask.
  • 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
@adamsitnik adamsitnik changed the title Fix SafeFileHandle leak after async IO on Windows when the handle is not disposed Fix leaks of undisposed async SafeFileHandle and PipeStream instances on Windows Nov 16, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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

@stephentoub stephentoub left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Generated by Copilot

…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
@adamsitnik
adamsitnik enabled auto-merge (squash) November 16, 2026 18:06
@adamsitnik

Copy link
Copy Markdown
Member Author

/ba-g the test failure is unrelated (it happened on Azure Linux and here we have touched only Windows-specific part of the product)

@adamsitnik
adamsitnik merged commit e863295 into dotnet:main Nov 16, 2026
100 of 102 checks passed
@adamsitnik

Copy link
Copy Markdown
Member Author

/backport to release/11.0

@github-actions

Copy link
Copy Markdown
Contributor

Started backporting to release/11.0 (link to workflow run)

@github-actions

Copy link
Copy Markdown
Contributor

@adamsitnik backporting to release/11.0 failed, the patch most likely resulted in conflicts. Please backport manually!

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

Link to workflow output

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

3 participants