From 96f8b70db602f94dacf918e7319c2ac659890cd9 Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Mon, 2 Nov 2026 00:27:24 +0000 Subject: [PATCH 1/9] Coalesce HangDump activity signals instead of one IPC round trip per test The test host awaited an ActivitySignalRequest round trip to the controller for every non-in-progress test node update. The controller only uses the signal to reset its inactivity timer, so a background loop now forwards pending activity at most once per interval (a tenth of the hang timeout, between 10 ms and 1 s). Coalescing only delays the latest signal, so a dump can fire at most one interval later than configured, never earlier. Co-Authored-By: Claude --- .../HangDumpActivityIndicator.cs | 107 +++++++++++++++--- .../HangDumpOptions.cs | 8 ++ .../HangDumpProcessLifetimeHandler.cs | 4 +- .../InternalAPI/InternalAPI.Unshipped.txt | 2 + .../HangDumpMutationTests.cs | 25 ++++ 5 files changed, 127 insertions(+), 19 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs index 0b18a60e88..b2ee50f306 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs @@ -32,8 +32,12 @@ internal sealed class HangDumpActivityIndicator : IDataConsumer, ITestSessionLif private readonly NamedPipeClient? _namedPipeClient; private readonly bool _traceLevelEnabled; private readonly ConcurrentDictionary _testsCurrentExecutionState = new(); + private readonly TimeSpan _activitySignalInterval; - private bool _exitSignalActivityIndicatorAsync; + private volatile bool _exitSignalActivityIndicatorAsync; + private int _activitySignalPending; + private CancellationTokenSource? _activitySignalCancellation; + private Task? _activitySignalTask; private NamedPipeServer? _singleConnectionNamedPipeServer; private PipeNameDescription? _pipeNameDescription; @@ -58,9 +62,24 @@ public HangDumpActivityIndicator( _namedPipeClient.RegisterSerializer(new VoidResponseSerializer(), typeof(VoidResponse)); _namedPipeClient.RegisterSerializer(new ConsumerPipeNameRequestSerializer(), typeof(ConsumerPipeNameRequest)); _namedPipeClient.RegisterSerializer(new ActivitySignalRequestSerializer(), typeof(ActivitySignalRequest)); + _activitySignalInterval = GetActivitySignalInterval(HangDumpOptions.GetTimeout(_commandLineOptions)); } } + /// + /// Activity is coalesced and sent to the controller at most once per interval instead of once per test + /// result, so fast tests do not pay a cross-process round trip each. Coalescing can only delay a signal, + /// never drop the latest one, so a dump can fire at most one interval later than the configured timeout, + /// never earlier. + /// + internal static TimeSpan GetActivitySignalInterval(TimeSpan hangTimeout) + { + var maxInterval = TimeSpan.FromSeconds(1); + var minInterval = TimeSpan.FromMilliseconds(10); + var interval = TimeSpan.FromTicks(hangTimeout.Ticks / 10); + return interval > maxInterval ? maxInterval : interval < minInterval ? minInterval : interval; + } + public Type[] DataTypesConsumed => [typeof(TestNodeUpdateMessage)]; public string Uid => nameof(HangDumpActivityIndicator); @@ -100,6 +119,10 @@ await _namedPipeClient.RequestReplyAsync( // Wait the connection from the testhost controller await _singleConnectionNamedPipeServer.WaitConnectionAsync(cancellationToken).TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, cancellationToken).ConfigureAwait(false); await _logger.LogTraceAsync("Test host controller connected").ConfigureAwait(false); + + _activitySignalCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + CancellationToken stopToken = _activitySignalCancellation.Token; + _activitySignalTask = _task.Run(() => SignalActivityLoopAsync(stopToken, cancellationToken), CancellationToken.None); } catch (OperationCanceledException ex) when (ex.CancellationToken == cancellationToken) { @@ -107,6 +130,41 @@ await _namedPipeClient.RequestReplyAsync( } } + private async Task SignalActivityLoopAsync(CancellationToken stopToken, CancellationToken sessionCancellationToken) + { + try + { + while (true) + { + await _task.Delay(_activitySignalInterval, stopToken).ConfigureAwait(false); + + // The stop token only interrupts the wait. A request in flight completes, so the pipe is never + // left with a half-read reply when the session ends. + await SendPendingActivitySignalAsync(sessionCancellationToken).ConfigureAwait(false); + } + } + catch (OperationCanceledException) when (stopToken.IsCancellationRequested) + { + // Stopped by the end of the session or by cancellation. + } + } + + private async Task SendPendingActivitySignalAsync(CancellationToken cancellationToken) + { + if (Interlocked.Exchange(ref _activitySignalPending, 0) == 0 || _exitSignalActivityIndicatorAsync) + { + return; + } + + ApplicationStateGuard.Ensure(_namedPipeClient is not null); + await _namedPipeClient.RequestReplyAsync(ActivitySignalRequest.Instance, cancellationToken).ConfigureAwait(false); + + if (_traceLevelEnabled) + { + await _logger.LogTraceAsync("Activity signal sent.").ConfigureAwait(false); + } + } + private async Task CallbackAsync(IRequest request) { if (request is GetInProgressTestsRequest) @@ -167,31 +225,48 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella await _logger.LogTraceAsync($"Signal for action node {nodeChangedMessage.TestNode.DisplayName} - '{state}'. _exitSignalActivityIndicatorAsync: {_exitSignalActivityIndicatorAsync}").ConfigureAwait(false); } - // Signal the activity. - if (!_exitSignalActivityIndicatorAsync) - { - ApplicationStateGuard.Ensure(_namedPipeClient is not null); - await _namedPipeClient.RequestReplyAsync(ActivitySignalRequest.Instance, cancellationToken).ConfigureAwait(false); - - if (_traceLevelEnabled) - { - await _logger.LogTraceAsync($"Activity signal sent.").ConfigureAwait(false); - } - } + // Record the activity; the signal loop forwards it to the controller. + Volatile.Write(ref _activitySignalPending, 1); } } - public Task OnTestSessionFinishingAsync(ITestSessionContext testSessionContext) - => Task.CompletedTask; + public async Task OnTestSessionFinishingAsync(ITestSessionContext testSessionContext) + { + if (_activitySignalTask is null) + { + return; + } + + // Stop the loop before sending the last pending signal, so two requests never share the pipe. + ApplicationStateGuard.Ensure(_activitySignalCancellation is not null); +#if NET + await _activitySignalCancellation.CancelAsync().ConfigureAwait(false); +#else + _activitySignalCancellation.Cancel(); +#endif + await _activitySignalTask.ConfigureAwait(false); + await SendPendingActivitySignalAsync(testSessionContext.CancellationToken).ConfigureAwait(false); + } #if NETCOREAPP public ValueTask DisposeAsync() { - _namedPipeClient?.Dispose(); + Dispose(); return ValueTask.CompletedTask; } #endif public void Dispose() - => _namedPipeClient?.Dispose(); + { + try + { + _activitySignalCancellation?.Cancel(); + } + catch (ObjectDisposedException) + { + } + + _activitySignalCancellation?.Dispose(); + _namedPipeClient?.Dispose(); + } } diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpOptions.cs b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpOptions.cs index 8ac388da31..da16ef13e3 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpOptions.cs +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpOptions.cs @@ -2,11 +2,19 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Testing.Platform.CommandLine; +using Microsoft.Testing.Platform.Helpers; namespace Microsoft.Testing.Extensions.Diagnostics; internal static class HangDumpOptions { + private static readonly TimeSpan DefaultTimeout = TimeSpan.FromMinutes(30); + public static bool IsEnabled(ICommandLineOptions commandLineOptions) => commandLineOptions.IsOptionSet(HangDumpCommandLineProvider.HangDumpOptionName); + + public static TimeSpan GetTimeout(ICommandLineOptions commandLineOptions) + => commandLineOptions.TryGetOptionArgumentList(HangDumpCommandLineProvider.HangDumpTimeoutOptionName, out string[]? timeout) + ? TimeSpanParser.Parse(timeout[0]) + : DefaultTimeout; } diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpProcessLifetimeHandler.cs b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpProcessLifetimeHandler.cs index 674253737a..fab96845ac 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpProcessLifetimeHandler.cs +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpProcessLifetimeHandler.cs @@ -127,9 +127,7 @@ public HangDumpProcessLifetimeHandler( public async Task BeforeTestHostProcessStartAsync(CancellationToken cancellationToken) { - _activityTimerValue = _commandLineOptions.TryGetOptionArgumentList(HangDumpCommandLineProvider.HangDumpTimeoutOptionName, out string[]? timeout) - ? TimeSpanParser.Parse(timeout[0]) - : TimeSpan.FromMinutes(30); + _activityTimerValue = HangDumpOptions.GetTimeout(_commandLineOptions); if (_commandLineOptions.TryGetOptionArgumentList(HangDumpCommandLineProvider.HangDumpTypeOptionName, out string[]? dumpType)) { diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/InternalAPI/InternalAPI.Unshipped.txt b/src/Platform/Microsoft.Testing.Extensions.HangDump/InternalAPI/InternalAPI.Unshipped.txt index 7dc5c58110..68f7b92dfe 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/InternalAPI/InternalAPI.Unshipped.txt +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/InternalAPI/InternalAPI.Unshipped.txt @@ -1 +1,3 @@ #nullable enable +static Microsoft.Testing.Extensions.Diagnostics.HangDumpActivityIndicator.GetActivitySignalInterval(System.TimeSpan hangTimeout) -> System.TimeSpan +static Microsoft.Testing.Extensions.Diagnostics.HangDumpOptions.GetTimeout(Microsoft.Testing.Platform.CommandLine.ICommandLineOptions! commandLineOptions) -> System.TimeSpan diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpMutationTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpMutationTests.cs index 7199ef2670..be5d1c633c 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpMutationTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpMutationTests.cs @@ -107,6 +107,31 @@ await indicator.ConsumeAsync( Assert.HasCount(1, messages.Where(message => message.Contains("Signal for action node Test uid", StringComparison.Ordinal))); } + [TestMethod] + public async Task ConsumeAsync_CoalescesActivityInsteadOfSendingAnIpcRequestPerResult() + { + // The indicator has no pipe client here, so any per-result IPC attempt would fail the guard. + using HangDumpActivityIndicator indicator = CreateIndicator(Mock.Of(), DateTimeOffset.UtcNow); + + await indicator.ConsumeAsync(null!, CreateUpdate("uid", InProgressTestNodeStateProperty.CachedInstance), CancellationToken.None); + Assert.AreEqual(0, GetPrivateField(indicator, "_activitySignalPending"), "An in-progress update is not activity."); + + await indicator.ConsumeAsync(null!, CreateUpdate("uid", PassedTestNodeStateProperty.CachedInstance), CancellationToken.None); + await indicator.ConsumeAsync(null!, CreateUpdate("other", PassedTestNodeStateProperty.CachedInstance), CancellationToken.None); + + Assert.AreEqual(1, GetPrivateField(indicator, "_activitySignalPending")); + } + + [TestMethod] + [DataRow(30 * 60 * 1000, 1000, DisplayName = "Default timeout is capped at one second")] + [DataRow(8000, 800, DisplayName = "Short timeout uses a tenth of the timeout")] + [DataRow(50, 10, DisplayName = "Tiny timeout is floored")] + [DataRow(0, 10, DisplayName = "Zero timeout is floored")] + public void GetActivitySignalInterval_IsATenthOfTheTimeoutWithinBounds(int timeoutMilliseconds, int expectedMilliseconds) + => Assert.AreEqual( + TimeSpan.FromMilliseconds(expectedMilliseconds), + HangDumpActivityIndicator.GetActivitySignalInterval(TimeSpan.FromMilliseconds(timeoutMilliseconds))); + private static HangDumpActivityIndicator CreateIndicator(ILogger logger, DateTimeOffset utcNow) { Mock loggerFactory = new(); From 258a69cf2339e746b8922de3376a0d8a89a3cd5b Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Mon, 2 Nov 2026 00:56:53 +0000 Subject: [PATCH 2/9] Stop HangDump activity signal loop before disposing its pipe client Dispose and DisposeAsync disposed the cancellation source and named pipe client without waiting for the signal loop, so an in-flight request could hit a disposed pipe and fault unobserved, and session finishing after disposal threw ObjectDisposedException. Loop shutdown is now idempotent and awaited (bounded in synchronous Dispose), and loop failures are logged immediately instead of only surfacing when the session ends. Co-Authored-By: Claude --- .../HangDumpActivityIndicator.cs | 74 +++++++++++++++---- .../HangDumpMutationTests.cs | 38 ++++++++++ 2 files changed, 98 insertions(+), 14 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs index b2ee50f306..922a4cfcfa 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs @@ -32,6 +32,8 @@ internal sealed class HangDumpActivityIndicator : IDataConsumer, ITestSessionLif private readonly NamedPipeClient? _namedPipeClient; private readonly bool _traceLevelEnabled; private readonly ConcurrentDictionary _testsCurrentExecutionState = new(); + private static readonly TimeSpan ActivitySignalShutdownTimeout = TimeSpan.FromSeconds(30); + private readonly TimeSpan _activitySignalInterval; private volatile bool _exitSignalActivityIndicatorAsync; @@ -147,6 +149,41 @@ private async Task SignalActivityLoopAsync(CancellationToken stopToken, Cancella { // Stopped by the end of the session or by cancellation. } + catch (Exception ex) + { + // Log now: without activity signals the controller can take a hang dump before the session ends + // and rethrows this failure. + await _logger.LogErrorAsync("Failed to send a hang dump activity signal to the test host controller; activity signals stopped.", ex).ConfigureAwait(false); + throw; + } + } + + private async Task StopActivitySignalLoopAsync() + { + // Idempotent: whoever takes the fields stops the loop, so session end and disposal never race on them. + CancellationTokenSource? cancellation = Interlocked.Exchange(ref _activitySignalCancellation, null); + Task? loop = Interlocked.Exchange(ref _activitySignalTask, null); + if (cancellation is null) + { + return; + } + + try + { +#if NET + await cancellation.CancelAsync().ConfigureAwait(false); +#else + cancellation.Cancel(); +#endif + if (loop is not null) + { + await loop.ConfigureAwait(false); + } + } + finally + { + cancellation.Dispose(); + } } private async Task SendPendingActivitySignalAsync(CancellationToken cancellationToken) @@ -232,41 +269,50 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella public async Task OnTestSessionFinishingAsync(ITestSessionContext testSessionContext) { - if (_activitySignalTask is null) + if (Volatile.Read(ref _activitySignalTask) is null) { return; } // Stop the loop before sending the last pending signal, so two requests never share the pipe. - ApplicationStateGuard.Ensure(_activitySignalCancellation is not null); -#if NET - await _activitySignalCancellation.CancelAsync().ConfigureAwait(false); -#else - _activitySignalCancellation.Cancel(); -#endif - await _activitySignalTask.ConfigureAwait(false); + await StopActivitySignalLoopAsync().ConfigureAwait(false); await SendPendingActivitySignalAsync(testSessionContext.CancellationToken).ConfigureAwait(false); } #if NETCOREAPP - public ValueTask DisposeAsync() + public async ValueTask DisposeAsync() { - Dispose(); - return ValueTask.CompletedTask; + // Wait for the loop before disposing the pipe client it may be using. + try + { + await StopActivitySignalLoopAsync().ConfigureAwait(false); + } + catch (Exception ex) + { + await _logger.LogDebugAsync($"Hang dump activity signal loop failed during disposal: {ex.Message}").ConfigureAwait(false); + } + + _namedPipeClient?.Dispose(); } #endif public void Dispose() { + // Wait (bounded) for the loop before disposing the pipe client it may be using. + Task stop = StopActivitySignalLoopAsync(); try { - _activitySignalCancellation?.Cancel(); + if (!stop.Wait(ActivitySignalShutdownTimeout)) + { + _logger.LogDebug("Hang dump activity signal loop did not stop within the shutdown timeout during disposal."); + _ = stop.ContinueWith(static task => _ = task.Exception, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default); + } } - catch (ObjectDisposedException) + catch (Exception ex) { + _logger.LogDebug($"Hang dump activity signal loop failed during disposal: {ex.Message}"); } - _activitySignalCancellation?.Dispose(); _namedPipeClient?.Dispose(); } } diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpMutationTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpMutationTests.cs index be5d1c633c..21d3ef303e 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpMutationTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpMutationTests.cs @@ -122,6 +122,44 @@ public async Task ConsumeAsync_CoalescesActivityInsteadOfSendingAnIpcRequestPerR Assert.AreEqual(1, GetPrivateField(indicator, "_activitySignalPending")); } +#if NETCOREAPP + [TestMethod] + public async Task DisposeAsync_StopsAndAwaitsActivitySignalLoop() + { + using HangDumpActivityIndicator indicator = CreateIndicator(Mock.Of(), DateTimeOffset.UtcNow); + (CancellationTokenSource cancellation, Task loop) = StartFakeActivitySignalLoop(indicator); + + await indicator.DisposeAsync(); + + Assert.IsTrue(cancellation.IsCancellationRequested); + Assert.IsTrue(loop.IsCompleted, "Disposal must wait for the loop before disposing the pipe client it may use."); + Assert.IsNull(GetPrivateField(indicator, "_activitySignalTask")); + } +#endif + + [TestMethod] + public async Task OnTestSessionFinishingAsync_AfterDispose_DoesNotTouchTheDisposedLoop() + { + HangDumpActivityIndicator indicator = CreateIndicator(Mock.Of(), DateTimeOffset.UtcNow); + StartFakeActivitySignalLoop(indicator); + indicator.Dispose(); + + Mock sessionContext = new(); + sessionContext.SetupGet(x => x.CancellationToken).Returns(CancellationToken.None); + + await indicator.OnTestSessionFinishingAsync(sessionContext.Object); + } + + private static (CancellationTokenSource Cancellation, Task Loop) StartFakeActivitySignalLoop(HangDumpActivityIndicator indicator) + { + var cancellation = new CancellationTokenSource(); + var loopCompletion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + cancellation.Token.Register(() => loopCompletion.TrySetResult(true)); + SetPrivateField(indicator, "_activitySignalCancellation", cancellation); + SetPrivateField(indicator, "_activitySignalTask", loopCompletion.Task); + return (cancellation, loopCompletion.Task); + } + [TestMethod] [DataRow(30 * 60 * 1000, 1000, DisplayName = "Default timeout is capped at one second")] [DataRow(8000, 800, DisplayName = "Short timeout uses a tenth of the timeout")] From ed0dc4f0331e4894c3986e8438c7dcb7ef1a389c Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Mon, 2 Nov 2026 01:11:28 +0000 Subject: [PATCH 3/9] Add the signal interval to the HangDump inactivity timer The controller re-arms its inactivity timer when an activity signal is delivered, but activity right after a delivery can wait up to one signal interval before the next flush. With the timer armed at exactly the hang timeout, a dump could fire before the timeout had elapsed since the last activity. The controller now arms the timer with the timeout plus the signal interval (computed with the same shared formula), so a dump never fires early and fires at most two intervals late. Also bound the wait for the signal loop in DisposeAsync, as in Dispose. Co-Authored-By: Claude --- .../HangDumpActivityIndicator.cs | 39 ++++++++++--------- .../HangDumpOptions.cs | 21 ++++++++++ .../HangDumpProcessLifetimeHandler.cs | 6 ++- .../InternalAPI/InternalAPI.Unshipped.txt | 3 +- .../HangDumpMutationTests.cs | 25 +++++++++++- 5 files changed, 71 insertions(+), 23 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs index 922a4cfcfa..72f435a8e3 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs @@ -64,24 +64,10 @@ public HangDumpActivityIndicator( _namedPipeClient.RegisterSerializer(new VoidResponseSerializer(), typeof(VoidResponse)); _namedPipeClient.RegisterSerializer(new ConsumerPipeNameRequestSerializer(), typeof(ConsumerPipeNameRequest)); _namedPipeClient.RegisterSerializer(new ActivitySignalRequestSerializer(), typeof(ActivitySignalRequest)); - _activitySignalInterval = GetActivitySignalInterval(HangDumpOptions.GetTimeout(_commandLineOptions)); + _activitySignalInterval = HangDumpOptions.GetActivitySignalInterval(HangDumpOptions.GetTimeout(_commandLineOptions)); } } - /// - /// Activity is coalesced and sent to the controller at most once per interval instead of once per test - /// result, so fast tests do not pay a cross-process round trip each. Coalescing can only delay a signal, - /// never drop the latest one, so a dump can fire at most one interval later than the configured timeout, - /// never earlier. - /// - internal static TimeSpan GetActivitySignalInterval(TimeSpan hangTimeout) - { - var maxInterval = TimeSpan.FromSeconds(1); - var minInterval = TimeSpan.FromMilliseconds(10); - var interval = TimeSpan.FromTicks(hangTimeout.Ticks / 10); - return interval > maxInterval ? maxInterval : interval < minInterval ? minInterval : interval; - } - public Type[] DataTypesConsumed => [typeof(TestNodeUpdateMessage)]; public string Uid => nameof(HangDumpActivityIndicator); @@ -282,10 +268,20 @@ public async Task OnTestSessionFinishingAsync(ITestSessionContext testSessionCon #if NETCOREAPP public async ValueTask DisposeAsync() { - // Wait for the loop before disposing the pipe client it may be using. + // Wait (bounded) for the loop before disposing the pipe client it may be using. This also covers runs + // where session finishing was skipped because execution or a lifecycle handler threw. + Task stop = StopActivitySignalLoopAsync(); try { - await StopActivitySignalLoopAsync().ConfigureAwait(false); + Task completed = await Task.WhenAny(stop, Task.Delay(ActivitySignalShutdownTimeout)).ConfigureAwait(false); + if (completed == stop) + { + await stop.ConfigureAwait(false); + } + else + { + ObserveLateStopFailure(stop); + } } catch (Exception ex) { @@ -304,8 +300,7 @@ public void Dispose() { if (!stop.Wait(ActivitySignalShutdownTimeout)) { - _logger.LogDebug("Hang dump activity signal loop did not stop within the shutdown timeout during disposal."); - _ = stop.ContinueWith(static task => _ = task.Exception, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default); + ObserveLateStopFailure(stop); } } catch (Exception ex) @@ -315,4 +310,10 @@ public void Dispose() _namedPipeClient?.Dispose(); } + + private void ObserveLateStopFailure(Task stop) + { + _logger.LogDebug("Hang dump activity signal loop did not stop within the shutdown timeout during disposal."); + _ = stop.ContinueWith(static task => _ = task.Exception, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default); + } } diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpOptions.cs b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpOptions.cs index da16ef13e3..69ef3f7253 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpOptions.cs +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpOptions.cs @@ -17,4 +17,25 @@ public static TimeSpan GetTimeout(ICommandLineOptions commandLineOptions) => commandLineOptions.TryGetOptionArgumentList(HangDumpCommandLineProvider.HangDumpTimeoutOptionName, out string[]? timeout) ? TimeSpanParser.Parse(timeout[0]) : DefaultTimeout; + + /// + /// The test host coalesces activity and sends it to the controller at most once per interval instead of once per + /// test result, so fast tests do not pay a cross-process round trip each. + /// + public static TimeSpan GetActivitySignalInterval(TimeSpan hangTimeout) + { + var maxInterval = TimeSpan.FromSeconds(1); + var minInterval = TimeSpan.FromMilliseconds(10); + var interval = TimeSpan.FromTicks(hangTimeout.Ticks / 10); + return interval > maxInterval ? maxInterval : interval < minInterval ? minInterval : interval; + } + + /// + /// Gets how long the controller waits after the last delivered activity signal before taking a hang dump. + /// Activity that happens right after a delivery can wait up to one signal interval before it is delivered, so + /// the controller adds that interval to the timeout. A dump then never fires before the configured timeout has + /// elapsed since the last activity; it can fire at most two intervals later. + /// + public static TimeSpan GetInactivityTimerDueTime(TimeSpan hangTimeout) + => hangTimeout + GetActivitySignalInterval(hangTimeout); } diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpProcessLifetimeHandler.cs b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpProcessLifetimeHandler.cs index fab96845ac..66065a2b4d 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpProcessLifetimeHandler.cs +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpProcessLifetimeHandler.cs @@ -53,6 +53,7 @@ internal sealed partial class HangDumpProcessLifetimeHandler : ITestHostProcessL #endif private TimeSpan? _activityTimerValue; + private TimeSpan? _activityTimerDueTime; private Timer? _activityTimer; private DateTimeOffset? _deadlineDumpAt; private Timer? _deadlineTimer; @@ -128,6 +129,7 @@ public HangDumpProcessLifetimeHandler( public async Task BeforeTestHostProcessStartAsync(CancellationToken cancellationToken) { _activityTimerValue = HangDumpOptions.GetTimeout(_commandLineOptions); + _activityTimerDueTime = HangDumpOptions.GetInactivityTimerDueTime(_activityTimerValue.Value); if (_commandLineOptions.TryGetOptionArgumentList(HangDumpCommandLineProvider.HangDumpTypeOptionName, out string[]? dumpType)) { @@ -210,7 +212,7 @@ private async Task CallbackAsync(IRequest request) } else if (request is ActivitySignalRequest) { - _activityTimer?.Change(_activityTimerValue!.Value, TimeSpan.FromMilliseconds(-1)); + _activityTimer?.Change(_activityTimerDueTime!.Value, TimeSpan.FromMilliseconds(-1)); if (_traceEnabled) { @@ -291,7 +293,7 @@ public async Task OnTestHostProcessStartedAsync(ITestHostProcessInformation test _activityTimer = new Timer( _ => TriggerDumpOnce(cancellationToken, triggeredByDeadline: false), null, - _activityTimerValue!.Value, + _activityTimerDueTime!.Value, TimeSpan.FromMilliseconds(-1)); } catch (Exception ex) when (Volatile.Read(ref _dumpTaken) != 0) diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/InternalAPI/InternalAPI.Unshipped.txt b/src/Platform/Microsoft.Testing.Extensions.HangDump/InternalAPI/InternalAPI.Unshipped.txt index 68f7b92dfe..8791f439d3 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/InternalAPI/InternalAPI.Unshipped.txt +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/InternalAPI/InternalAPI.Unshipped.txt @@ -1,3 +1,4 @@ #nullable enable -static Microsoft.Testing.Extensions.Diagnostics.HangDumpActivityIndicator.GetActivitySignalInterval(System.TimeSpan hangTimeout) -> System.TimeSpan +static Microsoft.Testing.Extensions.Diagnostics.HangDumpOptions.GetActivitySignalInterval(System.TimeSpan hangTimeout) -> System.TimeSpan +static Microsoft.Testing.Extensions.Diagnostics.HangDumpOptions.GetInactivityTimerDueTime(System.TimeSpan hangTimeout) -> System.TimeSpan static Microsoft.Testing.Extensions.Diagnostics.HangDumpOptions.GetTimeout(Microsoft.Testing.Platform.CommandLine.ICommandLineOptions! commandLineOptions) -> System.TimeSpan diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpMutationTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpMutationTests.cs index 21d3ef303e..59c155f564 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpMutationTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpMutationTests.cs @@ -168,7 +168,29 @@ private static (CancellationTokenSource Cancellation, Task Loop) StartFakeActivi public void GetActivitySignalInterval_IsATenthOfTheTimeoutWithinBounds(int timeoutMilliseconds, int expectedMilliseconds) => Assert.AreEqual( TimeSpan.FromMilliseconds(expectedMilliseconds), - HangDumpActivityIndicator.GetActivitySignalInterval(TimeSpan.FromMilliseconds(timeoutMilliseconds))); + HangDumpOptions.GetActivitySignalInterval(TimeSpan.FromMilliseconds(timeoutMilliseconds))); + + [TestMethod] + [DataRow(10_500, DisplayName = "Reviewer example: 10.5 s timeout, 1 s interval")] + [DataRow(8_000, DisplayName = "8 s timeout")] + [DataRow(30 * 60 * 1000, DisplayName = "Default 30 min timeout")] + [DataRow(50, DisplayName = "Tiny timeout with floored interval")] + public void InactivityTimer_NeverExpiresBeforeTheTimeoutSinceTheLastActivity(int timeoutMilliseconds) + { + var timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds); + TimeSpan interval = HangDumpOptions.GetActivitySignalInterval(timeout); + TimeSpan dueTime = HangDumpOptions.GetInactivityTimerDueTime(timeout); + + // The controller re-arms its timer when a signal is delivered. The worst case is activity just before the + // timeout elapses since that delivery, which then waits a full interval for the next flush. + var lastDelivery = TimeSpan.FromSeconds(1); + TimeSpan controllerExpiry = lastDelivery + dueTime; + TimeSpan latestActivity = lastDelivery + timeout - TimeSpan.FromTicks(1); + TimeSpan latestDelivery = latestActivity + interval; + + Assert.IsLessThan(controllerExpiry, latestDelivery, "Pending activity must reach the controller before its timer expires."); + Assert.AreEqual(timeout + interval, dueTime); + } private static HangDumpActivityIndicator CreateIndicator(ILogger logger, DateTimeOffset utcNow) { @@ -311,6 +333,7 @@ public async Task BeforeStartAndConsumerHandshake_InitializeEveryFieldAndSeriali await handler.BeforeTestHostProcessStartAsync(TestContext.CancellationToken); Assert.AreEqual(TimeSpan.FromMinutes(30), GetPrivateField(handler, "_activityTimerValue")); + Assert.AreEqual(TimeSpan.FromMinutes(30) + TimeSpan.FromSeconds(1), GetPrivateField(handler, "_activityTimerDueTime")); Assert.IsNull(GetPrivateField(handler, "_deadlineDumpAt")); Assert.Contains("Hang dump timeout setup 00:30:00.", messages); From 5da5fc4013e4a3f72d62845467cbb7a5c94ea478 Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Mon, 2 Nov 2026 01:36:31 +0000 Subject: [PATCH 4/9] Gate HangDump disposal tests on in-flight signal completion The fake signal loop completed inside its cancellation callback, so the disposal test still passed if disposal stopped waiting for the loop. The fake loop now observes cancellation separately and finishes only when a gate is released, and both Dispose and DisposeAsync are checked to stay incomplete until then. Co-Authored-By: Claude --- .../HangDumpMutationTests.cs | 66 +++++++++++++++---- 1 file changed, 55 insertions(+), 11 deletions(-) diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpMutationTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpMutationTests.cs index 59c155f564..8c5e980ab1 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpMutationTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpMutationTests.cs @@ -31,6 +31,10 @@ namespace Microsoft.Testing.Extensions.UnitTests; [TestClass] public sealed class HangDumpActivityIndicatorMutationTests { + private static readonly TimeSpan GateTimeout = TimeSpan.FromSeconds(30); + + public TestContext TestContext { get; set; } = null!; + [TestMethod] public async Task ConsumeAsync_PreCanceledToken_ThrowsBeforeInspectingTheMessage() { @@ -124,24 +128,36 @@ public async Task ConsumeAsync_CoalescesActivityInsteadOfSendingAnIpcRequestPerR #if NETCOREAPP [TestMethod] - public async Task DisposeAsync_StopsAndAwaitsActivitySignalLoop() + public async Task DisposeAsync_WaitsForInFlightActivitySignalBeforeReturning() { using HangDumpActivityIndicator indicator = CreateIndicator(Mock.Of(), DateTimeOffset.UtcNow); - (CancellationTokenSource cancellation, Task loop) = StartFakeActivitySignalLoop(indicator); + GatedActivitySignalLoop loop = StartGatedActivitySignalLoop(indicator); - await indicator.DisposeAsync(); + Task dispose = indicator.DisposeAsync().AsTask(); - Assert.IsTrue(cancellation.IsCancellationRequested); - Assert.IsTrue(loop.IsCompleted, "Disposal must wait for the loop before disposing the pipe client it may use."); + await AssertDisposalWaitsForLoopAsync(loop, dispose); Assert.IsNull(GetPrivateField(indicator, "_activitySignalTask")); } #endif + [TestMethod] + public async Task Dispose_WaitsForInFlightActivitySignalBeforeReturning() + { + HangDumpActivityIndicator indicator = CreateIndicator(Mock.Of(), DateTimeOffset.UtcNow); + GatedActivitySignalLoop loop = StartGatedActivitySignalLoop(indicator); + + var dispose = Task.Run(indicator.Dispose, TestContext.CancellationToken); + + await AssertDisposalWaitsForLoopAsync(loop, dispose); + Assert.IsNull(GetPrivateField(indicator, "_activitySignalTask")); + } + [TestMethod] public async Task OnTestSessionFinishingAsync_AfterDispose_DoesNotTouchTheDisposedLoop() { HangDumpActivityIndicator indicator = CreateIndicator(Mock.Of(), DateTimeOffset.UtcNow); - StartFakeActivitySignalLoop(indicator); + GatedActivitySignalLoop loop = StartGatedActivitySignalLoop(indicator); + loop.Release(); indicator.Dispose(); Mock sessionContext = new(); @@ -150,14 +166,42 @@ public async Task OnTestSessionFinishingAsync_AfterDispose_DoesNotTouchTheDispos await indicator.OnTestSessionFinishingAsync(sessionContext.Object); } - private static (CancellationTokenSource Cancellation, Task Loop) StartFakeActivitySignalLoop(HangDumpActivityIndicator indicator) + private static async Task AssertDisposalWaitsForLoopAsync(GatedActivitySignalLoop loop, Task dispose) { + try + { + // The loop has seen the stop request but its in-flight request (the gate) has not finished yet. + Assert.AreSame(loop.CancellationObserved, await Task.WhenAny(loop.CancellationObserved, Task.Delay(GateTimeout)), "Disposal must stop the loop."); + await Task.Delay(100); + Assert.IsFalse(dispose.IsCompleted, "Disposal must not return while an activity signal request may still use the pipe client."); + } + finally + { + loop.Release(); + } + + Assert.AreSame(dispose, await Task.WhenAny(dispose, Task.Delay(GateTimeout)), "Disposal must complete once the loop finishes."); + await dispose; + } + + private static GatedActivitySignalLoop StartGatedActivitySignalLoop(HangDumpActivityIndicator indicator) + { + // The fake loop observes cancellation like the real one, but finishes only when the gate is released, + // the way an in-flight request finishes only when the controller replies. var cancellation = new CancellationTokenSource(); - var loopCompletion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - cancellation.Token.Register(() => loopCompletion.TrySetResult(true)); + var cancellationObserved = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + cancellation.Token.Register(() => cancellationObserved.TrySetResult(true)); SetPrivateField(indicator, "_activitySignalCancellation", cancellation); - SetPrivateField(indicator, "_activitySignalTask", loopCompletion.Task); - return (cancellation, loopCompletion.Task); + SetPrivateField(indicator, "_activitySignalTask", gate.Task); + return new GatedActivitySignalLoop(cancellationObserved.Task, gate); + } + + private sealed class GatedActivitySignalLoop(Task cancellationObserved, TaskCompletionSource gate) + { + public Task CancellationObserved { get; } = cancellationObserved; + + public void Release() => gate.TrySetResult(true); } [TestMethod] From 8d28f962f5697a23b30f27797fb70f431ca8ecb7 Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Mon, 2 Nov 2026 10:47:51 +0000 Subject: [PATCH 5/9] Defer HangDump pipe disposal past a timed-out signal loop and contain a canceled final flush If the activity signal loop does not stop within the shutdown timeout, dispose the pipe client only once the loop finishes, so a request still in flight never runs against disposed buffers and triggers the client's process-exit path. A session canceled while finishing no longer lets the best-effort final activity flush throw, which would skip the session-finishing handlers after HangDump. --- .../HangDumpActivityIndicator.cs | 57 +++++++++---- .../HangDumpMutationTests.cs | 79 +++++++++++++++++++ 2 files changed, 120 insertions(+), 16 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs index 72f435a8e3..610cf165fe 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs @@ -32,9 +32,9 @@ internal sealed class HangDumpActivityIndicator : IDataConsumer, ITestSessionLif private readonly NamedPipeClient? _namedPipeClient; private readonly bool _traceLevelEnabled; private readonly ConcurrentDictionary _testsCurrentExecutionState = new(); - private static readonly TimeSpan ActivitySignalShutdownTimeout = TimeSpan.FromSeconds(30); private readonly TimeSpan _activitySignalInterval; + private readonly TimeSpan _activitySignalShutdownTimeout = TimeSpan.FromSeconds(30); private volatile bool _exitSignalActivityIndicatorAsync; private int _activitySignalPending; @@ -262,26 +262,36 @@ public async Task OnTestSessionFinishingAsync(ITestSessionContext testSessionCon // Stop the loop before sending the last pending signal, so two requests never share the pipe. await StopActivitySignalLoopAsync().ConfigureAwait(false); - await SendPendingActivitySignalAsync(testSessionContext.CancellationToken).ConfigureAwait(false); + + CancellationToken cancellationToken = testSessionContext.CancellationToken; + try + { + await SendPendingActivitySignalAsync(cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + // The final flush is best effort. A canceled session must not skip the session-finishing handlers + // that run after this one. + } } #if NETCOREAPP public async ValueTask DisposeAsync() { // Wait (bounded) for the loop before disposing the pipe client it may be using. This also covers runs - // where session finishing was skipped because execution or a lifecycle handler threw. + // where session finishing was skipped because execution or a lifecycle handler threw. If the wait times + // out, the pipe client is disposed only when the loop stops. Task stop = StopActivitySignalLoopAsync(); try { - Task completed = await Task.WhenAny(stop, Task.Delay(ActivitySignalShutdownTimeout)).ConfigureAwait(false); - if (completed == stop) - { - await stop.ConfigureAwait(false); - } - else + Task completed = await Task.WhenAny(stop, Task.Delay(_activitySignalShutdownTimeout)).ConfigureAwait(false); + if (completed != stop) { - ObserveLateStopFailure(stop); + DisposePipeClientAfterLateStop(stop); + return; } + + await stop.ConfigureAwait(false); } catch (Exception ex) { @@ -294,13 +304,15 @@ public async ValueTask DisposeAsync() public void Dispose() { - // Wait (bounded) for the loop before disposing the pipe client it may be using. + // Wait (bounded) for the loop before disposing the pipe client it may be using. If the wait times out, the + // pipe client is disposed only when the loop stops. Task stop = StopActivitySignalLoopAsync(); try { - if (!stop.Wait(ActivitySignalShutdownTimeout)) + if (!stop.Wait(_activitySignalShutdownTimeout)) { - ObserveLateStopFailure(stop); + DisposePipeClientAfterLateStop(stop); + return; } } catch (Exception ex) @@ -311,9 +323,22 @@ public void Dispose() _namedPipeClient?.Dispose(); } - private void ObserveLateStopFailure(Task stop) + private void DisposePipeClientAfterLateStop(Task stop) { - _logger.LogDebug("Hang dump activity signal loop did not stop within the shutdown timeout during disposal."); - _ = stop.ContinueWith(static task => _ = task.Exception, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default); + // A request that is still in flight uses the pipe client's stream and buffers. On Windows a write waits for + // the controller to drain the pipe, and the stop request cannot interrupt that wait. Disposing the client + // under it would make the request fail, and the client then exits the process. Dispose the client only + // after the loop has finished, and observe the loop's failure so it is never unobserved. + _logger.LogDebug("Hang dump activity signal loop did not stop within the shutdown timeout during disposal; the pipe client is disposed when it stops."); + _ = stop.ContinueWith( + static (task, state) => + { + _ = task.Exception; + ((NamedPipeClient?)state)?.Dispose(); + }, + _namedPipeClient, + CancellationToken.None, + TaskContinuationOptions.None, + TaskScheduler.Default); } } diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpMutationTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpMutationTests.cs index 8c5e980ab1..e662fedc7b 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpMutationTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpMutationTests.cs @@ -166,6 +166,67 @@ public async Task OnTestSessionFinishingAsync_AfterDispose_DoesNotTouchTheDispos await indicator.OnTestSessionFinishingAsync(sessionContext.Object); } +#if NETCOREAPP + [TestMethod] + public async Task DisposeAsync_ShutdownTimeout_DefersPipeClientDisposalUntilTheLoopStops() + { + HangDumpActivityIndicator indicator = CreateEnabledIndicator(); + SetPrivateField(indicator, "_activitySignalShutdownTimeout", TimeSpan.FromMilliseconds(50)); + GatedActivitySignalLoop loop = StartGatedActivitySignalLoop(indicator); + + await AssertPipeClientDisposalDeferredAsync(indicator, loop, () => indicator.DisposeAsync().AsTask()); + } +#endif + + [TestMethod] + public async Task Dispose_ShutdownTimeout_DefersPipeClientDisposalUntilTheLoopStops() + { + HangDumpActivityIndicator indicator = CreateEnabledIndicator(); + SetPrivateField(indicator, "_activitySignalShutdownTimeout", TimeSpan.FromMilliseconds(50)); + GatedActivitySignalLoop loop = StartGatedActivitySignalLoop(indicator); + + await AssertPipeClientDisposalDeferredAsync(indicator, loop, () => Task.Run(indicator.Dispose, TestContext.CancellationToken)); + } + + [TestMethod] + public async Task OnTestSessionFinishingAsync_CanceledSessionWithPendingActivity_CompletesSoLaterHandlersRun() + { + using HangDumpActivityIndicator indicator = CreateEnabledIndicator(); + GatedActivitySignalLoop loop = StartGatedActivitySignalLoop(indicator); + loop.Release(); + SetPrivateField(indicator, "_activitySignalPending", 1); + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + Mock sessionContext = new(); + sessionContext.SetupGet(x => x.CancellationToken).Returns(cancellation.Token); + + // The pipe client rejects the canceled token before touching the pipe; the handler must contain that. + await indicator.OnTestSessionFinishingAsync(sessionContext.Object); + + Assert.AreEqual(0, GetPrivateField(indicator, "_activitySignalPending")); + } + + private async Task AssertPipeClientDisposalDeferredAsync(HangDumpActivityIndicator indicator, GatedActivitySignalLoop loop, Func dispose) + { + object pipeClient = GetPrivateField(indicator, "_namedPipeClient"); + try + { + Task disposal = dispose(); + Assert.AreSame(disposal, await Task.WhenAny(disposal, Task.Delay(GateTimeout, TestContext.CancellationToken)), "Disposal must return after the shutdown timeout."); + await disposal; + + Assert.IsFalse(GetPrivateField(pipeClient, "_disposed"), "The pipe client must not be disposed while an activity signal request may still use it."); + } + finally + { + loop.Release(); + } + + Assert.IsTrue( + SpinWait.SpinUntil(() => GetPrivateField(pipeClient, "_disposed"), GateTimeout), + "The pipe client must be disposed once the activity signal loop stops."); + } + private static async Task AssertDisposalWaitsForLoopAsync(GatedActivitySignalLoop loop, Task dispose) { try @@ -250,6 +311,24 @@ private static HangDumpActivityIndicator CreateIndicator(ILogger logger, DateTim clock.Object); } + private static HangDumpActivityIndicator CreateEnabledIndicator() + { + Mock loggerFactory = new(); + loggerFactory.Setup(factory => factory.CreateLogger(It.IsAny())).Returns(Mock.Of()); + Mock environment = new(); + environment.Setup(x => x.GetEnvironmentVariable(It.IsAny())).Returns($"hang_{Guid.NewGuid():N}"); + Mock clock = new(); + clock.SetupGet(x => x.UtcNow).Returns(DateTimeOffset.UtcNow); + + // An enabled indicator owns a real, unconnected pipe client. + return new( + new TestCommandLineOptions(new Dictionary { [HangDumpCommandLineProvider.HangDumpOptionName] = [] }), + environment.Object, + Mock.Of(), + loggerFactory.Object, + clock.Object); + } + private static Mock CreateRecordingLogger(List messages, bool traceEnabled) { Mock logger = new(); From 364736b041ae05d684af962e8a9d32ccbc37bb5f Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Mon, 2 Nov 2026 10:47:51 +0000 Subject: [PATCH 6/9] Re-arm the HangDump inactivity timer in bounded periods The inactivity due time is the timeout plus the signal interval, which can exceed the longest period a Timer accepts for timeouts near the parser's upper bound. Wait for such due times in several periods instead of failing to create the timer or shortening the configured timeout. --- .../HangDumpOptions.cs | 22 +++++++ .../HangDumpProcessLifetimeHandler.cs | 65 ++++++++++++++++++- .../InternalAPI/InternalAPI.Unshipped.txt | 2 + .../HangDumpTests.cs | 39 +++++++++++ 4 files changed, 125 insertions(+), 3 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpOptions.cs b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpOptions.cs index 69ef3f7253..4a6237bb77 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpOptions.cs +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpOptions.cs @@ -10,6 +10,11 @@ internal static class HangDumpOptions { private static readonly TimeSpan DefaultTimeout = TimeSpan.FromMinutes(30); + /// + /// The longest period accepts ( - 1 milliseconds). + /// + public static readonly TimeSpan MaxTimerPeriod = TimeSpan.FromMilliseconds(uint.MaxValue - 1); + public static bool IsEnabled(ICommandLineOptions commandLineOptions) => commandLineOptions.IsOptionSet(HangDumpCommandLineProvider.HangDumpOptionName); @@ -38,4 +43,21 @@ public static TimeSpan GetActivitySignalInterval(TimeSpan hangTimeout) /// public static TimeSpan GetInactivityTimerDueTime(TimeSpan hangTimeout) => hangTimeout + GetActivitySignalInterval(hangTimeout); + + /// + /// Splits into the next period a accepts and the time still to + /// wait after it, so a due time beyond is waited for in several periods instead of + /// being rejected or shortened. + /// + public static TimeSpan GetTimerPeriod(TimeSpan dueTime, out TimeSpan remainingDueTime) + { + if (dueTime > MaxTimerPeriod) + { + remainingDueTime = dueTime - MaxTimerPeriod; + return MaxTimerPeriod; + } + + remainingDueTime = TimeSpan.Zero; + return dueTime; + } } diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpProcessLifetimeHandler.cs b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpProcessLifetimeHandler.cs index 66065a2b4d..03ce696804 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpProcessLifetimeHandler.cs +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpProcessLifetimeHandler.cs @@ -52,9 +52,21 @@ internal sealed partial class HangDumpProcessLifetimeHandler : ITestHostProcessL private readonly object _dumpLock = new(); #endif + // Serializes re-arming the inactivity timer (on each activity signal) with continuing a wait that is longer + // than one Timer period (in the timer callback). +#if NET9_0_OR_GREATER + private readonly Lock _activityTimerLock = new(); +#else + private readonly object _activityTimerLock = new(); +#endif + private TimeSpan? _activityTimerValue; private TimeSpan? _activityTimerDueTime; private Timer? _activityTimer; + + // The part of the inactivity due time that is still to wait after the timer's current period. It is non-zero + // only when the due time exceeds the maximum period a Timer accepts. Read and written under _activityTimerLock. + private TimeSpan _activityTimerRemainingDueTime; private DateTimeOffset? _deadlineDumpAt; private Timer? _deadlineTimer; private bool _hostExited; @@ -212,7 +224,7 @@ private async Task CallbackAsync(IRequest request) } else if (request is ActivitySignalRequest) { - _activityTimer?.Change(_activityTimerDueTime!.Value, TimeSpan.FromMilliseconds(-1)); + ArmActivityTimer(); if (_traceEnabled) { @@ -291,10 +303,11 @@ public async Task OnTestHostProcessStartedAsync(ITestHostProcessInformation test // The inactivity timer only makes sense once the host has connected and can send activity // signals; before that there is nothing to reset it. The deadline timer above is independent. _activityTimer = new Timer( - _ => TriggerDumpOnce(cancellationToken, triggeredByDeadline: false), + _ => OnActivityTimerElapsed(cancellationToken), null, - _activityTimerDueTime!.Value, + Timeout.InfiniteTimeSpan, TimeSpan.FromMilliseconds(-1)); + ArmActivityTimer(); } catch (Exception ex) when (Volatile.Read(ref _dumpTaken) != 0) { @@ -379,6 +392,52 @@ await RunBestEffortDiagnosticAsync( } } + private void ArmActivityTimer() + { + lock (_activityTimerLock) + { + Timer? timer = _activityTimer; + if (timer is null) + { + return; + } + + TimeSpan period = HangDumpOptions.GetTimerPeriod(_activityTimerDueTime!.Value, out _activityTimerRemainingDueTime); + try + { + timer.Change(period, Timeout.InfiniteTimeSpan); + } + catch (ObjectDisposedException) + { + // Teardown won the race with this activity signal. + } + } + } + + private void OnActivityTimerElapsed(CancellationToken cancellationToken) + { + lock (_activityTimerLock) + { + if (_activityTimerRemainingDueTime > TimeSpan.Zero) + { + // The inactivity timeout is longer than one Timer period: keep waiting instead of dumping early. + TimeSpan period = HangDumpOptions.GetTimerPeriod(_activityTimerRemainingDueTime, out _activityTimerRemainingDueTime); + try + { + _activityTimer!.Change(period, Timeout.InfiniteTimeSpan); + } + catch (ObjectDisposedException) + { + // Teardown won the race with this timer callback. + } + + return; + } + } + + TriggerDumpOnce(cancellationToken, triggeredByDeadline: false); + } + private void OnDeadlineTimerElapsed(CancellationToken cancellationToken) { TimeSpan dueTime = DeadlineHelper.GetTimerDueTime(_deadlineDumpAt!.Value, _clock.UtcNow); diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/InternalAPI/InternalAPI.Unshipped.txt b/src/Platform/Microsoft.Testing.Extensions.HangDump/InternalAPI/InternalAPI.Unshipped.txt index 8791f439d3..d9bb0e1bdf 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/InternalAPI/InternalAPI.Unshipped.txt +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/InternalAPI/InternalAPI.Unshipped.txt @@ -2,3 +2,5 @@ static Microsoft.Testing.Extensions.Diagnostics.HangDumpOptions.GetActivitySignalInterval(System.TimeSpan hangTimeout) -> System.TimeSpan static Microsoft.Testing.Extensions.Diagnostics.HangDumpOptions.GetInactivityTimerDueTime(System.TimeSpan hangTimeout) -> System.TimeSpan static Microsoft.Testing.Extensions.Diagnostics.HangDumpOptions.GetTimeout(Microsoft.Testing.Platform.CommandLine.ICommandLineOptions! commandLineOptions) -> System.TimeSpan +static Microsoft.Testing.Extensions.Diagnostics.HangDumpOptions.GetTimerPeriod(System.TimeSpan dueTime, out System.TimeSpan remainingDueTime) -> System.TimeSpan +static readonly Microsoft.Testing.Extensions.Diagnostics.HangDumpOptions.MaxTimerPeriod -> System.TimeSpan diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpTests.cs index 306cbc1ee8..6ef97e2bdc 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpTests.cs @@ -683,6 +683,40 @@ public async Task Dispose_DumpInFlight_WaitsForCompletion() await disposeTask; } + [TestMethod] + public void ActivityTimer_DueTimeBeyondTheTimerLimit_WaitsInSeveralPeriodsInsteadOfFailingOrDumping() + { + // The largest timeout the parser accepts plus the signal interval exceeds the longest period a Timer accepts. + TimeSpan dueTime = HangDumpOptions.GetInactivityTimerDueTime(TimeSpan.FromMilliseconds(uint.MaxValue - 1)); + using var activityTimer = new Timer(_ => { }, null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan); + HangDumpProcessLifetimeHandler handler = CreateHandler(); + SetHandlerField(handler, "_activityTimerDueTime", dueTime); + SetHandlerField(handler, "_activityTimer", activityTimer); + + InvokeHandlerMethod(handler, "ArmActivityTimer"); + Assert.AreEqual(TimeSpan.FromSeconds(1), GetHandlerField(handler, "_activityTimerRemainingDueTime")); + + InvokeHandlerMethod(handler, "OnActivityTimerElapsed", CancellationToken.None); + Assert.AreEqual(0, GetHandlerField(handler, "_dumpTaken"), "The first period elapsing is not inactivity for the whole timeout."); + Assert.AreEqual(TimeSpan.Zero, GetHandlerField(handler, "_activityTimerRemainingDueTime")); + + SetHandlerField(handler, "_activityTimer", (Timer?)null); + SetHandlerField(handler, "_activityIndicatorTask", Task.CompletedTask); + handler.Dispose(); + } + + [TestMethod] + [DataRow(1000L, 1000L, 0L, DisplayName = "Short due time is one period")] + [DataRow(4294967294L, 4294967294L, 0L, DisplayName = "Maximum period is one period")] + [DataRow(4294968294L, 4294967294L, 1000L, DisplayName = "Longer due time waits for the rest after the period")] + public void GetTimerPeriod_SplitsDueTimesBeyondTheTimerLimit(long dueTimeMilliseconds, long expectedPeriodMilliseconds, long expectedRemainingMilliseconds) + { + TimeSpan period = HangDumpOptions.GetTimerPeriod(TimeSpan.FromMilliseconds(dueTimeMilliseconds), out TimeSpan remaining); + + Assert.AreEqual(TimeSpan.FromMilliseconds(expectedPeriodMilliseconds), period); + Assert.AreEqual(TimeSpan.FromMilliseconds(expectedRemainingMilliseconds), remaining); + } + [TestMethod] public void Dispose_FaultedDump_ReportsAndRethrowsAggregateException() { @@ -921,6 +955,11 @@ await Assert.ThrowsExactlyAsync( () => (Task)operation.Invoke(pipe, [cancellationToken])!); } + private static void InvokeHandlerMethod(HangDumpProcessLifetimeHandler handler, string methodName, params object?[] arguments) + => typeof(HangDumpProcessLifetimeHandler) + .GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic)! + .Invoke(handler, arguments); + private static void SetHandlerField(HangDumpProcessLifetimeHandler handler, string fieldName, T value) => typeof(HangDumpProcessLifetimeHandler) .GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic)! From f4bc3d92f0b31522184a298283ff659a533478bc Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Tue, 3 Nov 2026 11:16:04 +0000 Subject: [PATCH 7/9] Adapt main's HangDump activity and real-pipe tests to coalesced signals HangDumpActivityBehaviorTests expected ConsumeAsync to fail on the missing pipe client, which relied on per-result IPC. Those cases now await normal completion and keep their bookkeeping, retry, clock and trace assertions, plus a check that no scheduler work is started. HangDumpInProcessProtocolFixture's strict ITask mock now provides a controllable, cancellation-aware Delay. FlushActivityAsync releases one wait of the signal loop and returns once the loop waits again, so the pending signal has been acknowledged. The lifecycle tests flush before asserting acknowledgements, assert coalescing (several results, one signal), assert that activity before the reverse connection is delivered once the loop starts, and cover a canceled final flush on a live pipe. --- .../HangDumpActivityBehaviorTests.cs | 34 ++++++------- .../HangDumpInProcessLifecycleTests.cs | 49 ++++++++++++++----- .../HangDumpInProcessProtocolFixture.cs | 35 +++++++++++++ 3 files changed, 88 insertions(+), 30 deletions(-) diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpActivityBehaviorTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpActivityBehaviorTests.cs index c76ed936cf..0656ddc9e6 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpActivityBehaviorTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpActivityBehaviorTests.cs @@ -107,7 +107,7 @@ public async Task Start_OnlyCancellationForTheSessionTokenIsSwallowed(int scenar [DataRow(4, DisplayName = "ActivityTerminal_Cancelled")] [DataRow(5, DisplayName = "ActivityTerminal_Timeout")] [DataRow(6, DisplayName = "ActivityTerminal_ExecutionCompleted")] - public async Task Consume_TerminalUpdateReportsOriginalStartAndRemainingTestBeforeMissingChannelFails(int terminalState) + public async Task Consume_TerminalUpdateReportsOriginalStartAndRemainingTestWithoutIpc(int terminalState) { using var fixture = new DumpBehaviorFixture(); using HangDumpActivityIndicator indicator = fixture.CreateActivityIndicator(); @@ -128,13 +128,11 @@ await indicator.ConsumeAsync( fixture.Now = fixture.Now.AddSeconds(4); TestNodeUpdateMessage terminal = DumpBehaviorFixture.Update("selected", "Terminal selected", GetTerminalProperty(terminalState)); - // A disabled indicator has no activity channel. Its public invariant fails after the - // bookkeeping/trace diagnostics, providing a deterministic boundary without IPC or reflection. - InvalidOperationException exception = await Assert.ThrowsExactlyAsync( - () => indicator.ConsumeAsync(null!, terminal, CancellationToken.None)); - Assert.Contains("Unexpected state", exception.Message); - await Assert.ThrowsExactlyAsync( - () => indicator.ConsumeAsync(null!, terminal, CancellationToken.None)); + // A disabled indicator has no activity channel, so any per-result IPC attempt would fail its + // state guard. Consuming only records the activity for the background signal loop, so both + // terminal updates complete without a request. + await indicator.ConsumeAsync(null!, terminal, CancellationToken.None); + await indicator.ConsumeAsync(null!, terminal, CancellationToken.None); Assert.AreSequenceEqual( ["Test removed from in-progress list 'Original selected' after '00:00:08', total in-progress '1'"], @@ -159,21 +157,22 @@ await indicator.ConsumeAsync( fixture.Now = fixture.Now.AddSeconds(3); IProperty attemptState = completionMarker ? TestNodeExecutionCompletedProperty.CachedInstance : new FailedTestNodeStateProperty(); - await Assert.ThrowsExactlyAsync(() => indicator.ConsumeAsync( + await indicator.ConsumeAsync( null!, DumpBehaviorFixture.Update("retried", "Superseded attempt", attemptState, new RetryAttemptProperty(1, isSuperseded: true)), - CancellationToken.None)); + CancellationToken.None); Assert.IsEmpty(fixture.Logs.Where(log => log.Message.StartsWith("Test removed from in-progress list", StringComparison.Ordinal))); fixture.Now = fixture.Now.AddSeconds(8); - await Assert.ThrowsExactlyAsync(() => indicator.ConsumeAsync( + await indicator.ConsumeAsync( null!, DumpBehaviorFixture.Update("retried", "Final attempt", PassedTestNodeStateProperty.CachedInstance, new RetryAttemptProperty(2, isSuperseded: false)), - CancellationToken.None)); + CancellationToken.None); Assert.AreSequenceEqual( ["Test removed from in-progress list 'Original retry' after '00:00:11', total in-progress '0'"], fixture.Logs.Select(log => log.Message).Where(message => message.StartsWith("Test removed from in-progress list", StringComparison.Ordinal))); + Assert.IsEmpty(fixture.Scheduler.Invocations); } [TestMethod] @@ -202,15 +201,16 @@ public async Task Consume_MissingStateDoesNotInventRunningTest() using var fixture = new DumpBehaviorFixture(); using HangDumpActivityIndicator indicator = fixture.CreateActivityIndicator(); - await Assert.ThrowsExactlyAsync(() => indicator.ConsumeAsync( + await indicator.ConsumeAsync( null!, DumpBehaviorFixture.Update("unknown", "Untracked test"), - CancellationToken.None)); + CancellationToken.None); Assert.AreSequenceEqual( ["Signal for action node Untracked test - ''. _exitSignalActivityIndicatorAsync: False"], fixture.Logs.Select(log => log.Message)); fixture.Clock.VerifyGet(x => x.UtcNow, Times.Never); + Assert.IsEmpty(fixture.Scheduler.Invocations); } [TestMethod] @@ -243,14 +243,14 @@ await indicator.ConsumeAsync( fixture.Clock.VerifyGet(x => x.UtcNow, Times.Once); fixture.Clock.SetupGet(x => x.UtcNow).Throws(new IOException("Trace-disabled terminal handling must not read elapsed time.")); - InvalidOperationException exception = await Assert.ThrowsExactlyAsync(() => indicator.ConsumeAsync( + await indicator.ConsumeAsync( null!, DumpBehaviorFixture.Update("running", "Completed test", PassedTestNodeStateProperty.CachedInstance), - CancellationToken.None)); + CancellationToken.None); - Assert.Contains("Unexpected state", exception.Message); Assert.IsEmpty(fixture.Logs); fixture.Clock.VerifyGet(x => x.UtcNow, Times.Once); + Assert.IsEmpty(fixture.Scheduler.Invocations); } #if NETCOREAPP diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpInProcessLifecycleTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpInProcessLifecycleTests.cs index 809b3758a4..1f2bed40db 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpInProcessLifecycleTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpInProcessLifecycleTests.cs @@ -45,8 +45,12 @@ public async Task RegisteredLifecycle_HandshakeActivityAndExitUseOwnedRoles(bool await ConsumeAsync(fixture, "not-running", "Ignoré é", SkippedTestNodeStateProperty.CachedInstance); await ConsumeAsync(fixture, "metadata", "No state 東京"); - fixture.AssertSignalCount(4); - fixture.ControllerClock.VerifyGet(value => value.UtcNow, Times.Exactly(traceEnabled ? 4 : 0)); + // Activity is only recorded on the per-result path; the background loop forwards all four + // updates to the controller as one coalesced signal. + fixture.AssertSignalCount(0); + await fixture.FlushActivityAsync(); + fixture.AssertSignalCount(1); + fixture.ControllerClock.VerifyGet(value => value.UtcNow, Times.Exactly(traceEnabled ? 1 : 0)); fixture.ChildClock.VerifyGet(value => value.UtcNow, Times.Exactly(traceEnabled ? 3 : 2)); string[] removals = RemovalMessages(fixture); if (traceEnabled) @@ -60,12 +64,16 @@ public async Task RegisteredLifecycle_HandshakeActivityAndExitUseOwnedRoles(bool || message.StartsWith("New in-progress test '", StringComparison.Ordinal))); } - // Finishing has no transport or cancellation side effects, even with a canceled token. + // Finishing stops the loop and makes a best-effort final flush. With a canceled session the + // flush is rejected before any request is written, and finishing still completes normally so + // later finishing handlers run. + await ConsumeAsync(fixture, "pending", "Pending at finish Ω", PassedTestNodeStateProperty.CachedInstance); using var rejectedFinish = new CancellationTokenSource(); rejectedFinish.Cancel(); int logCount = fixture.Logs.Count; - await fixture.SessionLifetime.OnTestSessionFinishingAsync(new TestSessionContext(rejectedFinish.Token)); + await fixture.AwaitAsync(fixture.SessionLifetime.OnTestSessionFinishingAsync(new TestSessionContext(rejectedFinish.Token))); Assert.HasCount(logCount, fixture.Logs); + fixture.AssertSignalCount(1); await fixture.AwaitAsync(fixture.Controller.OnTestHostProcessExitedAsync(fixture.ProcessInformation.Object, fixture.Token)); fixture.ProcessInformation.VerifyGet(value => value.HasExitedGracefully, Times.Once); fixture.ProcessInformation.VerifyGet(value => value.ExitCode, graceful ? Times.Never() : Times.Once()); @@ -81,7 +89,7 @@ public async Task RegisteredLifecycle_HandshakeActivityAndExitUseOwnedRoles(bool } [TestMethod] - public async Task RegisteredLifecycle_ActivityBeforeReverseConnectionIsAcknowledged() + public async Task RegisteredLifecycle_ActivityBeforeReverseConnectionIsDeliveredOnceConnected() { var fixture = new HangDumpInProcessProtocolFixture(TestContext.CancellationToken); try @@ -94,14 +102,18 @@ public async Task RegisteredLifecycle_ActivityBeforeReverseConnectionIsAcknowled Assert.DoesNotContain("Test host controller connected", fixture.ChildMessages); // This boundary is after the primary request lock was released and before the - // controller ever connects back or creates an inactivity timer. + // controller ever connects back or creates an inactivity timer. The activity stays + // pending: the signal loop only starts once the handshake has completed. await ConsumeAsync(fixture, "before-ready", "Discovery before ready 東京", DiscoveredTestNodeStateProperty.CachedInstance); - fixture.AssertSignalCount(1); + fixture.AssertSignalCount(0); fixture.ProcessInformation.VerifyNoOtherCalls(); Task controller = fixture.StartControllerAsync(); await fixture.AwaitAsync(Task.WhenAll(child, controller)); fixture.AssertReadyHandshake(); + await fixture.FlushActivityAsync(); + fixture.AssertSignalCount(1); await ConsumeAsync(fixture, "after-ready", "Discovery after ready Ω", DiscoveredTestNodeStateProperty.CachedInstance); + await fixture.FlushActivityAsync(); fixture.AssertSignalCount(2); fixture.ControllerClock.VerifyGet(value => value.UtcNow, Times.Exactly(2)); fixture.ChildClock.VerifyGet(value => value.UtcNow, Times.Never); @@ -139,6 +151,7 @@ public async Task RegisteredLifecycle_PreCanceledChildCallsCanRetry() fixture.AssertReadyHandshake(); Assert.AreEqual(originalEndpoint, fixture.PipeName); await ConsumeAsync(fixture, "accepted", "Accepted after cancellation Ω", PassedTestNodeStateProperty.CachedInstance); + await fixture.FlushActivityAsync(); fixture.AssertSignalCount(1); Assert.IsEmpty(RemovalMessages(fixture), "Rejected terminal input must not invent a running test."); await fixture.AwaitAsync(fixture.Controller.OnTestHostProcessExitedAsync(fixture.ProcessInformation.Object, fixture.Token)); @@ -172,6 +185,7 @@ public async Task RegisteredLifecycle_PreCanceledControllerStartCanRetry() Assert.AreEqual(originalEndpoint, fixture.PipeName); Assert.HasCount(2, fixture.ControllerMessages.Where(message => message.StartsWith("Wait for test host connection to the server pipe '", StringComparison.Ordinal))); await ConsumeAsync(fixture, "retry", "Controller retry 東京", DiscoveredTestNodeStateProperty.CachedInstance); + await fixture.FlushActivityAsync(); fixture.AssertSignalCount(1); await fixture.AwaitAsync(fixture.Controller.OnTestHostProcessExitedAsync(fixture.ProcessInformation.Object, fixture.Token)); } @@ -223,6 +237,7 @@ public async Task RegisteredLifecycle_CanceledControllerWaitCanRetryAfterPrimary Assert.HasCount(1, fixture.ControllerMessages.Where(message => message.StartsWith("Client connected to ", StringComparison.Ordinal))); Assert.HasCount(2, fixture.ControllerMessages.Where(message => message.StartsWith("Wait for test host connection to the server pipe '", StringComparison.Ordinal))); await ConsumeAsync(fixture, "after-wait-cancel", "Ready after controller cancellation Ω", DiscoveredTestNodeStateProperty.CachedInstance); + await fixture.FlushActivityAsync(); fixture.AssertSignalCount(1); await fixture.AwaitAsync(fixture.Controller.OnTestHostProcessExitedAsync(fixture.ProcessInformation.Object, fixture.Token)); } @@ -267,6 +282,7 @@ public async Task RegisteredLifecycle_ControllerWaitFailureCanRetry(bool foreign fixture.AssertReadyHandshake(); Assert.HasCount(2, fixture.ControllerMessages.Where(message => message.StartsWith("Wait for test host connection to the server pipe '", StringComparison.Ordinal))); await ConsumeAsync(fixture, "after-wait-failure", "Ready after diagnostic failure 東京", DiscoveredTestNodeStateProperty.CachedInstance); + await fixture.FlushActivityAsync(); fixture.AssertSignalCount(1); await fixture.AwaitAsync(fixture.Controller.OnTestHostProcessExitedAsync(fixture.ProcessInformation.Object, fixture.Token)); } @@ -349,6 +365,7 @@ public async Task RegisteredLifecycle_ControllerConnectedFailureStillCleansOwned await fixture.AwaitAsync(child); fixture.AssertReadyHandshake(); await ConsumeAsync(fixture, "connected-without-timer", "Discovery after connected diagnostic failure Ω", DiscoveredTestNodeStateProperty.CachedInstance); + await fixture.FlushActivityAsync(); fixture.AssertSignalCount(1); await fixture.AwaitAsync(fixture.Controller.OnTestHostProcessExitedAsync(fixture.ProcessInformation.Object, fixture.Token)); fixture.ProcessInformation.VerifyGet(value => value.HasExitedGracefully, Times.Once); @@ -380,6 +397,7 @@ public async Task RegisteredLifecycle_SupersededRetrySignalsWithoutLosingTracked : new FailedTestNodeStateProperty(); await ConsumeAsync(fixture, "retried", "Superseded retry", supersededState, new RetryAttemptProperty(1, isSuperseded: true)); Assert.IsEmpty(RemovalMessages(fixture)); + await fixture.FlushActivityAsync(); fixture.AssertSignalCount(1); await ConsumeAsync(fixture, "retried", "Final retry", PassedTestNodeStateProperty.CachedInstance, new RetryAttemptProperty(2, isSuperseded: false)); AssertRemoval(Assert.ContainsSingle(RemovalMessages(fixture)), "Original retry 東京", remaining: 1); @@ -387,7 +405,11 @@ public async Task RegisteredLifecycle_SupersededRetrySignalsWithoutLosingTracked string[] removals = RemovalMessages(fixture); Assert.HasCount(2, removals); AssertRemoval(removals[1], "Other tracked Ω", remaining: 0); - fixture.AssertSignalCount(3); + + // Both final results are forwarded as one coalesced signal. + fixture.AssertSignalCount(1); + await fixture.FlushActivityAsync(); + fixture.AssertSignalCount(2); await fixture.AwaitAsync(fixture.Controller.OnTestHostProcessExitedAsync(fixture.ProcessInformation.Object, fixture.Token)); fixture.AssertNoDumpWork(); } @@ -412,6 +434,7 @@ public async Task RegisteredLifecycle_PreCanceledExitLeavesChannelUsableForRetry Assert.AreEqual(rejected.Token, cancellation.CancellationToken); fixture.ProcessInformation.VerifyNoOtherCalls(); await ConsumeAsync(fixture, "after-rejected-exit", "Activity after rejected exit 東京", DiscoveredTestNodeStateProperty.CachedInstance); + await fixture.FlushActivityAsync(); fixture.AssertSignalCount(1); await fixture.AwaitAsync(fixture.Controller.OnTestHostProcessExitedAsync(fixture.ProcessInformation.Object, fixture.Token)); fixture.ProcessInformation.VerifyGet(value => value.HasExitedGracefully, Times.Once); @@ -475,17 +498,17 @@ public async Task RegisteredLifecycle_DisposeWithoutExitClosesClientsAndDrainsTa await fixture.BindAsync(); await fixture.ConnectAsync(); await ConsumeAsync(fixture, "before-disposal", "Activity before disposal Ω", DiscoveredTestNodeStateProperty.CachedInstance); + await fixture.FlushActivityAsync(); fixture.AssertSignalCount(1); await fixture.ShutdownAsync(useAsyncDisposal); await fixture.ShutdownAsync(useAsyncDisposal); Assert.IsTrue(fixture.AllTrackedTasksCompleted); - Assert.AreEqual(3, fixture.TrackedTransportTaskCount, "One primary accept and one loop for each registered direction must be drained."); + Assert.AreEqual(4, fixture.TrackedTransportTaskCount, "One primary accept, one loop for each registered direction and the activity signal loop must be drained."); fixture.ProcessInformation.VerifyNoOtherCalls(); - // CancellationToken.None makes the disposed client, not the canceled session token, - // the rejection boundary. The semaphore rejects before writing to a closed pipe. - await Assert.ThrowsExactlyAsync( - () => fixture.Consumer.ConsumeAsync(null!, Update("after-disposal", "No request after disposal", DiscoveredTestNodeStateProperty.CachedInstance), CancellationToken.None)); + // Consuming only records activity, so it completes after disposal. The stopped signal loop + // never forwards it to the closed pipe. + await fixture.AwaitAsync(fixture.Consumer.ConsumeAsync(null!, Update("after-disposal", "No request after disposal", DiscoveredTestNodeStateProperty.CachedInstance), CancellationToken.None)); fixture.AssertSignalCount(1); fixture.AssertNoDumpWork(); } diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/Helpers/HangDumpInProcessProtocolFixture.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/Helpers/HangDumpInProcessProtocolFixture.cs index 0c8a5af0e1..5b0f1393b4 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/Helpers/HangDumpInProcessProtocolFixture.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/Helpers/HangDumpInProcessProtocolFixture.cs @@ -36,6 +36,8 @@ internal sealed class HangDumpInProcessProtocolFixture private readonly ConcurrentQueue _transportTasks = new(); private readonly ConcurrentQueue _operations = new(); private readonly ConcurrentDictionary _observedOperations = new(); + private readonly ConcurrentQueue<(TimeSpan Delay, TaskCompletionSource Wait)> _activitySignalWaits = new(); + private readonly SemaphoreSlim _activitySignalWaitEntered = new(0); private readonly ICompositeExtensionFactory _consumerFactory; private readonly ICompositeExtensionFactory _sessionFactory; private HangDumpProcessLifetimeHandler? _controller; @@ -82,6 +84,20 @@ public HangDumpInProcessProtocolFixture(CancellationToken cancellationToken, boo return task; }); + // The activity indicator forwards coalesced activity from a background loop that waits between + // flushes. Each wait is held until a test advances it, so signal delivery is deterministic and + // never depends on wall-clock time. Cancellation still ends the wait, as Task.Delay does. + Scheduler.Setup(value => value.Delay(It.IsAny(), It.IsAny())) + .Returns((TimeSpan delay, CancellationToken token) => + { + var wait = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + CancellationTokenRegistration registration = token.Register(() => wait.TrySetCanceled(token)); + _ = wait.Task.ContinueWith(_ => registration.Dispose(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + _activitySignalWaits.Enqueue((delay, wait)); + _activitySignalWaitEntered.Release(); + return wait.Task; + }); + _controllerServices.AddServices( [ options, ControllerEnvironment.Object, ControllerClock.Object, _controllerLoggerFactory.Object, @@ -267,6 +283,25 @@ public void AssertReadyHandshake() AssertNoDumpWork(); } + /// + /// Ends the activity loop's current wait and returns once the loop has flushed any pending activity + /// and started its next wait. A pending signal is therefore acknowledged by the controller on return. + /// + public async Task FlushActivityAsync() + { + await AwaitAsync(_activitySignalWaitEntered.WaitAsync(Token)); + Assert.IsTrue(_activitySignalWaits.TryDequeue(out (TimeSpan Delay, TaskCompletionSource Wait) current)); + + // A one-hour timeout gives a tenth of the timeout capped at one second. + Assert.AreEqual(TimeSpan.FromSeconds(1), current.Delay); + Assert.IsTrue(current.Wait.TrySetResult(true), "The loop must still be waiting when the test advances it."); + + // The loop only waits again after the flush's request has been acknowledged. Leave that wait for + // the next advance. + await AwaitAsync(_activitySignalWaitEntered.WaitAsync(Token)); + _activitySignalWaitEntered.Release(); + } + public void AssertSignalCount(int count) { int tracedCount = TraceEnabled ? count : 0; From bd3306bfa541b1e614c296f498fef69545aac4f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Tue, 3 Nov 2026 12:39:54 +0100 Subject: [PATCH 8/9] Dispose the HangDump protocol fixture activity gate Close the activity-loop rendezvous semaphore after transport tasks drain and expose the existing cleanup through IAsyncDisposable, resolving CA1001 across all target frameworks. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../Helpers/HangDumpInProcessProtocolFixture.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/Helpers/HangDumpInProcessProtocolFixture.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/Helpers/HangDumpInProcessProtocolFixture.cs index 5b0f1393b4..5fd5f4fac5 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/Helpers/HangDumpInProcessProtocolFixture.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/Helpers/HangDumpInProcessProtocolFixture.cs @@ -26,7 +26,7 @@ namespace Microsoft.Testing.Extensions.UnitTests.Helpers; -internal sealed class HangDumpInProcessProtocolFixture +internal sealed class HangDumpInProcessProtocolFixture : IAsyncDisposable { private readonly CancellationTokenSource _lifetime; private readonly ServiceProvider _controllerServices = new(); @@ -379,6 +379,8 @@ public async Task ShutdownAsync(bool useAsyncDisposal) } } + public ValueTask DisposeAsync() => new(CloseAsync()); + public async Task CloseAsync() { if (_closed) @@ -390,6 +392,7 @@ public async Task CloseAsync() { await ShutdownAsync(useAsyncDisposal: false); Assert.IsTrue(AllTrackedTasksCompleted, "No task-owned pipe or lifecycle delegate may survive cleanup."); + _activitySignalWaitEntered.Dispose(); AssertNoDumpWork(); } finally From ace902258c24afc8344f8f61e71a7f254b765d8b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Tue, 3 Nov 2026 15:06:57 +0100 Subject: [PATCH 9/9] Keep HangDump deferred cleanup safe across repeated disposal Give synchronous and asynchronous disposal one atomic cleanup owner so later host disposal passes cannot close the pipe while its timed-out activity worker is still running. Add gated regression cases for repeated and mixed disposal calls, preserving the original bounded wait and eventual cleanup. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../HangDumpActivityIndicator.cs | 14 ++++++ .../HangDumpMutationTests.cs | 48 +++++++++++++++++-- 2 files changed, 57 insertions(+), 5 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs index 610cf165fe..788b02b871 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs @@ -38,6 +38,10 @@ internal sealed class HangDumpActivityIndicator : IDataConsumer, ITestSessionLif private volatile bool _exitSignalActivityIndicatorAsync; private int _activitySignalPending; + + // The first disposer retains ownership even when it must defer cleanup past the shutdown timeout. + private int _disposeStarted; + private CancellationTokenSource? _activitySignalCancellation; private Task? _activitySignalTask; private NamedPipeServer? _singleConnectionNamedPipeServer; @@ -278,6 +282,11 @@ public async Task OnTestSessionFinishingAsync(ITestSessionContext testSessionCon #if NETCOREAPP public async ValueTask DisposeAsync() { + if (Interlocked.Exchange(ref _disposeStarted, 1) != 0) + { + return; + } + // Wait (bounded) for the loop before disposing the pipe client it may be using. This also covers runs // where session finishing was skipped because execution or a lifecycle handler threw. If the wait times // out, the pipe client is disposed only when the loop stops. @@ -304,6 +313,11 @@ public async ValueTask DisposeAsync() public void Dispose() { + if (Interlocked.Exchange(ref _disposeStarted, 1) != 0) + { + return; + } + // Wait (bounded) for the loop before disposing the pipe client it may be using. If the wait times out, the // pipe client is disposed only when the loop stops. Task stop = StopActivitySignalLoopAsync(); diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpMutationTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpMutationTests.cs index e662fedc7b..b97f065ef0 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpMutationTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpMutationTests.cs @@ -188,6 +188,38 @@ public async Task Dispose_ShutdownTimeout_DefersPipeClientDisposalUntilTheLoopSt await AssertPipeClientDisposalDeferredAsync(indicator, loop, () => Task.Run(indicator.Dispose, TestContext.CancellationToken)); } + [TestMethod] + [DataRow(false, false, DisplayName = "ShutdownTimeout_DisposeThenDispose")] +#if NETCOREAPP + [DataRow(true, true, DisplayName = "ShutdownTimeout_DisposeAsyncThenDisposeAsync")] + [DataRow(true, false, DisplayName = "ShutdownTimeout_DisposeAsyncThenDispose")] + [DataRow(false, true, DisplayName = "ShutdownTimeout_DisposeThenDisposeAsync")] +#endif + public async Task Dispose_ShutdownTimeout_RepeatedCallsKeepPipeClientAlive(bool firstAsync, bool secondAsync) + { + HangDumpActivityIndicator indicator = CreateEnabledIndicator(); + SetPrivateField(indicator, "_activitySignalShutdownTimeout", TimeSpan.FromMilliseconds(50)); + GatedActivitySignalLoop loop = StartGatedActivitySignalLoop(indicator); + + await AssertPipeClientDisposalDeferredAsync( + indicator, + loop, + () => DisposeIndicatorAsync(firstAsync), + () => DisposeIndicatorAsync(secondAsync)); + + Task DisposeIndicatorAsync(bool useAsyncDisposal) + { +#if NETCOREAPP + if (useAsyncDisposal) + { + return indicator.DisposeAsync().AsTask(); + } +#endif + + return Task.Run(indicator.Dispose, TestContext.CancellationToken); + } + } + [TestMethod] public async Task OnTestSessionFinishingAsync_CanceledSessionWithPendingActivity_CompletesSoLaterHandlersRun() { @@ -206,20 +238,24 @@ public async Task OnTestSessionFinishingAsync_CanceledSessionWithPendingActivity Assert.AreEqual(0, GetPrivateField(indicator, "_activitySignalPending")); } - private async Task AssertPipeClientDisposalDeferredAsync(HangDumpActivityIndicator indicator, GatedActivitySignalLoop loop, Func dispose) + private async Task AssertPipeClientDisposalDeferredAsync(HangDumpActivityIndicator indicator, GatedActivitySignalLoop loop, params Func[] disposals) { object pipeClient = GetPrivateField(indicator, "_namedPipeClient"); try { - Task disposal = dispose(); - Assert.AreSame(disposal, await Task.WhenAny(disposal, Task.Delay(GateTimeout, TestContext.CancellationToken)), "Disposal must return after the shutdown timeout."); - await disposal; + foreach (Func dispose in disposals) + { + Task disposal = dispose(); + Assert.AreSame(disposal, await Task.WhenAny(disposal, Task.Delay(GateTimeout, TestContext.CancellationToken)), "Disposal must return after the shutdown timeout."); + await disposal; - Assert.IsFalse(GetPrivateField(pipeClient, "_disposed"), "The pipe client must not be disposed while an activity signal request may still use it."); + Assert.IsFalse(GetPrivateField(pipeClient, "_disposed"), "The pipe client must not be disposed while an activity signal request may still use it."); + } } finally { loop.Release(); + await loop.Completion; } Assert.IsTrue( @@ -262,6 +298,8 @@ private sealed class GatedActivitySignalLoop(Task cancellationObserved, TaskComp { public Task CancellationObserved { get; } = cancellationObserved; + public Task Completion => gate.Task; + public void Release() => gate.TrySetResult(true); }