Fix WebSocket close single-consumer violation #127183
Merged
MihaZupan merged 3 commits intodotnet:mainfrom May 7, 2026
Merged
Conversation
When a user has a pending ReceiveAsync and calls CloseAsync over an
HTTP/2 WebSocket (RFC 8441), two code paths could both reach
WaitForServerToCloseConnectionAsync and each issue a ReadAsync on the
underlying Http2Stream:
1. HandleReceivedCloseAsync (line 1122) — inside the receive loop;
holds _receiveMutex.
2. SendCloseFrameAsync (line 1566) — after sending the close frame;
does not hold _receiveMutex.
Both paths gate on _sentCloseFrame and _receivedCloseFrame respectively.
In rare concurrent Close + Receive scenarios the two flags are set
near-simultaneously, both checks pass, and both paths try to read from
the stream. Http2Stream enforces a single-consumer invariant and trips
Debug.Assert(!_hasWaiter), crashing the test process.
The scenario is explicitly listed as supported in the class-level
thread-safety contract:
/// - It's acceptable to have a pending ReceiveAsync while
/// CloseOutputAsync or CloseAsync is called.
Guard WaitForServerToCloseConnectionAsync with an Interlocked flag so
that only the first caller performs the wait; the other is a no-op.
This preserves RFC 6455 section 7.1.1 behavior (the wait still runs
exactly once), introduces no lock acquisition, and has no reentrancy
or lock-order implications.
Also clarify the long-stale comment in the test that exercises this
contract — the original attributed the OperationCanceledException path
to CloseAsync "receiving" the close frame, which is imprecise. The
exception originates from ReceiveAsyncPrivate's catch block when the
socket becomes Aborted during the close handshake (e.g. a 1s timeout
in WaitForServerToCloseConnectionAsync triggers Abort).
Contributor
|
Tagging subscribers to this area: @karelz, @dotnet/ncl |
This was referenced Apr 21, 2026
MihaZupan
requested changes
Apr 28, 2026
Member
MihaZupan
left a comment
There was a problem hiding this comment.
Thank you for looking into this!
I don't think the current change is a complete fix.
Move the client EOF wait out of SendCloseFrameAsync so send-side close paths acquire the receive mutex before issuing the final stream read. This prevents CloseAsync or CloseOutputAsync from racing a pending receive loop on the underlying transport after a close frame has already been observed. Keep the existing one-shot guard so the EOF wait is still performed at most once when both close paths reach the completed handshake state sequentially.
MihaZupan
reviewed
Apr 29, 2026
MihaZupan
reviewed
Apr 29, 2026
MihaZupan
reviewed
Apr 29, 2026
This was referenced Apr 30, 2026
Open
MihaZupan
approved these changes
May 6, 2026
Member
MihaZupan
left a comment
There was a problem hiding this comment.
Thanks.
I'm trying to think if there's any reason not to change CloseAsyncPrivate to do the EOF wait after waiting for the close frame, instead of only if we've already seen it, but can't think of any right now.
Member
|
/azp run runtime-libraries-coreclr outerloop |
|
Azure Pipelines successfully started running 1 pipeline(s). |
Member
|
/ba-g Infra timeouts. I'm not seeing any WebSocket outerloop failures |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Fixes #121157 and the likely related #117267 tracking the same assertion.
Serializes the client-side RFC 6455 7.1.1 EOF wait behind
_receiveMutexso the close path cannot issue a transport read while a pending receive is still reading from the same stream. This avoids theHttp2Stream.TryReadFromBufferDebug.Assert(!_hasWaiter)failure under concurrentCloseAsyncplus pendingReceiveAsyncscenarios over HTTP/2 (RFC 8441).Root cause
WaitForServerToCloseConnectionAsyncissues a_stream.ReadAsyncfor the RFC 6455 7.1.1 "client waits for server TCP close" step.There are two ways the close handshake can reach that wait:
HandleReceivedCloseAsync. This path already runs while_receiveMutexis held.SendCloseFrameAsync, which does not hold_receiveMutex.A CAS-only guard avoids two completed calls to
WaitForServerToCloseConnectionAsync, but it does not cover the wider race where the receive loop has already set_receivedCloseFrameand is still reading or parsing the close payload. In that window,SendCloseFrameAsynccould observe_receivedCloseFrameand issue the EOF wait as a second read on the transport.Over HTTP/1.1 the behavior is still wrong but historically tolerated by error handling. Over HTTP/2,
Http2Stream.Http2ReadWriteStreamenforces a single-consumer read invariant and can tripDebug.Assert(!_hasWaiter).The supported scenario is called out in the class-level thread-safety contract:
Fix
Move the EOF wait out of
SendCloseFrameAsyncand into callers that can coordinate with the receive side:HandleReceivedCloseAsyncstill callsWaitForServerToCloseConnectionAsyncwhile already holding_receiveMutex.CloseAsyncPrivateandCloseOutputAsyncCoreacquire_receiveMutexbefore performing the EOF wait.CloseWithReceiveErrorAndThrowAsyncalready runs under_receiveMutex, so it bypassesCloseOutputAsyncCoreand callsSendCloseFrameAsyncdirectly to avoid re-entering the receive mutex._waitedForServerCloseremains as a one-shot guard so the EOF wait is not repeated sequentially if more than one close path reaches the completed handshake state.Behavior preserved
Test-side comment clarification
The test that exercises this contract,
RunClient_CloseAsync_DuringConcurrentReceiveAsync_ExpectedStatesinCloseTest.cs, had a stale comment that misattributed whereOperationCanceledExceptioncomes from in the abort branch. The comment now describes the acceptable outcomes and where the exception originates:ReceiveAsyncPrivatetranslates a stream exception toOperationCanceledExceptionwhen_state == Aborted.No test logic is changed.
Note for reviewers about work item visibility
I'm a community contributor and do not have access to the work-item logs for #121157 / #117267. I identified the likely failing path by reading the code:
WaitForServerToCloseConnectionAsyncrunning underHttp2Stream.CloseAsync_DuringConcurrentReceiveAsync_ExpectedStatesunder theCloseTest_*_Http2Loopbackclasses matches the scenario.If a reviewer can confirm from the actual work-item logs that this test is the one triggering the assertion, I'll reference the run in this PR.
Local verification
Before the review update:
./build.cmd -subset libs -c Release): clean.System.Net.WebSockets.Client.Testsbuild: clean.CloseTest_Invoker_Http2Loopback.CloseAsync_DuringConcurrentReceiveAsync_ExpectedStates(bothuseSslvalues)CloseTest_HttpClient_Http2Loopback.CloseAsync_DuringConcurrentReceiveAsync_ExpectedStates(bothuseSslvalues)CloseTest*regression run (no new failures)The latest receive-mutex follow-up was reviewed locally but not re-run.