From 9d080237802fe3b0aa2dc29356a906dd0a0cf421 Mon Sep 17 00:00:00 2001 From: Damian Horna Date: Wed, 2 Sep 2026 15:36:25 +0200 Subject: [PATCH 1/3] Stop sending after a partial frame write LengthPrefixCommunicationChannel writes each message as a 7-bit encoded byte count followed by the payload, through a BufferedStream. A payload larger than the free buffer space forces the buffered prefix out first, so a write that fails part way through can leave the prefix on the wire without its body. Send logged that error and left the channel usable. Callers that swallow CommunicationException, such as the timer-driven cache flush, keep sending, and the receiver reads the next message inside the frame the previous one never finished. A captured trace shows the whole sequence. A 33,185 byte StatsChange flushes its 3 byte prefix a1 83 02, then the payload write fails with SocketException 10038. 126 ms later another thread sends a 38,382 byte message with prefix ee ab 02. The receiver consumes 33,185 bytes, which is the second message's prefix plus the first 33,182 bytes of its payload, decodes ee ab as U+FFFD and 02 as U+0002, and aborts with "Unexpected character encountered while parsing value" at line 0, position 0. Latch the first send failure, dispose the stream so the peer sees a disconnect rather than a shifted frame, and reject later sends. Skip BinaryWriter.Dispose after a failure because it flushes the BufferedStream and can re-emit bytes of the incomplete frame. Run the whole Send body under the write lock so a concurrent send cannot pass the latch check and then write. Dispose takes the write lock with Monitor.TryEnter rather than waiting for it. Waiting would block shutdown behind a stuck socket write, which is what happens today: with an in-flight write held open, the existing Dispose blocks until that write completes because BinaryWriter.Dispose flushes the BufferedStream underneath it. Skipping the flush when the lock is busy is safe, since Send flushes every message. Shutdown behavior is otherwise unchanged. Send after Dispose still writes, and the NotSupportedException tolerance for an owner-disposed stream stays. Add regression tests for a prefix-only write, disposal after a buffered failure, a concurrent send queued behind a failing one, and disposal racing an in-flight send. All four fail on unmodified main. A fifth test pins the existing post-Dispose behavior so this change cannot alter it silently. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9e03d8a7-a869-4ca9-ab36-45529635e316 --- .../LengthPrefixCommunicationChannel.cs | 82 ++++++-- .../LengthPrefixCommunicationChannelTests.cs | 185 ++++++++++++++++++ 2 files changed, 248 insertions(+), 19 deletions(-) diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/LengthPrefixCommunicationChannel.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/LengthPrefixCommunicationChannel.cs index ba99d29394..063a7390d3 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/LengthPrefixCommunicationChannel.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/LengthPrefixCommunicationChannel.cs @@ -18,10 +18,14 @@ namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities; /// public class LengthPrefixCommunicationChannel : ICommunicationChannel { + private readonly Stream _stream; + private readonly BinaryReader _reader; private readonly BinaryWriter _writer; + private Exception? _sendFailure; + /// /// Sync object for sending messages /// Write for binarywriter is NOT thread-safe @@ -30,6 +34,7 @@ public class LengthPrefixCommunicationChannel : ICommunicationChannel public LengthPrefixCommunicationChannel(Stream stream) { + _stream = stream; _reader = new BinaryReader(stream, Encoding.UTF8, true); // Using the Buffered stream while writing, improves the write performance. By reducing the number of writes. @@ -42,29 +47,47 @@ public LengthPrefixCommunicationChannel(Stream stream) /// public Task Send(string data) { - try + // Writing Message on binarywriter is not Thread-Safe + // Need to sync one by one to avoid buffer corruption + lock (_writeSyncObject) { - // Writing Message on binarywriter is not Thread-Safe - // Need to sync one by one to avoid buffer corruption - lock (_writeSyncObject) + if (_sendFailure is not null) + { + throw new CommunicationException("Unable to send data over channel because a previous send failed.", _sendFailure); + } + + try { _writer.Write(data); _writer.Flush(); } - } - catch (NotSupportedException ex) when (!_writer.BaseStream.CanWrite) - { - // As we are simply creating streams around some stream passed as ctor argument, we - // end up in some unsynchronized behavior where it's possible that the outside stream - // was disposed and we are still trying to write something. In such case we would fail - // with "System.NotSupportedException: Stream does not support writing.". - // To avoid being too generic in that catch, I am checking if the stream is not writable. - EqtTrace.Verbose("LengthPrefixCommunicationChannel.Send: BaseStream is not writable (most likely it was dispose). {0}", ex); - } - catch (Exception ex) - { - EqtTrace.Error("LengthPrefixCommunicationChannel.Send: Error sending data: {0}.", ex); - throw new CommunicationException("Unable to send data over channel.", ex); + catch (NotSupportedException ex) when (!_stream.CanWrite) + { + // As we are simply creating streams around some stream passed as ctor argument, we + // end up in some unsynchronized behavior where it's possible that the outside stream + // was disposed and we are still trying to write something. In such case we would fail + // with "System.NotSupportedException: Stream does not support writing.". + // To avoid being too generic in that catch, I am checking if the stream is not writable. + EqtTrace.Verbose("LengthPrefixCommunicationChannel.Send: Stream is not writable (most likely it was disposed). {0}", ex); + } + catch (Exception ex) + { + _sendFailure = ex; + + try + { + // A failed write may have left a length prefix or a partial payload on the wire. + // Close the stream before another send can reuse the broken frame boundary. + _stream.Dispose(); + } + catch (Exception disposeException) + { + EqtTrace.Error("LengthPrefixCommunicationChannel.Send: Error closing stream after send failure: {0}.", disposeException); + } + + EqtTrace.Error("LengthPrefixCommunicationChannel.Send: Error sending data: {0}.", ex); + throw new CommunicationException("Unable to send data over channel.", ex); + } } return Task.CompletedTask; @@ -107,16 +130,37 @@ public Task NotifyDataAvailable(CancellationToken cancellationToken) /// public void Dispose() { + // Dispose can run while another thread is inside Send. Take the write lock when it is + // free, so disposal never flushes the writer mid-frame, but never wait for it: blocking + // here would turn a stuck socket write into a shutdown hang. + var lockTaken = false; try { + Monitor.TryEnter(_writeSyncObject, ref lockTaken); + EqtTrace.Verbose("LengthPrefixCommunicationChannel.Dispose: Dispose reader and writer."); _reader.Dispose(); - _writer.Dispose(); + + // BinaryWriter.Dispose flushes its BufferedStream. Skip that flush after a failed + // send, where the buffer can still hold part of an incomplete frame that must not + // reach the peer, and skip it while a send holds the lock, to avoid racing that + // writer. Neither skip loses data: Send flushes after every message it completes. + if (lockTaken && _sendFailure is null) + { + _writer.Dispose(); + } } catch (ObjectDisposedException) { // We don't own the underlying stream lifecycle so it's possible that it's already disposed. } + finally + { + if (lockTaken) + { + Monitor.Exit(_writeSyncObject); + } + } GC.SuppressFinalize(this); } diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/LengthPrefixCommunicationChannelTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/LengthPrefixCommunicationChannelTests.cs index 92d65f9115..0a8cb521b2 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/LengthPrefixCommunicationChannelTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/LengthPrefixCommunicationChannelTests.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; +using System.Diagnostics; using System.IO; using System.Threading; using System.Threading.Tasks; @@ -25,6 +26,8 @@ public class LengthPrefixCommunicationChannelTests : IDisposable private readonly BinaryWriter _writer; + public TestContext TestContext { get; set; } = null!; + public LengthPrefixCommunicationChannelTests() { _stream = new MemoryStream(); @@ -120,6 +123,31 @@ public void DisposeShouldNotCloseTheStream() Assert.IsTrue(_stream.CanWrite); } + /// + /// Characterization test: it passes on main unchanged, and it passes here. It asserts no new + /// behavior and claims no documented guarantee. Two implementation details combine to let a + /// send after Dispose still reach the stream. BinaryWriter does not track its own disposal, so + /// Write has nothing to reject, and the writer holds the stream with leaveOpen, so disposing + /// the writer flushes rather than closing the stream underneath it. Shutdown leans on the + /// resulting tolerance, because Dispose runs while timer driven sends are still in flight. + /// Pinning it here means a future change surfaces as a failing test rather than as a silent + /// change to shutdown. + /// + [TestMethod] + public async Task SendAfterDisposeShouldStillWriteToTheStream() + { + using var stream = new MemoryStream(); + var channel = new LengthPrefixCommunicationChannel(stream); + channel.Dispose(); + + await channel.Send(Dummydata); + + Assert.IsTrue(stream.CanWrite); + SeekToBeginning(stream); + using var reader = new BinaryReader(stream); + Assert.AreEqual(Dummydata, reader.ReadString()); + } + [TestMethod] public async Task DoNotFailWhenWritingOnADisposedBaseStream() { @@ -138,6 +166,90 @@ public async Task DoNotFailWhenReadingFromADisposedBaseStream() await _channel.NotifyDataAvailable(new CancellationToken()); } + [TestMethod] + public async Task SendShouldCloseStreamAndRejectLaterMessagesAfterPartialFrame() + { + using var stream = new FailingWriteStream(bytesBeforeFailure: 3); + var channel = new LengthPrefixCommunicationChannel(stream); + var message = new string('x', SocketConstants.BufferSize + 1); + + await Assert.ThrowsExactlyAsync(() => channel.Send(message)); + + Assert.HasCount(3, stream.WrittenBytes); + using (var prefixStream = new MemoryStream(stream.WrittenBytes)) + using (var prefixReader = new BinaryReader(prefixStream)) + { + Assert.AreEqual(message.Length, Read7BitEncodedInt(prefixReader)); + } + + var writeCallCount = stream.WriteCallCount; + await Assert.ThrowsExactlyAsync(() => channel.Send(Dummydata)); + + Assert.IsTrue(stream.IsDisposed); + Assert.AreEqual(writeCallCount, stream.WriteCallCount); + Assert.HasCount(3, stream.WrittenBytes); + } + + [TestMethod] + public async Task DisposeShouldNotFlushBufferedDataAfterSendFailure() + { + using var stream = new FailingWriteStream(bytesBeforeFailure: 0); + var channel = new LengthPrefixCommunicationChannel(stream); + + await Assert.ThrowsExactlyAsync(() => channel.Send(Dummydata)); + var writeCallCount = stream.WriteCallCount; + + channel.Dispose(); + + Assert.AreEqual(writeCallCount, stream.WriteCallCount); + } + + [TestMethod] + public async Task ConcurrentSendShouldNotWriteAfterFirstSendFails() + { + using var stream = new FailingWriteStream(bytesBeforeFailure: 3, blockFirstWrite: true); + var channel = new LengthPrefixCommunicationChannel(stream); + var message = new string('x', SocketConstants.BufferSize + 1); + + var firstSend = Task.Run(() => channel.Send(message), TestContext.CancellationToken); + Assert.IsTrue(stream.WriteStarted.Wait(TimeSpan.FromSeconds(5), TestContext.CancellationToken)); + + var secondSend = Task.Run(() => channel.Send(Dummydata), TestContext.CancellationToken); + await Task.Delay(50, TestContext.CancellationToken); + Assert.IsFalse(secondSend.IsCompleted); + + stream.ReleaseWrite.Set(); + + await Assert.ThrowsExactlyAsync(() => firstSend); + await Assert.ThrowsExactlyAsync(() => secondSend); + Assert.IsTrue(stream.IsDisposed); + Assert.AreEqual(1, stream.WriteCallCount); + } + + [TestMethod] + public async Task DisposeShouldNeitherWriteNorBlockWhileASendIsInFlight() + { + using var stream = new FailingWriteStream(bytesBeforeFailure: 3, blockFirstWrite: true); + var channel = new LengthPrefixCommunicationChannel(stream); + var message = new string('x', SocketConstants.BufferSize + 1); + + var send = Task.Run(() => channel.Send(message), TestContext.CancellationToken); + Assert.IsTrue(stream.WriteStarted.Wait(TimeSpan.FromSeconds(5), TestContext.CancellationToken)); + + var writeCallCount = stream.WriteCallCount; + var stopwatch = Stopwatch.StartNew(); + channel.Dispose(); + stopwatch.Stop(); + + // The in-flight write is held for up to five seconds. Disposal must not wait for it, + // and must not flush the writer underneath it. + Assert.IsLessThan(TimeSpan.FromSeconds(2), stopwatch.Elapsed, $"Dispose blocked for {stopwatch.Elapsed}."); + Assert.AreEqual(writeCallCount, stream.WriteCallCount); + + stream.ReleaseWrite.Set(); + await Assert.ThrowsExactlyAsync(() => send); + } + // TODO // WriteFromMultilpleThreadShouldBeInSequence private static void SeekToBeginning(Stream stream) @@ -173,4 +285,77 @@ private static int Read7BitEncodedInt(BinaryReader reader) return count; } + + private sealed class FailingWriteStream : MemoryStream + { + private readonly int _bytesBeforeFailure; + private readonly bool _blockFirstWrite; + + private int _acceptedBytes; + private bool _failureInjected; + + public FailingWriteStream(int bytesBeforeFailure, bool blockFirstWrite = false) + { + _bytesBeforeFailure = bytesBeforeFailure; + _blockFirstWrite = blockFirstWrite; + } + + public bool IsDisposed { get; private set; } + + public int WriteCallCount { get; private set; } + + public byte[] WrittenBytes => ToArray(); + + public ManualResetEventSlim WriteStarted { get; } = new(false); + + public ManualResetEventSlim ReleaseWrite { get; } = new(false); + + public override void Write(byte[] buffer, int offset, int count) + { + if (IsDisposed) + { + throw new ObjectDisposedException(nameof(FailingWriteStream)); + } + + WriteCallCount++; + WriteStarted.Set(); + if (!_failureInjected) + { + if (_blockFirstWrite && !ReleaseWrite.Wait(TimeSpan.FromSeconds(5))) + { + throw new TimeoutException("Timed out waiting to release the injected write failure."); + } + + _failureInjected = true; + var remainingBytes = _bytesBeforeFailure - _acceptedBytes; + if (remainingBytes > 0) + { + var acceptedCount = Math.Min(remainingBytes, count); + base.Write(buffer, offset, acceptedCount); + _acceptedBytes += acceptedCount; + } + + throw new IOException("Injected write failure."); + } + + base.Write(buffer, offset, count); + } + + protected override void Dispose(bool disposing) + { + if (IsDisposed) + { + return; + } + + IsDisposed = true; + if (disposing) + { + WriteStarted.Dispose(); + ReleaseWrite.Dispose(); + } + + base.Dispose(disposing); + } + } } From d25b1b8d609093123b8f09a640afc594eecdf528 Mon Sep 17 00:00:00 2001 From: Damian Horna Date: Sun, 6 Sep 2026 23:32:22 +0200 Subject: [PATCH 2/3] Assert the corruption at the peer, not just at the sender Every test here so far checks what the sender does after a failed frame: that it stops writing, that Dispose does not flush, that a queued send is rejected. None of them check the thing that actually broke, which is what the peer decodes off the wire. PeerShouldNotDecodeAMessageThatWasNeverSent puts a real channel on both ends. The first send fails once its length prefix has been flushed, the second send lands behind that orphaned prefix, and the peer is then asked to read one message. On unmodified main it decodes 16,385 characters beginning U+FFFD U+FFFD U+0001, a frame that neither send produced, which is the JSON abort as the receiver experiences it. With this change the second send never reaches the wire and the peer has no complete frame to read. Pure addition; no existing test is modified. --- .../LengthPrefixCommunicationChannelTests.cs | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/LengthPrefixCommunicationChannelTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/LengthPrefixCommunicationChannelTests.cs index 0a8cb521b2..5ff0630a70 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/LengthPrefixCommunicationChannelTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/LengthPrefixCommunicationChannelTests.cs @@ -190,6 +190,78 @@ public async Task SendShouldCloseStreamAndRejectLaterMessagesAfterPartialFrame() Assert.HasCount(3, stream.WrittenBytes); } + /// + /// The corruption this change prevents, asserted at the peer instead of at the sender. A send + /// that fails once its length prefix has reached the peer leaves a frame header on the wire + /// promising a body that never arrives. On unmodified main the next message is consumed as that + /// body, and the peer decodes a string nobody ever sent, which is where the + /// "Unexpected character encountered while parsing value" JSON abort comes from. Every other + /// test here asserts what the sender does; this one asserts what the peer can observe. + /// + [TestMethod] + public async Task PeerShouldNotDecodeAMessageThatWasNeverSent() + { + var message1 = new string('a', SocketConstants.BufferSize + 1); + var message2 = new string('b', SocketConstants.BufferSize + 1); + + // The payload does not fit in what is left of the buffer, so the length prefix is flushed as + // its own write and reaches the peer before the payload write fails. + using var wire = new FailingWriteStream(bytesBeforeFailure: 3); + var sender = new LengthPrefixCommunicationChannel(wire); + + await Assert.ThrowsExactlyAsync(() => sender.Send(message1)); + + try + { + // The injected failure fires once, so on unmodified main this second message is written + // and lands directly behind the orphaned prefix. + await sender.Send(message2); + } + catch (CommunicationException) + { + // Expected once the channel refuses to send after a failed frame. + } + + var received = ReadFirstMessageFromWire(wire.WrittenBytes); + + var decoded = received is null ? string.Empty : DescribeFirstChars(received); + Assert.IsNull( + received, + $"The peer decoded a {received?.Length ?? 0} character frame that was never sent as a message, starting {decoded}."); + } + + private static string? ReadFirstMessageFromWire(byte[] bytesOnTheWire) + { + using var peerStream = new MemoryStream(bytesOnTheWire); + using var peer = new LengthPrefixCommunicationChannel(peerStream); + + string? received = null; + peer.MessageReceived.Subscribe((sender, messageEventArgs) => received = messageEventArgs.Data); + + try + { + peer.NotifyDataAvailable(CancellationToken.None).GetAwaiter().GetResult(); + } + catch (EndOfStreamException) + { + // An incomplete frame is the correct outcome. The peer has nothing to act on. + } + + return received; + } + + private static string DescribeFirstChars(string value) + { + var count = Math.Min(3, value.Length); + var parts = new string[count]; + for (var i = 0; i < count; i++) + { + parts[i] = $"U+{(int)value[i]:X4}"; + } + + return string.Join(" ", parts); + } + [TestMethod] public async Task DisposeShouldNotFlushBufferedDataAfterSendFailure() { From f7e172d7827097114181bac40e98bfecf088f1c2 Mon Sep 17 00:00:00 2001 From: Damian Horna Date: Mon, 7 Sep 2026 00:28:00 +0200 Subject: [PATCH 3/3] Extract the failure path into FaultChannel and document why it closes the stream The catch block carried the whole policy with no explanation of the part that needs one: why a channel that deliberately does not own its stream closes it here. Moving it to a named method puts that policy in one place and gives the reasoning somewhere to live. No behavior change. The trace messages are unchanged so existing diagnostics still match. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9e03d8a7-a869-4ca9-ab36-45529635e316 --- .../LengthPrefixCommunicationChannel.cs | 52 ++++++++++++++----- 1 file changed, 38 insertions(+), 14 deletions(-) diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/LengthPrefixCommunicationChannel.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/LengthPrefixCommunicationChannel.cs index 063a7390d3..89c4743727 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/LengthPrefixCommunicationChannel.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/LengthPrefixCommunicationChannel.cs @@ -72,20 +72,7 @@ public Task Send(string data) } catch (Exception ex) { - _sendFailure = ex; - - try - { - // A failed write may have left a length prefix or a partial payload on the wire. - // Close the stream before another send can reuse the broken frame boundary. - _stream.Dispose(); - } - catch (Exception disposeException) - { - EqtTrace.Error("LengthPrefixCommunicationChannel.Send: Error closing stream after send failure: {0}.", disposeException); - } - - EqtTrace.Error("LengthPrefixCommunicationChannel.Send: Error sending data: {0}.", ex); + FaultChannel(ex); throw new CommunicationException("Unable to send data over channel.", ex); } } @@ -93,6 +80,43 @@ public Task Send(string data) return Task.CompletedTask; } + /// + /// Marks the channel unusable after a failed write, and closes the transport. + /// + /// + /// + /// does not report how many bytes it wrote, so once it + /// throws we cannot know whether the length prefix reached the peer without its payload. If it + /// did, the peer is waiting for a body that will never arrive, and every later message would be + /// consumed as part of that frame. + /// + /// + /// There is no way to tell the peer in band, because the framing it is reading is the thing that + /// broke. Closing the transport is the only signal left: the peer reads end of stream, which it + /// already handles. + /// + /// + /// Both callers, SocketClient and SocketServer, build this channel over a TcpClient stream and + /// close that client in their own error paths, so this closes a stream that was already on its + /// way down. Dispose still leaves the stream open, which DisposeShouldNotCloseTheStream pins. + /// + /// + private void FaultChannel(Exception ex) + { + _sendFailure = ex; + + try + { + _stream.Dispose(); + } + catch (Exception disposeException) + { + EqtTrace.Error("LengthPrefixCommunicationChannel.Send: Error closing stream after send failure: {0}.", disposeException); + } + + EqtTrace.Error("LengthPrefixCommunicationChannel.Send: Error sending data: {0}.", ex); + } + /// public Task NotifyDataAvailable(CancellationToken cancellationToken) {