diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs index 6890237f1e..d096159216 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs @@ -35,7 +35,6 @@ internal sealed class HangDumpActivityIndicator : IDataConsumer, ITestSessionLif private bool _exitSignalActivityIndicatorAsync; private NamedPipeServer? _singleConnectionNamedPipeServer; private PipeNameDescription? _pipeNameDescription; - private bool _sessionEndCalled; public HangDumpActivityIndicator( ICommandLineOptions commandLineOptions, @@ -61,7 +60,6 @@ public HangDumpActivityIndicator( ?? throw new InvalidOperationException($"Expected {pipeNameEnvironmentVariable} environment variable set."); _namedPipeClient = new NamedPipeClient(namedPipeName, _environment); _namedPipeClient.RegisterSerializer(new VoidResponseSerializer(), typeof(VoidResponse)); - _namedPipeClient.RegisterSerializer(new SessionEndSerializerRequestSerializer(), typeof(SessionEndSerializerRequest)); _namedPipeClient.RegisterSerializer(new ConsumerPipeNameRequestSerializer(), typeof(ConsumerPipeNameRequest)); _namedPipeClient.RegisterSerializer(new ActivitySignalRequestSerializer(), typeof(ActivitySignalRequest)); } @@ -183,51 +181,17 @@ or FailedTestNodeStateProperty or TimeoutTestNodeStateProperty or SkippedTestNod } } - public async Task OnTestSessionFinishingAsync(ITestSessionContext testSessionContext) - { - CancellationToken cancellationToken = testSessionContext.CancellationToken; - ApplicationStateGuard.Ensure(_namedPipeClient is not null); - - if (!await IsEnabledAsync().ConfigureAwait(false)) - { - return; - } - - await _namedPipeClient.RequestReplyAsync(new SessionEndSerializerRequest(), cancellationToken) - .TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, cancellationToken).ConfigureAwait(false); - - await _logger.LogDebugAsync("Signal for test session end'").ConfigureAwait(false); - _exitSignalActivityIndicatorAsync = true; - - await _logger.LogTraceAsync("Signaled by process for it's exit").ConfigureAwait(false); - _sessionEndCalled = true; - } + public Task OnTestSessionFinishingAsync(ITestSessionContext testSessionContext) + => Task.CompletedTask; #if NETCOREAPP - public async ValueTask DisposeAsync() + public ValueTask DisposeAsync() { _namedPipeClient?.Dispose(); - - // If the OnTestSessionFinishingAsync is not called means that something unhandled happened - // and we didn't correctly coordinate the shutdown with the HangDumpProcessLifetimeHandler. - // If we go do wait for the server we will hang. - if (_sessionEndCalled) - { - await DisposeHelper.DisposeAsync(_singleConnectionNamedPipeServer).ConfigureAwait(false); - } + return ValueTask.CompletedTask; } #endif public void Dispose() - { - _namedPipeClient?.Dispose(); - - // If the OnTestSessionFinishingAsync is not called means that something unhandled happened - // and we didn't correctly coordinate the shutdown with the HangDumpProcessLifetimeHandler. - // If we go do wait for the server we will hang. - if (_sessionEndCalled) - { - _singleConnectionNamedPipeServer?.Dispose(); - } - } + => _namedPipeClient?.Dispose(); } diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpProcessLifetimeHandler.cs b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpProcessLifetimeHandler.cs index e3f94934c3..4df89a7daf 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpProcessLifetimeHandler.cs +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpProcessLifetimeHandler.cs @@ -113,7 +113,6 @@ public async Task BeforeTestHostProcessStartAsync(CancellationToken cancellation _singleConnectionNamedPipeServer = new(_pipeNameDescription, CallbackAsync, _environment, _logger, _task, cancellationToken); _singleConnectionNamedPipeServer.RegisterSerializer(new VoidResponseSerializer(), typeof(VoidResponse)); - _singleConnectionNamedPipeServer.RegisterSerializer(new SessionEndSerializerRequestSerializer(), typeof(SessionEndSerializerRequest)); _singleConnectionNamedPipeServer.RegisterSerializer(new ConsumerPipeNameRequestSerializer(), typeof(ConsumerPipeNameRequest)); _singleConnectionNamedPipeServer.RegisterSerializer(new ActivitySignalRequestSerializer(), typeof(ActivitySignalRequest)); @@ -127,24 +126,7 @@ public async Task BeforeTestHostProcessStartAsync(CancellationToken cancellation private async Task CallbackAsync(IRequest request) { - if (request is SessionEndSerializerRequest) - { - await _logger.LogDebugAsync("Session end received by the test host").ConfigureAwait(false); - -#pragma warning disable IDE0031 // Null check can be simplified - analyzer doesn't consider multigating. But we can fix when https://github.com/dotnet/csharplang/issues/8631 is implemented. - if (_activityTimer is not null) - { -#if NETCOREAPP - await _activityTimer.DisposeAsync().ConfigureAwait(false); -#else - _activityTimer.Dispose(); -#endif - } - - _namedPipeClient?.Dispose(); - return VoidResponse.CachedInstance; - } - else if (request is ConsumerPipeNameRequest consumerPipeNameRequest) + if (request is ConsumerPipeNameRequest consumerPipeNameRequest) { await _logger.LogDebugAsync($"Consumer pipe name received '{consumerPipeNameRequest.PipeName}'").ConfigureAwait(false); _namedPipeClient = new NamedPipeClient(consumerPipeNameRequest.PipeName, _environment); @@ -217,6 +199,15 @@ public async Task OnTestHostProcessExitedAsync(ITestHostProcessInformation testH { cancellationToken.ThrowIfCancellationRequested(); + if (_activityTimer is not null) + { +#if NETCOREAPP + await _activityTimer.DisposeAsync().ConfigureAwait(false); +#else + _activityTimer.Dispose(); +#endif + } + if (!testHostProcessInformation.HasExitedGracefully) { _logger.LogDebug($"Testhost didn't exit gracefully '{testHostProcessInformation.ExitCode}')"); diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/Serializers/SessionEndSerializer.cs b/src/Platform/Microsoft.Testing.Extensions.HangDump/Serializers/SessionEndSerializer.cs deleted file mode 100644 index 8e547f6974..0000000000 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/Serializers/SessionEndSerializer.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using Microsoft.Testing.Platform.IPC; -using Microsoft.Testing.Platform.IPC.Serializers; - -namespace Microsoft.Testing.Extensions.HangDump.Serializers; - -internal sealed class SessionEndSerializerRequest : IRequest; - -internal sealed class SessionEndSerializerRequestSerializer : BaseSerializer, INamedPipeSerializer -{ - public int Id => 2; - - public object Deserialize(Stream stream) - => new SessionEndSerializerRequest(); - - public void Serialize(object _, Stream __) - { - } -} diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HangDumpTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HangDumpTests.cs index 3833822964..adb139ced3 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HangDumpTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HangDumpTests.cs @@ -157,6 +157,25 @@ public async Task HangDump_InvalidFormat_ShouldFail() """); } + [TestMethod] + public async Task HangDump_WithForegroundThreadAfterSessionFinish_CreateDump() + { + string resultDirectory = Path.Combine(AssetFixture.TargetAssetPath, Guid.NewGuid().ToString("N"), TargetFrameworks.NetCurrent); + var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, "HangDump", TargetFrameworks.NetCurrent); + TestHostResult testHostResult = await testHost.ExecuteAsync( + $"--hangdump --hangdump-timeout 8s --results-directory {resultDirectory}", + new Dictionary + { + { "SLEEPTIMEMS1", "4000" }, + { "SLEEPTIMEMS2", "4000" }, + { "SPAWN_FOREGROUND_THREAD", "true" }, + }, + cancellationToken: TestContext.CancellationToken); + testHostResult.AssertExitCodeIs(ExitCodes.TestHostProcessExitedNonGracefully); + string[] dumpFiles = Directory.GetFiles(resultDirectory, "HangDump*.dmp", SearchOption.AllDirectories); + Assert.ContainsSingle(dumpFiles, $"Expected single dump file. Found: {Environment.NewLine}{string.Join(Environment.NewLine, dumpFiles)}{Environment.NewLine}{testHostResult}"); + } + public sealed class TestAssetFixture() : TestAssetFixtureBase(AcceptanceFixture.NuGetGlobalPackagesFolder) { private const string AssetName = "AssetFixture"; @@ -254,6 +273,18 @@ public async Task ExecuteRequestAsync(ExecuteRequestContext context) Properties = new PropertyBag(new PassedTestNodeStateProperty()), })); + // Spawn a foreground thread that continues running after the test session finishes + // to verify that hang dump triggers even after session end + if (Environment.GetEnvironmentVariable("SPAWN_FOREGROUND_THREAD") == "true") + { + Thread foregroundThread = new Thread(() => + { + Thread.Sleep(600000); // Sleep for 10 minutes to trigger hang dump + }); + foregroundThread.IsBackground = false; // Foreground thread to prevent process exit + foregroundThread.Start(); + } + context.Complete(); } }