Files
romanett 014f99a53a WebSocket transport: a sender queued across Close fails as closed (#4832)
## Problem


`WebSocketByteTransportTests.CloseFailsQueuedSendInsteadOfOrphaningItAsync`
fails intermittently. One example is test-linux-net10.0 (3/16) in run
39114639155 on #4831, an unrelated MachineTool change. The queued send
failed with a raw `WebSocketException` ("…transitioned into an invalid
state") instead of `ServiceResultException` with `BadConnectionClosed`.

## Cause

This is a product race in `WebSocketByteTransportBase`.

- `Close()` cancels the shared send token. That wakes both the in-flight
send and the queued `SemaphoreSlim.WaitAsync`.
- `SemaphoreSlim` removes a cancelled waiter on a later continuation. If
the in-flight sender's `finally` releases the lock first, the release
*grants* the queued waiter despite its cancelled token.
- `EnterSendAsync` then returned normally, and the queued sender called
`SendAsync` on the already aborted socket.
- That socket error is not an `OperationCanceledException`, so it
reached the caller untranslated.

## Fix

After acquiring the lock, `EnterSendAsync` checks whether the transport
closed. If it did, it gives the lock back and throws
`BadConnectionClosed`. `Close()` sets the closed flag before it cancels,
so every waiter woken by `Close()` sees it.

## Tests

- The existing test body moved into a helper. New
`CloseFailsQueuedSendEvenWhenTheLockIsGrantedAsync` repeats the
interleaving 2000 times (about 140 ms).
- Without the fix it fails 3/3 runs within about 100 ms, with the CI
exception. With the fix it passes 3/3.
- `Opc.Ua.Core.Tests` `~WebSocket` (net10.0): 39/39 passed.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 12:37:56 +00:00
..