Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,14 @@ internal sealed class HangDumpActivityIndicator : IDataConsumer, ITestSessionLif
private readonly NamedPipeClient? _namedPipeClient;
private readonly bool _traceLevelEnabled;
private readonly ConcurrentDictionary<TestNodeUid, (string Name, Type Type, DateTimeOffset StartTime)> _testsCurrentExecutionState = new();
private static readonly TimeSpan ActivitySignalShutdownTimeout = TimeSpan.FromSeconds(30);

private bool _exitSignalActivityIndicatorAsync;
private readonly TimeSpan _activitySignalInterval;

private volatile bool _exitSignalActivityIndicatorAsync;
private int _activitySignalPending;
private CancellationTokenSource? _activitySignalCancellation;
private Task? _activitySignalTask;
private NamedPipeServer? _singleConnectionNamedPipeServer;
private PipeNameDescription? _pipeNameDescription;

Expand All @@ -58,6 +64,7 @@ public HangDumpActivityIndicator(
_namedPipeClient.RegisterSerializer(new VoidResponseSerializer(), typeof(VoidResponse));
_namedPipeClient.RegisterSerializer(new ConsumerPipeNameRequestSerializer(), typeof(ConsumerPipeNameRequest));
_namedPipeClient.RegisterSerializer(new ActivitySignalRequestSerializer(), typeof(ActivitySignalRequest));
_activitySignalInterval = HangDumpOptions.GetActivitySignalInterval(HangDumpOptions.GetTimeout(_commandLineOptions));
}
}

Expand Down Expand Up @@ -100,13 +107,87 @@ await _namedPipeClient.RequestReplyAsync<ConsumerPipeNameRequest, VoidResponse>(
// 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)
{
// Do nothing, we're stopping
}
}

private async Task SignalActivityLoopAsync(CancellationToken stopToken, CancellationToken sessionCancellationToken)
{
try
{
while (true)
{
await _task.Delay(_activitySignalInterval, stopToken).ConfigureAwait(false);
Comment thread
Evangelink marked this conversation as resolved.
Resolved

// 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);
Comment thread
Evangelink marked this conversation as resolved.
Resolved
}
}
catch (OperationCanceledException) when (stopToken.IsCancellationRequested)
{
// 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);
Comment thread
Evangelink marked this conversation as resolved.
Resolved
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)
{
if (Interlocked.Exchange(ref _activitySignalPending, 0) == 0 || _exitSignalActivityIndicatorAsync)
{
return;
}

ApplicationStateGuard.Ensure(_namedPipeClient is not null);
await _namedPipeClient.RequestReplyAsync<ActivitySignalRequest, VoidResponse>(ActivitySignalRequest.Instance, cancellationToken).ConfigureAwait(false);

if (_traceLevelEnabled)
{
await _logger.LogTraceAsync("Activity signal sent.").ConfigureAwait(false);
}
}

private async Task<IResponse> CallbackAsync(IRequest request)
{
if (request is GetInProgressTestsRequest)
Expand Down Expand Up @@ -167,31 +248,72 @@ 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, VoidResponse>(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);
Comment thread
Evangelink marked this conversation as resolved.
Resolved
}
}

public Task OnTestSessionFinishingAsync(ITestSessionContext testSessionContext)
=> Task.CompletedTask;
public async Task OnTestSessionFinishingAsync(ITestSessionContext testSessionContext)
{
if (Volatile.Read(ref _activitySignalTask) is null)
{
return;
}

// 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);
Comment thread
Evangelink marked this conversation as resolved.
Resolved
}

#if NETCOREAPP
public ValueTask DisposeAsync()
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.
Task stop = StopActivitySignalLoopAsync();
try
{
Task completed = await Task.WhenAny(stop, Task.Delay(ActivitySignalShutdownTimeout)).ConfigureAwait(false);
if (completed == stop)
{
await stop.ConfigureAwait(false);
}
else
{
ObserveLateStopFailure(stop);
Comment thread
Evangelink marked this conversation as resolved.
Resolved
}
}
catch (Exception ex)
{
await _logger.LogDebugAsync($"Hang dump activity signal loop failed during disposal: {ex.Message}").ConfigureAwait(false);
}

