Skip to content

Fix WebSocket close single-consumer violation #127183

Merged
MihaZupan merged 3 commits intodotnet:mainfrom
cittaz:fix/websocket-http2-close-receive-race
May 7, 2026
Merged

Fix WebSocket close single-consumer violation #127183
MihaZupan merged 3 commits intodotnet:mainfrom
cittaz:fix/websocket-http2-close-receive-race

Conversation

@cittaz
Copy link
Copy Markdown
Contributor

@cittaz cittaz commented Apr 20, 2026

Summary

Fixes #121157 and the likely related #117267 tracking the same assertion.

Serializes the client-side RFC 6455 7.1.1 EOF wait behind _receiveMutex so the close path cannot issue a transport read while a pending receive is still reading from the same stream. This avoids the Http2Stream.TryReadFromBuffer Debug.Assert(!_hasWaiter) failure under concurrent CloseAsync plus pending ReceiveAsync scenarios over HTTP/2 (RFC 8441).

Root cause

WaitForServerToCloseConnectionAsync issues a _stream.ReadAsync for the RFC 6455 7.1.1 "client waits for server TCP close" step.

There are two ways the close handshake can reach that wait:

  1. The receive loop observes the peer close frame in HandleReceivedCloseAsync. This path already runs while _receiveMutex is held.
  2. The send-side close path sends our close frame after a peer close frame has already been observed. Previously this happened from 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 _receivedCloseFrame and is still reading or parsing the close payload. In that window, SendCloseFrameAsync could observe _receivedCloseFrame and 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.Http2ReadWriteStream enforces a single-consumer read invariant and can trip Debug.Assert(!_hasWaiter).

The supported scenario is called out in the class-level thread-safety contract:

/// - It's acceptable to have a pending ReceiveAsync while
///   CloseOutputAsync or CloseAsync is called.

Fix

Move the EOF wait out of SendCloseFrameAsync and into callers that can coordinate with the receive side:

  • HandleReceivedCloseAsync still calls WaitForServerToCloseConnectionAsync while already holding _receiveMutex.
  • CloseAsyncPrivate and CloseOutputAsyncCore acquire _receiveMutex before performing the EOF wait.
  • CloseWithReceiveErrorAndThrowAsync already runs under _receiveMutex, so it bypasses CloseOutputAsyncCore and calls SendCloseFrameAsync directly to avoid re-entering the receive mutex.
  • _waitedForServerClose remains 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

  • RFC 6455 7.1.1 "client waits for server TCP close" still runs at most once for a completed client close handshake.
  • No public API change.
  • No intended observable state-machine change.

Test-side comment clarification

The test that exercises this contract, RunClient_CloseAsync_DuringConcurrentReceiveAsync_ExpectedStates in CloseTest.cs, had a stale comment that misattributed where OperationCanceledException comes from in the abort branch. The comment now describes the acceptable outcomes and where the exception originates: ReceiveAsyncPrivate translates a stream exception to OperationCanceledException when _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:

  • The stack trace in System.Net.WebSockets.Client.Tests: Assertion failed: !_hasWaiter #121157 narrows the failure to WaitForServerToCloseConnectionAsync running under Http2Stream.
  • Combined with the "HTTP/2 WebSocket tests under Helix" context and the class-level thread-safety doc, the test CloseAsync_DuringConcurrentReceiveAsync_ExpectedStates under the CloseTest_*_Http2Loopback classes 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:

  • Full libraries build (./build.cmd -subset libs -c Release): clean.
  • System.Net.WebSockets.Client.Tests build: clean.
  • Targeted test runs:
    • CloseTest_Invoker_Http2Loopback.CloseAsync_DuringConcurrentReceiveAsync_ExpectedStates (both useSsl values)
    • CloseTest_HttpClient_Http2Loopback.CloseAsync_DuringConcurrentReceiveAsync_ExpectedStates (both useSsl values)
    • Full CloseTest* regression run (no new failures)

The latest receive-mutex follow-up was reviewed locally but not re-run.

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).
@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Apr 20, 2026
@dotnet-policy-service
Copy link
Copy Markdown
Contributor

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

Copy link
Copy Markdown
Member

@MihaZupan MihaZupan left a comment

Choose a reason for hiding this comment

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

Thank you for looking into this!
I don't think the current change is a complete fix.

Comment thread src/libraries/System.Net.WebSockets/src/System/Net/WebSockets/ManagedWebSocket.cs Outdated
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.
Comment thread src/libraries/System.Net.WebSockets/src/System/Net/WebSockets/ManagedWebSocket.cs Outdated
@cittaz cittaz requested a review from MihaZupan April 29, 2026 20:32
Comment thread src/libraries/System.Net.WebSockets/src/System/Net/WebSockets/ManagedWebSocket.cs Outdated
Copy link
Copy Markdown
Member

@MihaZupan MihaZupan left a comment

Choose a reason for hiding this comment

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

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.

@MihaZupan
Copy link
Copy Markdown
Member

/azp run runtime-libraries-coreclr outerloop

@MihaZupan MihaZupan added this to the 11.0.0 milestone May 6, 2026
@azure-pipelines
Copy link
Copy Markdown

Azure Pipelines successfully started running 1 pipeline(s).

@MihaZupan
Copy link
Copy Markdown
Member

/ba-g Infra timeouts. I'm not seeing any WebSocket outerloop failures

@MihaZupan MihaZupan merged commit ee4f930 into dotnet:main May 7, 2026
96 of 111 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-System.Net community-contribution Indicates that the PR has been added by a community member

Projects

None yet

Development

Successfully merging this pull request may close these issues.

System.Net.WebSockets.Client.Tests: Assertion failed: !_hasWaiter

2 participants