From 01dd43217ef31c0c5bcb9dc3ac4b61b39ac77255 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Fri, 5 Jun 2026 16:35:00 -0700 Subject: [PATCH] Fix flaky test: add sync point in ReadEventsAsync_InStreamingMode_YieldsNewlyWrittenEvents (#1491) --- .../Server/DistributedCacheEventStreamStoreTests.cs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/tests/ModelContextProtocol.Tests/Server/DistributedCacheEventStreamStoreTests.cs b/tests/ModelContextProtocol.Tests/Server/DistributedCacheEventStreamStoreTests.cs index 0983e6a..f306064 100644 --- a/tests/ModelContextProtocol.Tests/Server/DistributedCacheEventStreamStoreTests.cs +++ b/tests/ModelContextProtocol.Tests/Server/DistributedCacheEventStreamStoreTests.cs @@ -904,10 +904,16 @@ public class DistributedCacheEventStreamStoreTests(ITestOutputHelper testOutputH using var cts = CancellationTokenSource.CreateLinkedTokenSource(CancellationToken); cts.CancelAfter(TimeSpan.FromSeconds(10)); var events = new List>(); + + // Use a TCS as a sync point: set when the reader has confirmed receipt of the first event. + // This guarantees the streaming enumerator is definitely active before we write events 2 and 3. + var readerStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var readTask = Task.Run(async () => { await foreach (var evt in reader.ReadEventsAsync(cts.Token)) { + readerStarted.TrySetResult(true); events.Add(evt); if (events.Count >= 3) { @@ -916,8 +922,13 @@ public class DistributedCacheEventStreamStoreTests(ITestOutputHelper testOutputH } }, CancellationToken); - // Write 3 new events - the reader should pick them up since it's in streaming mode + // Write the first event and wait for the reader to confirm it has been received. + // This establishes a synchronization point: once readerStarted is signalled, we know + // the streaming loop is running and will reliably observe any subsequently written events. var event1 = await writer.WriteEventAsync(new SseItem(null), CancellationToken); + await readerStarted.Task.WaitAsync(cts.Token); + + // Write the remaining 2 events now that the reader is confirmed active var event2 = await writer.WriteEventAsync(new SseItem(null), CancellationToken); var event3 = await writer.WriteEventAsync(new SseItem(null), CancellationToken);