Fix WebSocket close single-consumer violation #127183
Fix WebSocket close single-consumer violation #127183cittaz wants to merge 3 commits intodotnet:mainfrom
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).
|
Tagging subscribers to this area: @karelz, @dotnet/ncl |
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.
| // Called from both the receive and the send path. In rare concurrent Close + Receive | ||
| // scenarios both paths can observe the close handshake as complete and would otherwise | ||
| // both issue a stream read (violating most Stream implementations' single-consumer invariant). | ||
| // The flag guarantees that only the first invocation performs the wait; the other is a no-op. | ||
| if (Interlocked.CompareExchange(ref _waitedForServerClose, 1, 0) != 0) | ||
| { | ||
| return; | ||
| } |
There was a problem hiding this comment.
I don't think this is a sufficient fix. From reading the code, there's a potentially large race condition window here where we've set _receivedCloseFrame but are still reading from the receive side, e.g. here before we call into WaitForServerToCloseConnectionAsync:
If the receive loop is busy in that EnsureBufferContainsAsync call, the SendCloseFrameAsync will issue a 2nd read on the transport.
I think a better fix would be to ensure that WaitForServerToCloseConnectionAsync is only called after the caller has acquired the read lock.
As you've called out already:
- When called from the receive side, it's while we're holding the mutex.
- When called from the send side, we're not ensuring that right now.
There was a problem hiding this comment.
Hi @MihaZupan,
You're right about the second edge case. I missed that part.
Acquiring _receiveMutex on that code path needs a bit more code to avoid re-entering the receive lock, so I pushed a follow-up change that moves the EOF wait out of SendCloseFrameAsync and into callers that can coordinate with the receive side.
I still kept _waitedForServerClose, since it avoids running the EOF wait twice sequentially. That case would not hit the HTTP/2 single-reader assertion anymore, but it could still waste up to 1 second on a duplicate wait.
Whenever you have time, could you re-review it?
Also, while digging into this, the close handling started feeling a bit non-intuitive to me, and I think there may be a second, separate behavior worth clarifying: messages can be consumed by CloseAsyncPrivate while it is waiting for the close frame inside CloseAsyncPrivate:
// Loop until we've received a close frame.
while (!_receivedCloseFrame)
{
...
receiveTask = ReceiveAsyncPrivate<ValueWebSocketReceiveResult>(closeBuffer, cancellationToken);
...
}The loop calls ReceiveAsyncPrivate into a local closeBuffer until _receivedCloseFrame is set. Any data frames the peer sends in the meantime get consumed by that internal receive and are not surfaced to the user. So if a user has a pending ReceiveAsync when CloseAsync is called, whether they observe those last frames depends on which receive loop wins the race.
I noticed the existing tests already point users toward CloseOutputAsync when they want to send a close frame and still receive data, and RFC 6455 section 5.5.1 also says there is no guarantee that an endpoint that has already sent a Close frame will continue to process data. So I'm not sure whether this current CloseAsync behavior is intentional and correct.
The part that still gives me some doubt is the class-level remark at ManagedWebSocket.cs#L25:
/// - It's acceptable to have a pending ReceiveAsync while CloseOutputAsync or CloseAsync is called.To me, "acceptable" reads as "supported and observable", but I'm not sure whether that interpretation is too strong for CloseAsync specifically.
Do you think the current behavior is intentional/correct? If it is, do you think it would be worth documenting or covering directly with a test? I'd be happy to keep this PR scoped down to the immediate fix you suggested in the meantime.
Thanks for the careful review!
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.
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.