_namedPipeClient?.Dispose();
return ValueTask.CompletedTask;
}
#endif

public void Dispose()
=> _namedPipeClient?.Dispose();
{
// Wait (bounded) for the loop before disposing the pipe client it may be using.
Task stop = StopActivitySignalLoopAsync();
try
{
if (!stop.Wait(ActivitySignalShutdownTimeout))
{
ObserveLateStopFailure(stop);
}
}
catch (Exception ex)
{
_logger.LogDebug($"Hang dump activity signal loop failed during disposal: {ex.Message}");
}

_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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,40 @@
// 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;

/// <summary>
/// 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.
/// </summary>
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;
}

/// <summary>
/// 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.
/// </summary>
public static TimeSpan GetInactivityTimerDueTime(TimeSpan hangTimeout)
=> hangTimeout + GetActivitySignalInterval(hangTimeout);
Comment thread
Evangelink marked this conversation as resolved.
Resolved
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -127,9 +128,8 @@ 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);
_activityTimerDueTime = HangDumpOptions.GetInactivityTimerDueTime(_activityTimerValue.Value);

if (_commandLineOptions.TryGetOptionArgumentList(HangDumpCommandLineProvider.HangDumpTypeOptionName, out string[]? dumpType))
{
Expand Down Expand Up @@ -212,7 +212,7 @@ private async Task<IResponse> CallbackAsync(IRequest request)
}
else if (request is ActivitySignalRequest)
{
_activityTimer?.Change(_activityTimerValue!.Value, TimeSpan.FromMilliseconds(-1));
_activityTimer?.Change(_activityTimerDueTime!.Value, TimeSpan.FromMilliseconds(-1));

if (_traceEnabled)
{
Expand Down Expand Up @@ -293,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)
Expand Down
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
#nullable enable
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
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,91 @@ 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<ILogger>(), DateTimeOffset.UtcNow);

await indicator.ConsumeAsync(null!, CreateUpdate("uid", InProgressTestNodeStateProperty.CachedInstance), CancellationToken.None);
Assert.AreEqual(0, GetPrivateField<int>(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<int>(indicator, "_activitySignalPending"));
}

#if NETCOREAPP
[TestMethod]
public async Task DisposeAsync_StopsAndAwaitsActivitySignalLoop()
{
using HangDumpActivityIndicator indicator = CreateIndicator(Mock.Of<ILogger>(), 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<Task?>(indicator, "_activitySignalTask"));
}
#endif

[TestMethod]
public async Task OnTestSessionFinishingAsync_AfterDispose_DoesNotTouchTheDisposedLoop()
{
HangDumpActivityIndicator indicator = CreateIndicator(Mock.Of<ILogger>(), DateTimeOffset.UtcNow);
StartFakeActivitySignalLoop(indicator);
indicator.Dispose();

Mock<ITestSessionContext> 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<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
cancellation.Token.Register(() => loopCompletion.TrySetResult(true));
Comment thread
Copilot marked this conversation as resolved.
Resolved
SetPrivateField(indicator, "_activitySignalCancellation", cancellation);
SetPrivateField<Task?>(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")]
[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),
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)
{
Mock<ILoggerFactory> loggerFactory = new();
Expand Down Expand Up @@ -248,6 +333,7 @@ public async Task BeforeStartAndConsumerHandshake_InitializeEveryFieldAndSeriali
await handler.BeforeTestHostProcessStartAsync(TestContext.CancellationToken);

Assert.AreEqual(TimeSpan.FromMinutes(30), GetPrivateField<TimeSpan?>(handler, "_activityTimerValue"));
Assert.AreEqual(TimeSpan.FromMinutes(30) + TimeSpan.FromSeconds(1), GetPrivateField<TimeSpan?>(handler, "_activityTimerDueTime"));
Assert.IsNull(GetPrivateField<DateTimeOffset?>(handler, "_deadlineDumpAt"));
Assert.Contains("Hang dump timeout setup 00:30:00.", messages);

Expand Down
Loading