diff --git a/docs/Changelog-Platform.md b/docs/Changelog-Platform.md index bb59a575c2..2ddcccd79c 100644 --- a/docs/Changelog-Platform.md +++ b/docs/Changelog-Platform.md @@ -30,6 +30,9 @@ See full log [of v4.3.3...v4.4.0](https://github.com/microsoft/testfx/compare/v4 * Fix `--report-azdo` faulting the test run with `Could not find solution root, .git not found in ... or any parent directory.` when annotating a failing test from an application that does not run inside a git checkout (a published app, a container, or `browser-wasm`, whose virtual filesystem has no `.git`); the reporter now degrades to a message-only annotation, matching the GitHub Actions reporter in [#10313](https://github.com/microsoft/testfx/issues/10313) * Fix TRX attachments being silently dropped on .NET Framework when the destination path exceeds the Windows `MAX_PATH` limit. Both per-test `ResultFile` entries and session-level `CollectorDataEntries` attachments (crash dumps, hang dumps and other extension artifacts) could disappear from the report while the run still reported success in [#10312](https://github.com/microsoft/testfx/issues/10312) * Report attachments that could not be copied into the TRX results directory on the output device instead of only in the `RunInfos` section of the generated TRX in [#10312](https://github.com/microsoft/testfx/issues/10312) +* Fix `--publish-azdo-test-results` creating and completing one Azure DevOps test run per `--retry-failed-tests` attempt instead of one run for the build, which recorded a test rescued by a retry as failed forever in the earlier run. The run's lifetime now belongs to the retry orchestrator process, which outlives every attempt: it creates the run once, hands its id to the attempts through the inherited `TESTINGPLATFORM_AZUREDEVOPS_TESTRUNID` variable, and completes it once. Orchestrator processes take part in the existing per-build coordination too, so several test projects sharing a results directory still publish into a single run. Note that a retried test still contributes one result per attempt inside that single run (`Failed` and then `Passed`); collapsing those into one result carrying the final outcome is tracked separately in [#10360](https://github.com/microsoft/testfx/issues/10360) +* Keep an Azure DevOps test run open while a peer test project that is still running has yet to publish into it. The owner previously gave up after a fixed 30 second grace period, so in a multi-project build a project that finished early could complete the run and make every result the remaining projects sent afterwards be rejected. Participants whose process is provably alive are now waited for, bounded by a hard cap so a leaked process cannot stall a build in [#10360](https://github.com/microsoft/testfx/issues/10360) +* Release what an `ITestHostOrchestratorApplicationLifetime` acquired in `BeforeRunAsync` when the orchestration is canceled or fails. `AfterRunAsync` was only invoked when the orchestrator completed normally, so an Azure DevOps test run created before a cancellation — or before `--retry-failed-tests` rejected server mode or hot reload — was left `InProgress` and never appeared in the build's Tests tab in [#10360](https://github.com/microsoft/testfx/issues/10360) ## [2.3.3] - 2026-07-28 diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsConstants.cs b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsConstants.cs index 09d051034a..b892ddddea 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsConstants.cs +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsConstants.cs @@ -24,6 +24,65 @@ internal static class AzureDevOpsConstants /// public const string TfBuildEnabledValue = "true"; + /// + /// Name of the environment variable that carries the id of an Azure DevOps test run created by an + /// ancestor process, so that every process taking part in the same logical run publishes into it + /// instead of creating one of its own. + /// + /// + /// Set by before the orchestrated test hosts are + /// launched, and inherited by them. This is what makes --publish-azdo-test-results produce a + /// single run when combined with --retry-failed-tests: the run outlives every attempt, so the + /// attempts must neither create nor complete it. + /// + /// The value is <buildId>:<runId>. The build id is what makes a stale value safe: + /// an agent that reuses its environment, or a long-lived process that inherited the variable from an + /// earlier build, would otherwise redirect this build's results into an unrelated (and probably + /// already completed) run, which Azure DevOps then rejects. + /// + /// + /// Deliberately carries nothing else. The rest of the publish configuration is derived independently + /// by each process from the same Azure Pipelines variables, and the access token must never be + /// propagated through a channel that is easier to observe than the agent's own environment. + /// + /// + public const string TestRunIdEnvironmentVariableName = "TESTINGPLATFORM_AZUREDEVOPS_TESTRUNID"; + + /// + /// Formats the handoff value that tells descendant processes which run to publish into. + /// + public static string FormatInheritedTestRunId(int buildId, int runId) + => $"{buildId.ToString(CultureInfo.InvariantCulture)}:{runId.ToString(CultureInfo.InvariantCulture)}"; + + /// + /// Returns the Azure DevOps test run id established by an ancestor process for , + /// or when the current process is the one that owns the run's lifetime. + /// + /// + /// A value that is malformed, non-positive, or belongs to a different build is treated as absent: the + /// variable is an internal handoff, so anything we cannot make sense of means the handoff did not + /// happen for this build, and falling back to the normal (self-owned) path keeps publishing working + /// rather than sending results into somebody else's run. + /// + public static int? TryGetInheritedTestRunId(IEnvironment environment, int buildId) + { + string? value = environment.GetEnvironmentVariable(TestRunIdEnvironmentVariableName); + if (value is null || value.Length == 0) + { + return null; + } + + int separatorIndex = value.IndexOf(':'); + return separatorIndex <= 0 + ? null + : int.TryParse(value[..separatorIndex], NumberStyles.Integer, CultureInfo.InvariantCulture, out int inheritedBuildId) + && inheritedBuildId == buildId + && int.TryParse(value[(separatorIndex + 1)..], NumberStyles.Integer, CultureInfo.InvariantCulture, out int runId) + && runId > 0 + ? runId + : null; + } + /// /// Returns when the current process is running inside an /// Azure DevOps build/release agent (i.e. when the TF_BUILD environment diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsExtensions.cs b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsExtensions.cs index f59b486a79..669c7885dd 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsExtensions.cs +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsExtensions.cs @@ -106,6 +106,23 @@ public static void AddAzureDevOpsProvider(this ITestApplicationBuilder builder) // Registered last so its OnTestSessionFinishingAsync (the closing ##[endgroup]) runs after // the other AzDO handlers' finishing callbacks, ensuring the group wraps all their output. builder.TestHost.AddTestSessionLifetimeHandler(compositeLogGroupReporter); + + // A test run must span every process an orchestrator launches (e.g. each --retry-failed-tests + // attempt), so its lifetime belongs to the orchestrator process rather than to any single test + // host. This is only built when an orchestrator is active, and is inert otherwise. + builder.TestHostOrchestrator.AddTestHostOrchestratorApplicationLifetime(serviceProvider => + new AzureDevOpsTestRunOrchestratorLifetime( + serviceProvider.GetCommandLineOptions(), + serviceProvider.GetConfiguration(), + serviceProvider.GetEnvironment(), + serviceProvider.GetFileSystem(), + serviceProvider.GetOutputDevice(), + serviceProvider.GetTestApplicationModuleInfo(), + new AzureDevOpsTestResultsClient(serviceProvider.GetTask(), serviceProvider.GetClock()), + serviceProvider.GetTask(), + serviceProvider.GetClock(), + serviceProvider.GetLoggerFactory())); + builder.CommandLine.AddProvider(() => new AzureDevOpsCommandLineProvider()); } diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsLivePublishingModels.cs b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsLivePublishingModels.cs index 52217cd98f..a791165d48 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsLivePublishingModels.cs +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsLivePublishingModels.cs @@ -133,6 +133,17 @@ public AzureDevOpsTestResultsPublisherOptions(int batchSize, TimeSpan flushInter { } + /// + /// Gets the longest the owner will hold a run open waiting for peers that are provably still running. + /// + /// + /// is the grace period for participants that cannot be + /// proven alive; this is the hard cap that also applies to live ones, so a leaked process cannot stall + /// a build indefinitely. Generous because it bounds a whole test project, not a single test: the cost + /// of stopping too early is that the peer's remaining results are rejected by Azure DevOps. + /// + public TimeSpan CoordinationFinalizeMaxWaitTime { get; init; } = TimeSpan.FromMinutes(15); + public static AzureDevOpsTestResultsPublisherOptions Default { get; } = new(100, TimeSpan.FromSeconds(5), 40, TimeSpan.FromMilliseconds(250), TimeSpan.FromSeconds(30), TimeSpan.FromHours(4), TimeSpan.FromMinutes(2)); } diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsTestResultsPublisher.Configuration.cs b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsPublishConfigurationFactory.cs similarity index 56% rename from src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsTestResultsPublisher.Configuration.cs rename to src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsPublishConfigurationFactory.cs index bce49f2789..e18e34a73d 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsTestResultsPublisher.Configuration.cs +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsPublishConfigurationFactory.cs @@ -1,32 +1,49 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// 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.Extensions.AzureDevOpsReport.Resources; using Microsoft.Testing.Extensions.Reporting; using Microsoft.Testing.Platform; +using Microsoft.Testing.Platform.CommandLine; using Microsoft.Testing.Platform.Configurations; +using Microsoft.Testing.Platform.Helpers; +using Microsoft.Testing.Platform.Services; namespace Microsoft.Testing.Extensions.AzureDevOpsReport; -internal sealed partial class AzureDevOpsTestResultsPublisher +/// +/// Builds the Azure DevOps live-publishing configuration from the Azure Pipelines environment. +/// +/// +/// Shared by the test-host publisher and by , which +/// runs in the orchestrator process and therefore has no test session to derive it from. Both must agree +/// on the collection, project and build being targeted, so the derivation lives in one place. +/// +internal static class AzureDevOpsPublishConfigurationFactory { - private bool TryCreatePublishConfiguration([NotNullWhen(true)] out AzureDevOpsPublishConfiguration? publishConfiguration, [NotNullWhen(false)] out string? warning) + public static bool TryCreate( + ICommandLineOptions commandLineOptions, + IConfiguration configuration, + IEnvironment environment, + ITestApplicationModuleInfo testApplicationModuleInfo, + [NotNullWhen(true)] out AzureDevOpsPublishConfiguration? publishConfiguration, + [NotNullWhen(false)] out string? warning) { publishConfiguration = null; warning = null; List missingVariables = []; - bool isTfBuild = AzureDevOpsConstants.IsRunningInAzureDevOps(_environment); + bool isTfBuild = AzureDevOpsConstants.IsRunningInAzureDevOps(environment); if (!isTfBuild) { missingVariables.Add($"{AzureDevOpsConstants.TfBuildEnvironmentVariableName}={AzureDevOpsConstants.TfBuildEnabledValue}"); } - string? collectionUri = GetRequiredEnvironmentVariable("SYSTEM_COLLECTIONURI", missingVariables); - string? project = GetRequiredEnvironmentVariable("SYSTEM_TEAMPROJECT", missingVariables); - string? accessToken = GetRequiredEnvironmentVariable("SYSTEM_ACCESSTOKEN", missingVariables); - string? buildIdText = GetRequiredEnvironmentVariable("BUILD_BUILDID", missingVariables); + string? collectionUri = GetRequiredEnvironmentVariable(environment, "SYSTEM_COLLECTIONURI", missingVariables); + string? project = GetRequiredEnvironmentVariable(environment, "SYSTEM_TEAMPROJECT", missingVariables); + string? accessToken = GetRequiredEnvironmentVariable(environment, "SYSTEM_ACCESSTOKEN", missingVariables); + string? buildIdText = GetRequiredEnvironmentVariable(environment, "BUILD_BUILDID", missingVariables); if (missingVariables.Count > 0) { @@ -40,34 +57,37 @@ private bool TryCreatePublishConfiguration([NotNullWhen(true)] out AzureDevOpsPu return false; } - string currentTestApplicationPath = _testApplicationModuleInfo.GetCurrentTestApplicationFullPath(); - string assemblyName = _testApplicationModuleInfo.TryGetAssemblyName() ?? Path.GetFileNameWithoutExtension(currentTestApplicationPath); + string currentTestApplicationPath = testApplicationModuleInfo.GetCurrentTestApplicationFullPath(); + string assemblyName = testApplicationModuleInfo.TryGetAssemblyName() ?? Path.GetFileNameWithoutExtension(currentTestApplicationPath); string automatedTestStorage = Path.GetFileNameWithoutExtension(currentTestApplicationPath); string targetFrameworkMoniker = TargetFrameworkMonikerHelper.GetTargetFrameworkMonikerIncludingPlatform(); - string agentName = _environment.GetEnvironmentVariable("AGENT_NAME") ?? _environment.MachineName; - string? stageName = _environment.GetEnvironmentVariable("SYSTEM_STAGENAME"); - string? jobName = _environment.GetEnvironmentVariable("SYSTEM_JOBNAME"); + string agentName = environment.GetEnvironmentVariable("AGENT_NAME") ?? environment.MachineName; + string? stageName = environment.GetEnvironmentVariable("SYSTEM_STAGENAME"); + string? jobName = environment.GetEnvironmentVariable("SYSTEM_JOBNAME"); string runName = GetRunName(assemblyName, targetFrameworkMoniker, agentName, stageName, jobName); - string resultsDirectory = _configuration.GetTestResultDirectory(); + string resultsDirectory = configuration.GetTestResultDirectory(); - if (_commandLineOptions.TryGetOptionArgumentList(AzureDevOpsCommandLineOptions.PublishAzureDevOpsRunNameOptionName, out string[]? arguments) && arguments is [string configuredRunName]) + if (commandLineOptions.TryGetOptionArgumentList(AzureDevOpsCommandLineOptions.PublishAzureDevOpsRunNameOptionName, out string[]? arguments) && arguments is [string configuredRunName]) { runName = configuredRunName; } publishConfiguration = new AzureDevOpsPublishConfiguration(collectionUri!, project!, accessToken!, buildId, runName, automatedTestStorage, resultsDirectory) { - PipelineReference = CreatePipelineReference(stageName, jobName), + PipelineReference = CreatePipelineReference(environment, stageName, jobName), }; return true; } - private AzureDevOpsPipelineReference? CreatePipelineReference(string? stageName, string? jobName) + public static string BuildTestRunUrl(AzureDevOpsPublishConfiguration configuration, int runId) + => $"{configuration.CollectionUri.TrimEnd('/')}/{Uri.EscapeDataString(configuration.Project)}/_TestManagement/Runs?runId={runId}&_a=resultQuery"; + + private static AzureDevOpsPipelineReference? CreatePipelineReference(IEnvironment environment, string? stageName, string? jobName) { - string? phaseName = _environment.GetEnvironmentVariable("SYSTEM_PHASENAME"); - int? stageAttempt = GetOptionalEnvironmentVariableAsInt32("SYSTEM_STAGEATTEMPT"); - int? phaseAttempt = GetOptionalEnvironmentVariableAsInt32("SYSTEM_PHASEATTEMPT"); - int? jobAttempt = GetOptionalEnvironmentVariableAsInt32("SYSTEM_JOBATTEMPT"); + string? phaseName = environment.GetEnvironmentVariable("SYSTEM_PHASENAME"); + int? stageAttempt = GetOptionalEnvironmentVariableAsInt32(environment, "SYSTEM_STAGEATTEMPT"); + int? phaseAttempt = GetOptionalEnvironmentVariableAsInt32(environment, "SYSTEM_PHASEATTEMPT"); + int? jobAttempt = GetOptionalEnvironmentVariableAsInt32(environment, "SYSTEM_JOBATTEMPT"); // Azure DevOps rejects a reference that names nothing, and a run without any stage/job context is // better linked to the build alone than to an empty reference. @@ -82,17 +102,17 @@ private bool TryCreatePublishConfiguration([NotNullWhen(true)] out AzureDevOpsPu jobAttempt); } - private int? GetOptionalEnvironmentVariableAsInt32(string variableName) - => int.TryParse(_environment.GetEnvironmentVariable(variableName), NumberStyles.Integer, CultureInfo.InvariantCulture, out int value) + private static int? GetOptionalEnvironmentVariableAsInt32(IEnvironment environment, string variableName) + => int.TryParse(environment.GetEnvironmentVariable(variableName), NumberStyles.Integer, CultureInfo.InvariantCulture, out int value) ? value : null; private static string? NullIfWhiteSpace(string? value) => RoslynString.IsNullOrWhiteSpace(value) ? null : value; - private string? GetRequiredEnvironmentVariable(string variableName, List missingVariables) + private static string? GetRequiredEnvironmentVariable(IEnvironment environment, string variableName, List missingVariables) { - string? value = _environment.GetEnvironmentVariable(variableName); + string? value = environment.GetEnvironmentVariable(variableName); if (RoslynString.IsNullOrWhiteSpace(value)) { missingVariables.Add(variableName); diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsRunIdCoordinator.cs b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsRunIdCoordinator.cs index 966a012cae..6c508e1f5b 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsRunIdCoordinator.cs +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsRunIdCoordinator.cs @@ -13,6 +13,11 @@ namespace Microsoft.Testing.Extensions.AzureDevOpsReport; internal sealed class AzureDevOpsRunIdCoordinator { private const string CoordinationFilePrefix = "azdo-runid"; + + /// + /// Build id recorded for a legacy plain-PID lease, which carries no build context of its own. + /// + private const int LegacyLeaseBuildId = 0; private static readonly JsonSerializerOptions JsonSerializerOptions = new() { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, @@ -54,7 +59,7 @@ public async Task AcquireRunAsync(AzureDevOpsPublishC if (ownsOwnerFile) { int runId = await createRunAsync(cancellationToken).ConfigureAwait(false); - await WriteRunIdFileAsync(runIdFilePath, configuration, runId, cancellationToken).ConfigureAwait(false); + await TryWriteRunIdFileAsync(runIdFilePath, configuration, runId, cancellationToken).ConfigureAwait(false); return new AzureDevOpsCoordinatedRun(runId, true, configuration.BuildId, configuration.ResultsDirectory, runIdFilePath, ownerFilePath, participantFilePath); } @@ -65,7 +70,7 @@ public async Task AcquireRunAsync(AzureDevOpsPublishC if (ownsOwnerFile) { int runId = await createRunAsync(cancellationToken).ConfigureAwait(false); - await WriteRunIdFileAsync(runIdFilePath, configuration, runId, cancellationToken).ConfigureAwait(false); + await TryWriteRunIdFileAsync(runIdFilePath, configuration, runId, cancellationToken).ConfigureAwait(false); return new AzureDevOpsCoordinatedRun(runId, true, configuration.BuildId, configuration.ResultsDirectory, runIdFilePath, ownerFilePath, participantFilePath); } @@ -100,8 +105,28 @@ public async Task AcquireRunAsync(AzureDevOpsPublishC } } + /// + /// Creates a handle to a run established by an ancestor process, which also owns completing it. + /// + /// + /// No coordination files are involved: file-based coordination exists to elect an owner among peer + /// processes that cannot see each other, whereas here the owner is already known and outlives all of + /// them. and are therefore no-ops for the + /// returned run. + /// + public static AzureDevOpsCoordinatedRun CreateInheritedRun(int runId, AzureDevOpsPublishConfiguration configuration) + => new(runId, IsOwner: false, configuration.BuildId, configuration.ResultsDirectory, RunIdFilePath: string.Empty, OwnerFilePath: string.Empty, ParticipantFilePath: string.Empty) + { + IsInherited = true, + }; + public async Task RenewLeaseAsync(AzureDevOpsCoordinatedRun coordinatedRun, CancellationToken cancellationToken) { + if (coordinatedRun.IsInherited) + { + return; + } + await WriteLeaseFileAsync(coordinatedRun.ParticipantFilePath, CreateLeaseFile(coordinatedRun.BuildId), overwrite: true, cancellationToken).ConfigureAwait(false); if (coordinatedRun.IsOwner) @@ -112,6 +137,13 @@ public async Task RenewLeaseAsync(AzureDevOpsCoordinatedRun coordinatedRun, Canc public async Task FinalizeRunAsync(AzureDevOpsCoordinatedRun coordinatedRun, Func finalizeRunAsync, CancellationToken cancellationToken) { + // The ancestor process that created the run completes it once every participant has exited. + // Completing it here would close the run while later attempts are still to come. + if (coordinatedRun.IsInherited) + { + return; + } + TryDeleteFile(coordinatedRun.ParticipantFilePath); if (!coordinatedRun.IsOwner) @@ -119,11 +151,24 @@ public async Task FinalizeRunAsync(AzureDevOpsCoordinatedRun coordinatedRun, Fun return; } - DateTimeOffset timeoutAt = _clock.UtcNow + _options.CoordinationFinalizeTimeout; + // Two bounds, because "still waiting" and "not responding" are different situations. A participant + // whose process is provably alive is still publishing, and completing the run out from under it + // makes Azure DevOps reject everything it sends afterwards — losing results that used to reach a + // (separate) run before builds were consolidated. So keep waiting for live participants, up to a + // hard cap so a leaked process cannot stall the build forever. Participants we cannot prove alive + // (unreadable, mid-write) only get the short grace period. + DateTimeOffset unresponsiveDeadline = _clock.UtcNow + _options.CoordinationFinalizeTimeout; + DateTimeOffset hardDeadline = _clock.UtcNow + _options.CoordinationFinalizeMaxWaitTime; while (true) { string[] participantFiles = _fileSystem.GetFiles(coordinatedRun.ResultsDirectory, GetParticipantSearchPattern(coordinatedRun.BuildId), SearchOption.TopDirectoryOnly); + + // Never wait on ourselves. Deleting our own lease above is best-effort (an antivirus or + // indexer holding the handle makes it fail and is exactly what TryDeleteFile tolerates), and + // this process trivially passes every liveness check — so without this the owner would keep + // renewing the grace period against its own leftover file until the hard cap. + participantFiles = [.. participantFiles.Where(participantFile => !string.Equals(participantFile, coordinatedRun.ParticipantFilePath, PathComparison.Comparison))]; participantFiles = CleanupStaleParticipants(participantFiles); if (participantFiles.Length == 0) @@ -131,9 +176,23 @@ public async Task FinalizeRunAsync(AzureDevOpsCoordinatedRun coordinatedRun, Fun break; } - if (_clock.UtcNow >= timeoutAt) + if (AnyParticipantProcessAlive(participantFiles)) { - _logger.LogWarning(string.Format(CultureInfo.InvariantCulture, AzureDevOpsResources.AzureDevOpsLivePublishingFinalizeWaitTimedOut, _options.CoordinationFinalizeTimeout, participantFiles.Length)); + unresponsiveDeadline = _clock.UtcNow + _options.CoordinationFinalizeTimeout; + } + + DateTimeOffset now = _clock.UtcNow; + bool hardDeadlineExpired = now >= hardDeadline; + bool unresponsiveDeadlineExpired = now >= unresponsiveDeadline; + if (hardDeadlineExpired || unresponsiveDeadlineExpired || cancellationToken.IsCancellationRequested) + { + TimeSpan timeout = hardDeadlineExpired + ? _options.CoordinationFinalizeMaxWaitTime + : _options.CoordinationFinalizeTimeout; + // Best-effort: this is the recovery path, and letting a failing log provider escape here + // would skip finalizeRunAsync below and leave the run "InProgress" - the exact outcome the + // warning is reporting on. + TryLogWarning(string.Format(CultureInfo.InvariantCulture, AzureDevOpsResources.AzureDevOpsLivePublishingFinalizeWaitTimedOut, timeout, participantFiles.Length)); break; } @@ -151,6 +210,32 @@ public async Task FinalizeRunAsync(AzureDevOpsCoordinatedRun coordinatedRun, Fun } } + /// + /// Returns whether at least one of the given participants belongs to a process that is still running. + /// + /// + /// Distinguishes "a peer is still publishing" from "a lease is lying around that nobody can vouch for". + /// Only the former justifies holding the run open past the short grace period. + /// + private bool AnyParticipantProcessAlive(string[] participantFiles) + { + foreach (string participantFile in participantFiles) + { + AzureDevOpsLeaseFile? lease = ReadLease(participantFile).Lease; + int? processId = lease?.ProcessId ?? TryGetPid(participantFile); + + // Our own process is always alive, so counting it would mean waiting for ourselves forever. + if (processId is { } participantProcessId + && participantProcessId != _environment.ProcessId + && IsProcessAlive(participantProcessId)) + { + return true; + } + } + + return false; + } + private string[] CleanupStaleParticipants(string[] participantFiles) { var activeParticipants = new List(); @@ -228,11 +313,16 @@ private static bool IsProcessAlive(int processId) AzureDevOpsRunIdFile? runIdFile = JsonSerializer.Deserialize(content, JsonSerializerOptions); if (runIdFile is not null) { - if (runIdFile.ExpiresAt <= _clock.UtcNow || runIdFile.BuildId != buildId) + // A run-id file whose expiry has passed is only stale if nobody owns it any more. + // An owner that does not renew its lease (a run orchestrator holds one for the whole + // orchestration) is still publishing into that run, so deleting the file here would + // send every joiner off to create a second run for the same build. + if (runIdFile.BuildId != buildId + || (runIdFile.ExpiresAt <= _clock.UtcNow && !IsOwnerStillAlive(ReadLease(ownerFilePath)))) { TryDeleteFile(runIdFilePath); } - else + else if (runIdFile.BuildId == buildId) { return runIdFile; } @@ -262,9 +352,7 @@ private static bool IsProcessAlive(int processId) LeaseReadResult ownerLease = ReadLease(ownerFilePath); bool ownerStillActive = ownerLease.Status is LeaseFileStatus.Active or LeaseFileStatus.TransientReadError - || (ownerLease.Status == LeaseFileStatus.Expired - && ownerLease.Lease is { } expiredLease - && IsProcessAlive(expiredLease.ProcessId)); + || (ownerLease.Status == LeaseFileStatus.Expired && IsOwnerStillAlive(ownerLease)); if (!ownerStillActive) { @@ -308,7 +396,8 @@ private async Task TryAcquireOwnerAsync(string ownerFilePath, int buildId, return false; } - if (existing.Status is LeaseFileStatus.NotFound or LeaseFileStatus.Expired) + if (existing.Status is LeaseFileStatus.NotFound + || (existing.Status == LeaseFileStatus.Expired && !IsOwnerStillAlive(existing))) { TryDeleteFile(ownerFilePath); return await TryWriteLeaseFileAsync(ownerFilePath, lease, overwrite: false, cancellationToken).ConfigureAwait(false); @@ -317,6 +406,26 @@ private async Task TryAcquireOwnerAsync(string ownerFilePath, int buildId, return false; } + /// + /// Returns whether the process that wrote a lease is still running. + /// + /// + /// Liveness, not wall-clock expiry, is the authoritative signal that an owner is still in charge. Not + /// every owner renews its lease: a run orchestrator holds one for the whole orchestration without a + /// natural point to refresh it, so on a build longer than + /// its lease goes stale + /// while it is very much still publishing. Taking over then would create a second Azure DevOps run for + /// the same build. Refusing to take over from a live process errs towards one run rather than two, + /// which is also how already treats participants. + /// + /// The legacy plain-PID lease format is excluded: deliberately reports it as + /// expired so it can be replaced, and it carries no build id to tell us which run it belongs to. A + /// reused pid would otherwise let a stale file from an older version block takeover indefinitely. + /// + /// + private static bool IsOwnerStillAlive(LeaseReadResult lease) + => lease.Lease is { BuildId: not LegacyLeaseBuildId } ownerLease && IsProcessAlive(ownerLease.ProcessId); + private AzureDevOpsLeaseFile CreateLeaseFile(int buildId) => new(_environment.ProcessId, buildId, _clock.UtcNow + _options.CoordinationFileExpiration); @@ -342,8 +451,10 @@ private LeaseReadResult ReadLease(string path) if (int.TryParse(content, NumberStyles.Integer, CultureInfo.InvariantCulture, out int processId)) { - // Legacy plain-PID lease format: treat as expired so the caller can take over. - return new LeaseReadResult(LeaseFileStatus.Expired, new AzureDevOpsLeaseFile(processId, 0, DateTimeOffset.MinValue)); + // Legacy plain-PID lease format: treat as expired so the caller can take over. The sentinel + // build id marks it as carrying no build context, which is what keeps IsOwnerStillAlive from + // treating a reused pid as a live owner. + return new LeaseReadResult(LeaseFileStatus.Expired, new AzureDevOpsLeaseFile(processId, LegacyLeaseBuildId, DateTimeOffset.MinValue)); } // The file exists but neither parser yielded a usable value. It might be mid-write — @@ -368,6 +479,49 @@ private LeaseReadResult ReadLease(string path) private async Task WriteRunIdFileAsync(string runIdFilePath, AzureDevOpsPublishConfiguration configuration, int runId, CancellationToken cancellationToken) => await WriteJsonFileAsync(runIdFilePath, new AzureDevOpsRunIdFile(runId, configuration.BuildId, configuration.CollectionUri, configuration.Project, _clock.UtcNow + _options.CoordinationFileExpiration), overwrite: true, cancellationToken).ConfigureAwait(false); + /// + /// Publishes the run id for peers to join, tolerating a failure to write the file. + /// + /// + /// The run already exists in Azure DevOps at this point, and this process is the only one that can + /// close it. Letting anything propagate here would unwind into the caller's cleanup, which deletes the + /// leases and never hands back the run, stranding it in "InProgress" forever. So nothing escapes: + /// not a file-system failure, not cancellation, and not a logger provider that throws while reporting + /// it. Losing the file costs peers the ability to join this run, which is degraded but recoverable; + /// losing the run itself is not. + /// + private async Task TryWriteRunIdFileAsync(string runIdFilePath, AzureDevOpsPublishConfiguration configuration, int runId, CancellationToken cancellationToken) + { + try + { + await WriteRunIdFileAsync(runIdFilePath, configuration, runId, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) + { + TryLogWarning($"{AzureDevOpsResources.AzureDevOpsLivePublishingFailedToWriteCoordinationFile} {runIdFilePath}: {ex.Message}"); + } + } + + /// + /// Logs a warning, swallowing any failure from the logging providers. + /// + /// + /// The aggregate logger invokes each provider directly, so a failing provider propagates. Every caller + /// here is already recovering from something, and letting a diagnostic replace the failure it was + /// describing would lose both. + /// + private void TryLogWarning(string message) + { + try + { + _logger.LogWarning(message); + } + catch (Exception) + { + // There is nowhere left to report this: the diagnostic logger is the fallback sink. + } + } + [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026", Justification = "The coordination payload type is internal, fixed, and controlled by this extension.")] [UnconditionalSuppressMessage("Aot", "IL3050", Justification = "The coordination payload type is internal, fixed, and controlled by this extension.")] private Task WriteLeaseFileAsync(string path, AzureDevOpsLeaseFile payload, bool overwrite, CancellationToken cancellationToken) @@ -419,11 +573,11 @@ private void TryDeleteFile(string path) } catch (IOException ex) { - _logger.LogWarning($"{AzureDevOpsResources.AzureDevOpsLivePublishingFailedToDeleteCoordinationFile} {path}: {ex.Message}"); + TryLogWarning($"{AzureDevOpsResources.AzureDevOpsLivePublishingFailedToDeleteCoordinationFile} {path}: {ex.Message}"); } catch (UnauthorizedAccessException ex) { - _logger.LogWarning($"{AzureDevOpsResources.AzureDevOpsLivePublishingFailedToDeleteCoordinationFile} {path}: {ex.Message}"); + TryLogWarning($"{AzureDevOpsResources.AzureDevOpsLivePublishingFailedToDeleteCoordinationFile} {path}: {ex.Message}"); } } @@ -458,7 +612,19 @@ internal sealed record AzureDevOpsCoordinatedRun( string ResultsDirectory, string RunIdFilePath, string OwnerFilePath, - string ParticipantFilePath); + string ParticipantFilePath) +{ + /// + /// Gets a value indicating whether the run was created by an ancestor process, which also owns closing it. + /// + /// + /// Declared as a property rather than a positional parameter so that adding it does not change the + /// record's constructor and deconstructor signatures. An inherited run has no coordination files of + /// its own: the ancestor decides when the run ends, so there is no owner to elect and no participant + /// set to drain. + /// + public bool IsInherited { get; init; } +} internal sealed record AzureDevOpsRunIdFile( [property: JsonPropertyName("runId")] int RunId, diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsTestResultsPublisher.cs b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsTestResultsPublisher.cs index 02dfcbcc19..eecca5fcf3 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsTestResultsPublisher.cs +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsTestResultsPublisher.cs @@ -133,7 +133,7 @@ public Task IsEnabledAsync() public async Task OnTestSessionStartingAsync(ITestSessionContext testSessionContext) { - if (!TryCreatePublishConfiguration(out AzureDevOpsPublishConfiguration? publishConfiguration, out string? warning)) + if (!AzureDevOpsPublishConfigurationFactory.TryCreate(_commandLineOptions, _configuration, _environment, _testApplicationModuleInfo, out AzureDevOpsPublishConfiguration? publishConfiguration, out string? warning)) { await WarnAsync(warning, testSessionContext.CancellationToken).ConfigureAwait(false); return; @@ -144,10 +144,16 @@ public async Task OnTestSessionStartingAsync(ITestSessionContext testSessionCont try { - _coordinatedRun = await _runIdCoordinator.AcquireRunAsync( - publishConfiguration, - cancellationToken => _client.CreateTestRunAsync(publishConfiguration, cancellationToken), - testSessionContext.CancellationToken).ConfigureAwait(false); + // An orchestrator (e.g. retry) creates the run before launching any test host, because the run + // must span every attempt. When that happened, join the existing run: this process neither + // created it nor can tell whether it is the last one to publish into it, so it must not + // complete it either. See AzureDevOpsTestRunOrchestratorLifetime. + _coordinatedRun = AzureDevOpsConstants.TryGetInheritedTestRunId(_environment, publishConfiguration.BuildId) is { } inheritedRunId + ? AzureDevOpsRunIdCoordinator.CreateInheritedRun(inheritedRunId, publishConfiguration) + : await _runIdCoordinator.AcquireRunAsync( + publishConfiguration, + cancellationToken => _client.CreateTestRunAsync(publishConfiguration, cancellationToken), + testSessionContext.CancellationToken).ConfigureAwait(false); CurrentRunId = _coordinatedRun.RunId; // Results stream into the run as tests complete, but the build's Tests tab only lists the run @@ -162,7 +168,7 @@ await DisplayAsync( CultureInfo.InvariantCulture, AzureDevOpsResources.AzureDevOpsLivePublishingRunCreated, CurrentRunId.Value, - BuildTestRunUrl(publishConfiguration, CurrentRunId.Value)), + AzureDevOpsPublishConfigurationFactory.BuildTestRunUrl(publishConfiguration, CurrentRunId.Value)), testSessionContext.CancellationToken).ConfigureAwait(false); } @@ -171,10 +177,12 @@ await DisplayAsync( _backgroundFlushCts = new CancellationTokenSource(); _backgroundFlushTask = Task.Run(() => BackgroundFlushLoopAsync(_backgroundFlushCts.Token)); } - catch (Exception ex) when (ex is not OperationCanceledException) + catch (Exception ex) when (!testSessionContext.CancellationToken.IsCancellationRequested) { // Reset state before reporting so a failure to display the warning can never leave the - // publisher half-initialized. + // publisher half-initialized. The filter tests the caller's token rather than the exception + // type because the HTTP client surfaces its own internal timeouts as TaskCanceledException; + // those must be reported, not rethrown as if the user had canceled. _publishConfiguration = null; _coordinatedRun = null; CurrentRunId = null; @@ -221,9 +229,6 @@ private async Task DisplayCoreAsync(IOutputDeviceData data, CancellationToken ca } } - private static string BuildTestRunUrl(AzureDevOpsPublishConfiguration configuration, int runId) - => $"{configuration.CollectionUri.TrimEnd('/')}/{Uri.EscapeDataString(configuration.Project)}/_TestManagement/Runs?runId={runId}&_a=resultQuery"; - /// /// Logs a warning, swallowing any failure from the logging providers. /// @@ -382,7 +387,7 @@ await WarnAsync( { // Use a fresh, non-canceled token so finalization (marking the run Aborted/Completed) // succeeds even when the test session itself has been canceled. - using var cleanupCts = new CancellationTokenSource(_options.CoordinationFinalizeTimeout + TimeSpan.FromSeconds(60)); + using var cleanupCts = new CancellationTokenSource(_options.CoordinationFinalizeMaxWaitTime + TimeSpan.FromSeconds(60)); await _runIdCoordinator.FinalizeRunAsync( _coordinatedRun, cancellationToken => _client.UpdateTestRunStateAsync(_publishConfiguration, CurrentRunId.Value, finalState, cancellationToken), diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsTestRunOrchestratorLifetime.cs b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsTestRunOrchestratorLifetime.cs new file mode 100644 index 0000000000..6ae3fa3075 --- /dev/null +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsTestRunOrchestratorLifetime.cs @@ -0,0 +1,288 @@ +// 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.Extensions.AzureDevOpsReport.Resources; +using Microsoft.Testing.Extensions.Reporting; +using Microsoft.Testing.Platform.CommandLine; +using Microsoft.Testing.Platform.Configurations; +using Microsoft.Testing.Platform.Extensions.OutputDevice; +using Microsoft.Testing.Platform.Extensions.TestHostOrchestrator; +using Microsoft.Testing.Platform.Helpers; +using Microsoft.Testing.Platform.Logging; +using Microsoft.Testing.Platform.OutputDevice; +using Microsoft.Testing.Platform.Services; + +namespace Microsoft.Testing.Extensions.AzureDevOpsReport; + +/// +/// Owns the Azure DevOps test run for the whole orchestrated execution, so that a run spanning several +/// test host processes is created once and completed once. +/// +/// +/// +/// An orchestrator (today: --retry-failed-tests) runs each attempt in its own test host process, +/// each of which used to create and complete its own Azure DevOps run. That produced one run per attempt +/// and left a test rescued by a retry recorded as failed forever in the earlier run (see +/// ). +/// +/// +/// The run's lifetime therefore has to belong to a process that outlives every attempt, and the +/// orchestrator process is the only one that qualifies: attempts are sequential and an attempt cannot +/// know whether it is the last one, because the retry options are stripped from its command line. This +/// lifetime is only built when an orchestrator is active, so it is inert for a normal run — and it is +/// deliberately orchestrator-agnostic, taking no dependency on the retry extension. +/// +/// +internal sealed class AzureDevOpsTestRunOrchestratorLifetime : ITestHostOrchestratorApplicationLifetime, IOutputDeviceDataProducer +{ + private readonly ICommandLineOptions _commandLineOptions; + private readonly IConfiguration _configuration; + private readonly IEnvironment _environment; + private readonly IFileSystem _fileSystem; + private readonly IOutputDevice _outputDevice; + private readonly ITestApplicationModuleInfo _testApplicationModuleInfo; + private readonly IAzureDevOpsTestResultsClient _client; + private readonly ITask _task; + private readonly IClock _clock; + private readonly ILogger _logger; + private readonly AzureDevOpsTestResultsPublisherOptions _options; + + private AzureDevOpsPublishConfiguration? _publishConfiguration; + private AzureDevOpsRunIdCoordinator? _runIdCoordinator; + private AzureDevOpsCoordinatedRun? _coordinatedRun; + + public AzureDevOpsTestRunOrchestratorLifetime( + ICommandLineOptions commandLineOptions, + IConfiguration configuration, + IEnvironment environment, + IFileSystem fileSystem, + IOutputDevice outputDevice, + ITestApplicationModuleInfo testApplicationModuleInfo, + IAzureDevOpsTestResultsClient client, + ITask task, + IClock clock, + ILoggerFactory loggerFactory) + : this(commandLineOptions, configuration, environment, fileSystem, outputDevice, testApplicationModuleInfo, client, task, clock, loggerFactory.CreateLogger(), AzureDevOpsTestResultsPublisherOptions.Default) + { + } + + internal AzureDevOpsTestRunOrchestratorLifetime( + ICommandLineOptions commandLineOptions, + IConfiguration configuration, + IEnvironment environment, + IFileSystem fileSystem, + IOutputDevice outputDevice, + ITestApplicationModuleInfo testApplicationModuleInfo, + IAzureDevOpsTestResultsClient client, + ITask task, + IClock clock, + ILogger logger, + AzureDevOpsTestResultsPublisherOptions options) + { + _commandLineOptions = commandLineOptions; + _configuration = configuration; + _environment = environment; + _fileSystem = fileSystem; + _outputDevice = outputDevice; + _testApplicationModuleInfo = testApplicationModuleInfo; + _client = client; + _task = task; + _clock = clock; + _logger = logger; + _options = options; + } + + public string Uid => nameof(AzureDevOpsTestRunOrchestratorLifetime); + + public string Version => ExtensionVersion.DefaultSemVer; + + public string DisplayName => AzureDevOpsResources.DisplayName; + + public string Description => AzureDevOpsResources.Description; + + internal int? RunId => _coordinatedRun?.RunId; + + public Task IsEnabledAsync() + => Task.FromResult(_commandLineOptions.IsOptionSet(AzureDevOpsCommandLineOptions.PublishAzureDevOpsTestResultsOptionName)); + + public async Task BeforeRunAsync(CancellationToken cancellationToken) + { + if (!AzureDevOpsPublishConfigurationFactory.TryCreate(_commandLineOptions, _configuration, _environment, _testApplicationModuleInfo, out AzureDevOpsPublishConfiguration? publishConfiguration, out string? warning)) + { + // Not configured for live publishing. Keep this off the output device — the test host publisher + // reports it there once — but still record it in the diagnostic log. + TryLogWarning(warning); + return; + } + + // A run id already in the environment for this build means an ancestor process owns the run (e.g. + // nested orchestrators). Leave its lifetime alone and let the test hosts join it as they would + // anyway. Checked after the configuration is built because the build id is what scopes the handoff. + if (AzureDevOpsConstants.TryGetInheritedTestRunId(_environment, publishConfiguration.BuildId) is not null) + { + return; + } + + AzureDevOpsRunIdCoordinator coordinator = new(_fileSystem, _task, _clock, _environment, _logger, _options); + try + { + // Go through the coordinator rather than creating a run directly, so that several test + // applications sharing a results directory (a multi-project 'dotnet test') still land in a + // single run for the build. Orchestrator processes are well-behaved participants: this one + // outlives every attempt it launches, so it can hold the lease for all of them. + _coordinatedRun = await coordinator.AcquireRunAsync( + publishConfiguration, + createRunCancellationToken => _client.CreateTestRunAsync(publishConfiguration, createRunCancellationToken), + cancellationToken).ConfigureAwait(false); + _runIdCoordinator = coordinator; + _publishConfiguration = publishConfiguration; + } + catch (Exception ex) when (!cancellationToken.IsCancellationRequested) + { + // No run was acquired (AcquireRunAsync cleans up after itself), so the test hosts fall back to + // coordinating among themselves — the pre-existing behaviour, not a loss of results. + // The filter tests the caller's token rather than the exception type because the HTTP client + // surfaces its own internal timeouts as TaskCanceledException; those must be reported, not + // rethrown as if the user had canceled. + await WarnAsync($"{AzureDevOpsResources.AzureDevOpsLivePublishingCreateRunFailed} {ex.Message}", cancellationToken).ConfigureAwait(false); + return; + } + + // The run now exists and this process owns closing it. Nothing below may discard that state: doing + // so would make AfterRunAsync skip finalization and leave the run "InProgress" forever. + try + { + // Published before any test host is launched so that every orchestrated process inherits it. + _environment.SetEnvironmentVariable(AzureDevOpsConstants.TestRunIdEnvironmentVariableName, AzureDevOpsConstants.FormatInheritedTestRunId(publishConfiguration.BuildId, _coordinatedRun.RunId)); + + // Only the process that created the run announces it; the others share the same id and would + // just repeat the same line. + if (_coordinatedRun.IsOwner) + { + await DisplayAsync( + string.Format( + CultureInfo.InvariantCulture, + AzureDevOpsResources.AzureDevOpsLivePublishingRunCreated, + _coordinatedRun.RunId, + AzureDevOpsPublishConfigurationFactory.BuildTestRunUrl(publishConfiguration, _coordinatedRun.RunId)), + cancellationToken).ConfigureAwait(false); + } + } + catch (Exception ex) when (!cancellationToken.IsCancellationRequested) + { + // Without the handoff the attempts coordinate among themselves instead of joining this run, + // which is degraded but not broken. The run itself stays owned by this process. + TryLogWarning($"{AzureDevOpsResources.AzureDevOpsLivePublishingRunIdHandoffFailed} {ex.Message}"); + } + } + + public async Task AfterRunAsync(int exitCode, CancellationToken cancellationToken) + { + // Read and clear together so a second invocation cannot finalize the run twice. AfterRunAsync can + // be reached without a successful BeforeRunAsync (another lifetime may have faulted first), in + // which case there is nothing to release. + AzureDevOpsCoordinatedRun? coordinatedRun = _coordinatedRun; + AzureDevOpsRunIdCoordinator? coordinator = _runIdCoordinator; + AzureDevOpsPublishConfiguration? publishConfiguration = _publishConfiguration; + _coordinatedRun = null; + _runIdCoordinator = null; + _publishConfiguration = null; + + if (coordinatedRun is null || coordinator is null || publishConfiguration is null) + { + return; + } + + // Stop handing the run id to any process started later: the run is about to be closed, and a + // straggler publishing into a completed run would be rejected by Azure DevOps. + TrySetEnvironmentVariable(AzureDevOpsConstants.TestRunIdEnvironmentVariableName, null); + + // Azure DevOps uses "Aborted" for cancellation and session-level infrastructure failures. + // Individual failing tests must still complete the run, so only exit codes that are not a test + // result are treated as an abort — mirroring how the test host publisher finalizes a run it owns. + bool exitCodeIsTestResult = exitCode is (int)ExitCode.Success or (int)ExitCode.AtLeastOneTestFailed; + string finalState = cancellationToken.IsCancellationRequested || !exitCodeIsTestResult + ? AzureDevOpsLivePublishingConstants.AbortedTestRunState + : AzureDevOpsLivePublishingConstants.CompletedTestRunState; + + try + { + // A fresh token so the run is still closed when the orchestration itself was canceled: a run + // left "InProgress" never shows up in the build's Tests tab, which looks like total data loss + // even though every result was uploaded. + using var cleanupCts = new CancellationTokenSource(_options.CoordinationFinalizeMaxWaitTime + TimeSpan.FromSeconds(60)); + await coordinator.FinalizeRunAsync( + coordinatedRun, + finalizeCancellationToken => _client.UpdateTestRunStateAsync(publishConfiguration, coordinatedRun.RunId, finalState, finalizeCancellationToken), + cleanupCts.Token).ConfigureAwait(false); + } + catch (Exception ex) + { + // Cancellation is handled here too: this step runs on its own token, so an expiry is a + // finalization failure rather than a canceled session, and must not escape and fail an + // otherwise successful run. + await WarnAsync( + $"{AzureDevOpsResources.AzureDevOpsLivePublishingCompleteRunFailed} {ex.Message} {AzureDevOpsResources.AzureDevOpsLivePublishingRunLeftInProgress}", + CancellationToken.None).ConfigureAwait(false); + } + } + + /// + /// Sets an environment variable, swallowing any failure. + /// + /// + /// Called from teardown, where the host may refuse the write (a SecurityException on + /// .NET Framework). Failing to withdraw the handoff is far less harmful than failing the run. + /// + private void TrySetEnvironmentVariable(string name, string? value) + { + try + { + _environment.SetEnvironmentVariable(name, value); + } + catch (Exception ex) + { + TryLogWarning($"{AzureDevOpsResources.AzureDevOpsLivePublishingRunIdHandoffFailed} {ex.Message}"); + } + } + + /// + /// Reports a live-publishing problem both to the diagnostic log and to the output device, so that it + /// is visible in CI logs instead of only in an opt-in log file. Never throws: it is invoked from + /// error-recovery paths where propagating would turn a warning into a failed run. + /// + private async Task WarnAsync(string message, CancellationToken cancellationToken) + { + TryLogWarning(message); + await DisplayCoreAsync(new WarningMessageOutputDeviceData(message), cancellationToken).ConfigureAwait(false); + } + + private Task DisplayAsync(string message, CancellationToken cancellationToken) + => DisplayCoreAsync(new SessionMessageOutputDeviceData(message), cancellationToken); + + private async Task DisplayCoreAsync(IOutputDeviceData data, CancellationToken cancellationToken) + { + try + { + await _outputDevice.DisplayAsync(this, data, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) + { + // The message is already in the diagnostic log (for warnings); losing the console copy is + // preferable to failing the test run from inside a diagnostic helper. + TryLogWarning($"{AzureDevOpsResources.AzureDevOpsLivePublishingWarningDisplayFailed} {ex.Message}"); + } + } + + private void TryLogWarning(string message) + { + try + { + _logger.LogWarning(message); + } + catch (Exception) + { + // There is nowhere left to report this: the diagnostic logger is the fallback sink. + } + } +} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/InternalAPI/InternalAPI.Unshipped.txt b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/InternalAPI/InternalAPI.Unshipped.txt index 81a18d904e..c9fdd4fa12 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/InternalAPI/InternalAPI.Unshipped.txt +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/InternalAPI/InternalAPI.Unshipped.txt @@ -36,3 +36,25 @@ override Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineRefer override Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference.ToString() -> string! static Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference.operator !=(Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference? left, Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference? right) -> bool static Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference.operator ==(Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference? left, Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference? right) -> bool +const Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsConstants.TestRunIdEnvironmentVariableName = "TESTINGPLATFORM_AZUREDEVOPS_TESTRUNID" -> string! +Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsCoordinatedRun.IsInherited.get -> bool +Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsCoordinatedRun.IsInherited.init -> void +Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPublishConfigurationFactory +Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsTestRunOrchestratorLifetime +Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsTestRunOrchestratorLifetime.AfterRunAsync(int exitCode, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! +Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsTestRunOrchestratorLifetime.BeforeRunAsync(System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! +Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsTestRunOrchestratorLifetime.Description.get -> string! +Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsTestRunOrchestratorLifetime.DisplayName.get -> string! +Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsTestRunOrchestratorLifetime.IsEnabledAsync() -> System.Threading.Tasks.Task! +Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsTestRunOrchestratorLifetime.RunId.get -> int? +Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsTestRunOrchestratorLifetime.Uid.get -> string! +Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsTestRunOrchestratorLifetime.Version.get -> string! +static Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPublishConfigurationFactory.BuildTestRunUrl(Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPublishConfiguration! configuration, int runId) -> string! +static Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPublishConfigurationFactory.TryCreate(Microsoft.Testing.Platform.CommandLine.ICommandLineOptions! commandLineOptions, Microsoft.Testing.Platform.Configurations.IConfiguration! configuration, Microsoft.Testing.Platform.Helpers.IEnvironment! environment, Microsoft.Testing.Platform.Services.ITestApplicationModuleInfo! testApplicationModuleInfo, out Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPublishConfiguration? publishConfiguration, out string? warning) -> bool +static Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsRunIdCoordinator.CreateInheritedRun(int runId, Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPublishConfiguration! configuration) -> Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsCoordinatedRun! +Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsTestRunOrchestratorLifetime.AzureDevOpsTestRunOrchestratorLifetime(Microsoft.Testing.Platform.CommandLine.ICommandLineOptions! commandLineOptions, Microsoft.Testing.Platform.Configurations.IConfiguration! configuration, Microsoft.Testing.Platform.Helpers.IEnvironment! environment, Microsoft.Testing.Platform.Helpers.IFileSystem! fileSystem, Microsoft.Testing.Platform.OutputDevice.IOutputDevice! outputDevice, Microsoft.Testing.Platform.Services.ITestApplicationModuleInfo! testApplicationModuleInfo, Microsoft.Testing.Extensions.AzureDevOpsReport.IAzureDevOpsTestResultsClient! client, Microsoft.Testing.Platform.Helpers.ITask! task, Microsoft.Testing.Platform.Helpers.IClock! clock, Microsoft.Testing.Platform.Logging.ILogger! logger, Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsTestResultsPublisherOptions! options) -> void +Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsTestRunOrchestratorLifetime.AzureDevOpsTestRunOrchestratorLifetime(Microsoft.Testing.Platform.CommandLine.ICommandLineOptions! commandLineOptions, Microsoft.Testing.Platform.Configurations.IConfiguration! configuration, Microsoft.Testing.Platform.Helpers.IEnvironment! environment, Microsoft.Testing.Platform.Helpers.IFileSystem! fileSystem, Microsoft.Testing.Platform.OutputDevice.IOutputDevice! outputDevice, Microsoft.Testing.Platform.Services.ITestApplicationModuleInfo! testApplicationModuleInfo, Microsoft.Testing.Extensions.AzureDevOpsReport.IAzureDevOpsTestResultsClient! client, Microsoft.Testing.Platform.Helpers.ITask! task, Microsoft.Testing.Platform.Helpers.IClock! clock, Microsoft.Testing.Platform.Logging.ILoggerFactory! loggerFactory) -> void +Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsTestResultsPublisherOptions.CoordinationFinalizeMaxWaitTime.get -> System.TimeSpan +Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsTestResultsPublisherOptions.CoordinationFinalizeMaxWaitTime.init -> void +static Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsConstants.FormatInheritedTestRunId(int buildId, int runId) -> string! +static Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsConstants.TryGetInheritedTestRunId(Microsoft.Testing.Platform.Helpers.IEnvironment! environment, int buildId) -> int? diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/AzureDevOpsResources.resx b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/AzureDevOpsResources.resx index be5617f059..b58dc4239b 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/AzureDevOpsResources.resx +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/AzureDevOpsResources.resx @@ -162,6 +162,9 @@ Azure DevOps live publishing failed to delete coordination file + + Azure DevOps live publishing failed to write coordination file + Azure DevOps live publishing timed out after {0} waiting for {1} participant file(s); finalizing the run anyway. {0} is the finalize wait timeout. {1} is the number of participant files still pending. @@ -210,6 +213,9 @@ Azure DevOps live publishing found an azdo-runid.<buildId>.json file for a different Azure DevOps project. {Locked="azdo-runid.<buildId>.json"} + + Azure DevOps live publishing failed to update the test run id handoff. + The Azure DevOps test run was not marked as completed and may not appear in the build's Tests tab. diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.cs.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.cs.xlf index 6172beaa2c..9dd7bcade2 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.cs.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.cs.xlf @@ -62,6 +62,11 @@ Živému publikování Azure DevOps se nepodařilo odstranit koordinační soubor + + Azure DevOps live publishing failed to write coordination file + Azure DevOps live publishing failed to write coordination file + + Azure DevOps live publishing timed out after {0} waiting for {1} participant file(s); finalizing the run anyway. Živému publikování Azure DevOps vypršel časový limit po {0} čekání na soubory účastníka ({1}). Běh se přesto dokončí. @@ -127,6 +132,11 @@ Živé publikování Azure DevOps nalezlo soubor azdo-runid.<buildId>.json pro jiný projekt Azure DevOps. {Locked="azdo-runid.<buildId>.json"} + + Azure DevOps live publishing failed to update the test run id handoff. + Azure DevOps live publishing failed to update the test run id handoff. + + The Azure DevOps test run was not marked as completed and may not appear in the build's Tests tab. The Azure DevOps test run was not marked as completed and may not appear in the build's Tests tab. diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.de.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.de.xlf index 505e09eda3..9dcbfbc7c8 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.de.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.de.xlf @@ -62,6 +62,11 @@ Die Azure DevOps Liveveröffentlichung konnte die Koordinierungsdatei nicht löschen. + + Azure DevOps live publishing failed to write coordination file + Azure DevOps live publishing failed to write coordination file + + Azure DevOps live publishing timed out after {0} waiting for {1} participant file(s); finalizing the run anyway. Die Azure DevOps Liveveröffentlichung hat nach {0} beim Warten auf {1} Teilnehmerdatei(en) eine Zeitüberschreitung erreicht; der Lauf wird trotzdem abgeschlossen. @@ -127,6 +132,11 @@ Die Azure DevOps Liveveröffentlichung hat eine azdo-runid.<buildId>.json-Datei für ein anderes Azure DevOps-Projekt gefunden. {Locked="azdo-runid.<buildId>.json"} + + Azure DevOps live publishing failed to update the test run id handoff. + Azure DevOps live publishing failed to update the test run id handoff. + + The Azure DevOps test run was not marked as completed and may not appear in the build's Tests tab. The Azure DevOps test run was not marked as completed and may not appear in the build's Tests tab. diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.es.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.es.xlf index d374f70d0b..5ce6a566d5 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.es.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.es.xlf @@ -62,6 +62,11 @@ La publicación en directo de Azure DevOps no pudo eliminar el archivo de coordinación + + Azure DevOps live publishing failed to write coordination file + Azure DevOps live publishing failed to write coordination file + + Azure DevOps live publishing timed out after {0} waiting for {1} participant file(s); finalizing the run anyway. La publicación en directo de Azure DevOps agotó el tiempo de espera después de {0} esperar {1} archivo(s) de participante; finalizando la ejecución de todos modos. @@ -127,6 +132,11 @@ La publicación en directo de Azure DevOps encontró un archivo azdo-runid.<buildId>.json para otro proyecto de Azure DevOps. {Locked="azdo-runid.<buildId>.json"} + + Azure DevOps live publishing failed to update the test run id handoff. + Azure DevOps live publishing failed to update the test run id handoff. + + The Azure DevOps test run was not marked as completed and may not appear in the build's Tests tab. The Azure DevOps test run was not marked as completed and may not appear in the build's Tests tab. diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.fr.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.fr.xlf index ddb30537ed..6ccf96f116 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.fr.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.fr.xlf @@ -62,6 +62,11 @@ Nous n’avons pas pu effectuer la publication en direct d’Azure DevOps pour supprimer le fichier de coordination + + Azure DevOps live publishing failed to write coordination file + Azure DevOps live publishing failed to write coordination file + + Azure DevOps live publishing timed out after {0} waiting for {1} participant file(s); finalizing the run anyway. La publication en direct d’Azure DevOps a expiré après {0} en attendant {1} fichier(s) de participant(s), finalisant l’exécution malgré tout. @@ -127,6 +132,11 @@ La publication en direct d’Azure DevOps a trouvé un fichier azdo-runid.<buildId>.json pour un autre projet Azure DevOps. {Locked="azdo-runid.<buildId>.json"} + + Azure DevOps live publishing failed to update the test run id handoff. + Azure DevOps live publishing failed to update the test run id handoff. + + The Azure DevOps test run was not marked as completed and may not appear in the build's Tests tab. The Azure DevOps test run was not marked as completed and may not appear in the build's Tests tab. diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.it.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.it.xlf index a63a9e82fd..8a6fc9f20c 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.it.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.it.xlf @@ -62,6 +62,11 @@ La pubblicazione live di Azure DevOps non è riuscita a eliminare il file di coordinamento + + Azure DevOps live publishing failed to write coordination file + Azure DevOps live publishing failed to write coordination file + + Azure DevOps live publishing timed out after {0} waiting for {1} participant file(s); finalizing the run anyway. La pubblicazione live di Azure DevOps è andata in timeout dopo {0} di attesa di {1} file partecipanti; l'esecuzione verrà comunque finalizzata. @@ -127,6 +132,11 @@ La pubblicazione live di Azure DevOps ha trovato un file azdo-runid.<buildId>.json per un progetto Azure DevOps diverso. {Locked="azdo-runid.<buildId>.json"} + + Azure DevOps live publishing failed to update the test run id handoff. + Azure DevOps live publishing failed to update the test run id handoff. + + The Azure DevOps test run was not marked as completed and may not appear in the build's Tests tab. The Azure DevOps test run was not marked as completed and may not appear in the build's Tests tab. diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ja.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ja.xlf index 76736f93c8..5a129fc203 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ja.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ja.xlf @@ -62,6 +62,11 @@ Azure DevOps ライブ公開で調整ファイルを削除できませんでした + + Azure DevOps live publishing failed to write coordination file + Azure DevOps live publishing failed to write coordination file + + Azure DevOps live publishing timed out after {0} waiting for {1} participant file(s); finalizing the run anyway. Azure DevOps ライブ公開は、{0} が {1} 個の参加者ファイルの待機後にタイムアウトしました。実行を続行して最終処理します。 @@ -127,6 +132,11 @@ Azure DevOps ライブ公開で、別の Azure DevOps プロジェクトの azdo-runid.<buildId>.json ファイルが見つかりました。 {Locked="azdo-runid.<buildId>.json"} + + Azure DevOps live publishing failed to update the test run id handoff. + Azure DevOps live publishing failed to update the test run id handoff. + + The Azure DevOps test run was not marked as completed and may not appear in the build's Tests tab. The Azure DevOps test run was not marked as completed and may not appear in the build's Tests tab. diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ko.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ko.xlf index 83700d5158..747d016c0d 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ko.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ko.xlf @@ -62,6 +62,11 @@ Azure DevOps 라이브 게시에서 조정 파일을 삭제하지 못했습니다. + + Azure DevOps live publishing failed to write coordination file + Azure DevOps live publishing failed to write coordination file + + Azure DevOps live publishing timed out after {0} waiting for {1} participant file(s); finalizing the run anyway. Azure DevOps 라이브 게시가 {0} 동안 {1}개 참가자 파일을 기다리다 시간이 초과되었습니다. 그래도 실행을 마무리하겠습니다. @@ -127,6 +132,11 @@ Azure DevOps 라이브 게시에서 다른 Azure DevOps 프로젝트에 대한 azdo-runid.<buildId>.json 파일을 찾았습니다. {Locked="azdo-runid.<buildId>.json"} + + Azure DevOps live publishing failed to update the test run id handoff. + Azure DevOps live publishing failed to update the test run id handoff. + + The Azure DevOps test run was not marked as completed and may not appear in the build's Tests tab. The Azure DevOps test run was not marked as completed and may not appear in the build's Tests tab. diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.pl.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.pl.xlf index 5238781503..7df36e8770 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.pl.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.pl.xlf @@ -62,6 +62,11 @@ Publikowanie na żywo w usłudze Azure DevOps nie może usunąć pliku koordynacji + + Azure DevOps live publishing failed to write coordination file + Azure DevOps live publishing failed to write coordination file + + Azure DevOps live publishing timed out after {0} waiting for {1} participant file(s); finalizing the run anyway. Publikowanie na żywo w usłudze Azure DevOps przekroczyło limit czasu po {0} oczekiwaniu na pliki uczestników w liczbie {1}; mimo to zakończono przebieg. @@ -127,6 +132,11 @@ Publikowanie na żywo w usłudze Azure DevOps znalazło plik azdo-runid.<buildId>.json dla innego projektu usługi Azure DevOps. {Locked="azdo-runid.<buildId>.json"} + + Azure DevOps live publishing failed to update the test run id handoff. + Azure DevOps live publishing failed to update the test run id handoff. + + The Azure DevOps test run was not marked as completed and may not appear in the build's Tests tab. The Azure DevOps test run was not marked as completed and may not appear in the build's Tests tab. diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.pt-BR.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.pt-BR.xlf index e62e0a9d3a..e1fc2a3b2b 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.pt-BR.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.pt-BR.xlf @@ -62,6 +62,11 @@ A publicação ao vivo do Azure DevOps falhou ao excluir o arquivo de coordenação + + Azure DevOps live publishing failed to write coordination file + Azure DevOps live publishing failed to write coordination file + + Azure DevOps live publishing timed out after {0} waiting for {1} participant file(s); finalizing the run anyway. A publicação ao vivo do Azure DevOps atingiu o tempo limite depois de {0} aguardar {1} arquivo(s) dos participantes, finalizando a execução mesmo assim. @@ -127,6 +132,11 @@ A publicação ao vivo do Azure DevOps encontrou um arquivo azdo-runid.<buildId>.json para um projeto do Azure DevOps diferente. {Locked="azdo-runid.<buildId>.json"} + + Azure DevOps live publishing failed to update the test run id handoff. + Azure DevOps live publishing failed to update the test run id handoff. + + The Azure DevOps test run was not marked as completed and may not appear in the build's Tests tab. The Azure DevOps test run was not marked as completed and may not appear in the build's Tests tab. diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ru.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ru.xlf index d1511ffad8..99ea6c415d 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ru.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ru.xlf @@ -62,6 +62,11 @@ Azure DevOps: не удалось удалить файл координирования при публикации в реальном времени + + Azure DevOps live publishing failed to write coordination file + Azure DevOps live publishing failed to write coordination file + + Azure DevOps live publishing timed out after {0} waiting for {1} participant file(s); finalizing the run anyway. Azure DevOps: время ожидания публикации в реальном времени истекло после {0} ожидания файлов участника ({1}) ; запуск будет завершен в любом случае. @@ -127,6 +132,11 @@ Azure DevOps: при публикации в реальном времени обнаружен файл azdo-runid.<buildId>.json для другого проекта Azure DevOps. {Locked="azdo-runid.<buildId>.json"} + + Azure DevOps live publishing failed to update the test run id handoff. + Azure DevOps live publishing failed to update the test run id handoff. + + The Azure DevOps test run was not marked as completed and may not appear in the build's Tests tab. The Azure DevOps test run was not marked as completed and may not appear in the build's Tests tab. diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.tr.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.tr.xlf index ac5bb54411..ef3fbfe9eb 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.tr.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.tr.xlf @@ -62,6 +62,11 @@ Azure DevOps canlı yayımlama koordinasyon dosyasını silemedi + + Azure DevOps live publishing failed to write coordination file + Azure DevOps live publishing failed to write coordination file + + Azure DevOps live publishing timed out after {0} waiting for {1} participant file(s); finalizing the run anyway. Azure DevOps canlı yayımlama, {0} boyunca {1} katılımcı dosyasını bekledikten sonra zaman aşımına uğradı; çalıştırma yine de sonlandırılıyor. @@ -127,6 +132,11 @@ Azure DevOps canlı yayımlama, farklı bir Azure DevOps projesi için azdo-runid.<buildId>.json dosyası buldu. {Locked="azdo-runid.<buildId>.json"} + + Azure DevOps live publishing failed to update the test run id handoff. + Azure DevOps live publishing failed to update the test run id handoff. + + The Azure DevOps test run was not marked as completed and may not appear in the build's Tests tab. The Azure DevOps test run was not marked as completed and may not appear in the build's Tests tab. diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.zh-Hans.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.zh-Hans.xlf index fd5f5b4278..083480033d 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.zh-Hans.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.zh-Hans.xlf @@ -62,6 +62,11 @@ Azure DevOps 实时发布未能删除协调文件 + + Azure DevOps live publishing failed to write coordination file + Azure DevOps live publishing failed to write coordination file + + Azure DevOps live publishing timed out after {0} waiting for {1} participant file(s); finalizing the run anyway. Azure DevOps 实时发布在等待 {1} 个参与者文件 {0} 后超时;仍将完成运行。 @@ -127,6 +132,11 @@ Azure DevOps 实时发布发现了属于其他 Azure DevOps 项目的 azdo-runid.<buildId>.json 文件。 {Locked="azdo-runid.<buildId>.json"} + + Azure DevOps live publishing failed to update the test run id handoff. + Azure DevOps live publishing failed to update the test run id handoff. + + The Azure DevOps test run was not marked as completed and may not appear in the build's Tests tab. The Azure DevOps test run was not marked as completed and may not appear in the build's Tests tab. diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.zh-Hant.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.zh-Hant.xlf index 206984d3f5..bf2f92b8cf 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.zh-Hant.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.zh-Hant.xlf @@ -62,6 +62,11 @@ Azure DevOps 即時發佈無法刪除協調檔案 + + Azure DevOps live publishing failed to write coordination file + Azure DevOps live publishing failed to write coordination file + + Azure DevOps live publishing timed out after {0} waiting for {1} participant file(s); finalizing the run anyway. Azure DevOps 即時發佈在 {0} 等待 {1} 個參與者檔案後逾時; 無論如何都要完成執行。 @@ -127,6 +132,11 @@ Azure DevOps 即時發佈找到不同 Azure DevOps 專案的 azdo-runid.<buildId>.json 檔案。 {Locked="azdo-runid.<buildId>.json"} + + Azure DevOps live publishing failed to update the test run id handoff. + Azure DevOps live publishing failed to update the test run id handoff. + + The Azure DevOps test run was not marked as completed and may not appear in the build's Tests tab. The Azure DevOps test run was not marked as completed and may not appear in the build's Tests tab. diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostOchestratorHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostOchestratorHost.cs index 0449952c83..320c6f6038 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostOchestratorHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostOchestratorHost.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using System.Runtime.ExceptionServices; + using Microsoft.Testing.Platform.Extensions.TestHostOrchestrator; using Microsoft.Testing.Platform.Helpers; using Microsoft.Testing.Platform.IPC; @@ -60,6 +62,7 @@ await pushOnlyProtocol.StartServerControlChannelAsync(_ => } int exitCode; + bool orchestrationCanceled = false; await logger.LogInformationAsync($"Running test orchestrator '{testHostOrchestrator.Uid}'").ConfigureAwait(false); try { @@ -69,19 +72,90 @@ await pushOnlyProtocol.StartServerControlChannelAsync(_ => } exitCode = await testHostOrchestrator.OrchestrateTestHostExecutionAsync(applicationCancellationToken.CancellationToken).ConfigureAwait(false); - - foreach (ITestHostOrchestratorApplicationLifetime orchestratorLifetime in _serviceProvider.GetServicesInternal()) - { - await orchestratorLifetime.AfterRunAsync(exitCode, applicationCancellationToken.CancellationToken).ConfigureAwait(false); - await DisposeHelper.DisposeAsync(orchestratorLifetime).ConfigureAwait(false); - } } catch (OperationCanceledException) when (applicationCancellationToken.CancellationToken.IsCancellationRequested) { // We do nothing we're canceling + orchestrationCanceled = true; exitCode = (int)ExitCode.TestSessionAborted; } + catch + { + // The orchestrator faulted (for example retry rejecting server mode or hot reload, which throws + // before running anything). A lifetime that acquired a resource in BeforeRunAsync still has to + // release it, or an Azure DevOps test run created there stays "InProgress" and never appears in + // the build's Tests tab. Failures during that release are swallowed so they cannot replace the + // exception that actually caused the run to fail. + await RunAfterRunAsync((int)ExitCode.GenericFailure, swallowFailures: true).ConfigureAwait(false); + throw; + } + + // AfterRunAsync also runs when the orchestration was canceled, because cancellation is exactly when + // releasing what BeforeRunAsync acquired matters most. Cleanup failures only surface after normally + // completed orchestration; cancellation and fault paths already have their outcome, so cleanup is + // best-effort. + await RunAfterRunAsync(exitCode, swallowFailures: orchestrationCanceled).ConfigureAwait(false); return exitCode; + + async Task RunAfterRunAsync(int reportedExitCode, bool swallowFailures) + { + Exception? firstFailure = null; + + foreach (ITestHostOrchestratorApplicationLifetime orchestratorLifetime in _serviceProvider.GetServicesInternal()) + { + // Every lifetime gets its AfterRunAsync and its disposal, whatever the previous one did: + // one extension failing to release its resource must not strand everyone else's. + try + { + await orchestratorLifetime.AfterRunAsync(reportedExitCode, applicationCancellationToken.CancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (applicationCancellationToken.CancellationToken.IsCancellationRequested) + { + await TryLogAsync(() => logger.LogDebugAsync( + $"Orchestrator lifetime '{orchestratorLifetime.Uid}' did not complete AfterRunAsync because the run was canceled.")).ConfigureAwait(false); + } + catch (Exception ex) + { + firstFailure ??= ex; + + // Logged rather than discarded: a lifetime that consistently fails to release its + // resource is otherwise undiagnosable, even with --diagnostic. + await TryLogAsync(() => logger.LogWarningAsync( + $"Orchestrator lifetime '{orchestratorLifetime.Uid}' failed in AfterRunAsync: {ex}")).ConfigureAwait(false); + } + + try + { + await DisposeHelper.DisposeAsync(orchestratorLifetime).ConfigureAwait(false); + } + catch (Exception ex) + { + firstFailure ??= ex; + await TryLogAsync(() => logger.LogWarningAsync( + $"Orchestrator lifetime '{orchestratorLifetime.Uid}' failed to dispose: {ex}")).ConfigureAwait(false); + } + } + + // On cancellation and fault paths the caller already has an outcome to report; only surface + // cleanup failures after normal completion. + if (firstFailure is not null && !swallowFailures) + { + ExceptionDispatchInfo.Capture(firstFailure).Throw(); + } + } + + async Task TryLogAsync(Func logAsync) + { + try + { + await logAsync().ConfigureAwait(false); + } + catch (Exception) + { + // Diagnostic logging in this cleanup path is best-effort; letting it escape could skip + // disposal or later lifetimes and strand the resources this loop exists to release. + } + } } } diff --git a/src/Platform/Microsoft.Testing.Platform/TestHostOrchestrator/ITestHostOrchestratorApplicationLifetime.cs b/src/Platform/Microsoft.Testing.Platform/TestHostOrchestrator/ITestHostOrchestratorApplicationLifetime.cs index 0e98bb36e2..8e1118cdd6 100644 --- a/src/Platform/Microsoft.Testing.Platform/TestHostOrchestrator/ITestHostOrchestratorApplicationLifetime.cs +++ b/src/Platform/Microsoft.Testing.Platform/TestHostOrchestrator/ITestHostOrchestratorApplicationLifetime.cs @@ -19,6 +19,15 @@ public interface ITestHostOrchestratorApplicationLifetime : ITestHostOrchestrato /// /// Executes after the orchestrator runs. /// + /// + /// Also invoked when the orchestration was canceled or failed, so that whatever + /// acquired can still be released. Implementations + /// must therefore tolerate being called when their + /// never ran or did not complete, must be safe to call once per run regardless of outcome, and should + /// not assume is still usable — it may already be canceled. + /// Implementations should not throw from this method. When the orchestration was canceled or failed, + /// exceptions thrown from this method are logged and suppressed so they cannot mask the original outcome. + /// /// The exit code of the orchestrator. /// The cancellation token. /// A task representing the asynchronous operation. diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/AzureDevOpsLivePublishingTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/AzureDevOpsLivePublishingTests.cs index 6b05f86235..310a061fca 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/AzureDevOpsLivePublishingTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/AzureDevOpsLivePublishingTests.cs @@ -4,6 +4,7 @@ using System.Diagnostics; using System.Net; using System.Net.Http; +using System.Security; using System.Text; using System.Text.Json; @@ -1070,7 +1071,11 @@ public async Task RunIdCoordinator_FinalizeRunAsync_TimesOutAndLogsWarning() File.WriteAllText(ownerFilePath, JsonSerializer.Serialize(new AzureDevOpsLeaseFile(aliveProcessId, 123, clock.UtcNow.AddHours(1)))); File.WriteAllText(runIdFilePath, JsonSerializer.Serialize(new AzureDevOpsRunIdFile(5, 123, "https://dev.azure.com/org/", "project", clock.UtcNow.AddHours(1)))); - File.WriteAllText(Path.Combine(directory.Path, $"azdo-runid.123.participant.{aliveProcessId}.json"), JsonSerializer.Serialize(new AzureDevOpsLeaseFile(aliveProcessId, 123, clock.UtcNow.AddHours(1)))); + + // A participant that cannot be vouched for: its lease is unreadable and the process in its file + // name is not running. Those get only the short grace period — unlike a peer whose process is + // provably alive, which the owner keeps waiting for because it is still publishing. + File.WriteAllText(Path.Combine(directory.Path, $"azdo-runid.123.participant.{int.MaxValue - 1}.json"), "not-json"); int finalizeCalls = 0; await coordinator.FinalizeRunAsync(new AzureDevOpsCoordinatedRun(5, true, 123, directory.Path, runIdFilePath, ownerFilePath, participantFilePath), _ => @@ -1317,6 +1322,623 @@ private static async Task StartPublisherAsync(AzureDevOpsTestResultsPublisher pu await publisher.OnTestSessionStartingAsync(new Microsoft.Testing.Platform.Services.TestSessionContext(CancellationToken.None)); } + #region Run lifetime across orchestrated processes (https://github.com/microsoft/testfx/issues/10360) + + [TestMethod] + public async Task OrchestratorLifetime_BeforeRun_CreatesRunOnceAndPublishesItToOrchestratedProcesses() + { + using TestDirectory directory = CreateTestDirectory(); + Mock environment = CreateEnvironmentMockWithSettableRunId(); + AzureDevOpsTestRunOrchestratorLifetime lifetime = CreateOrchestratorLifetime(directory.Path, out FakeAzureDevOpsTestResultsClient client, out _, environment); + client.CreateTestRunAsyncFunc = (_, _) => Task.FromResult(4242); + + Assert.IsTrue(await lifetime.IsEnabledAsync()); + await lifetime.BeforeRunAsync(CancellationToken.None); + + Assert.HasCount(1, client.CreateTestRunCalls); + Assert.AreEqual(4242, lifetime.RunId); + Assert.AreEqual(4242, AzureDevOpsConstants.TryGetInheritedTestRunId(environment.Object, buildId: 123)); + } + + [TestMethod] + public async Task OrchestratorLifetime_AfterRun_CompletesTheRunItCreated() + { + using TestDirectory directory = CreateTestDirectory(); + AzureDevOpsTestRunOrchestratorLifetime lifetime = CreateOrchestratorLifetime(directory.Path, out FakeAzureDevOpsTestResultsClient client, out _, CreateEnvironmentMockWithSettableRunId()); + client.CreateTestRunAsyncFunc = (_, _) => Task.FromResult(4243); + + await lifetime.BeforeRunAsync(CancellationToken.None); + await lifetime.AfterRunAsync(2 /* ExitCode.AtLeastOneTestFailed */, CancellationToken.None); + + Assert.HasCount(1, client.UpdateTestRunStateCalls); + Assert.AreEqual(4243, client.UpdateTestRunStateCalls[0].RunId); + Assert.AreEqual(AzureDevOpsLivePublishingConstants.CompletedTestRunState, client.UpdateTestRunStateCalls[0].State); + } + + [TestMethod] + public async Task OrchestratorLifetime_AfterRun_NonTestResultExitCodeAbortsTheRun() + { + using TestDirectory directory = CreateTestDirectory(); + AzureDevOpsTestRunOrchestratorLifetime lifetime = CreateOrchestratorLifetime(directory.Path, out FakeAzureDevOpsTestResultsClient client, out _, CreateEnvironmentMockWithSettableRunId()); + client.CreateTestRunAsyncFunc = (_, _) => Task.FromResult(4244); + + await lifetime.BeforeRunAsync(CancellationToken.None); + await lifetime.AfterRunAsync(3 /* ExitCode.TestSessionAborted */, CancellationToken.None); + + Assert.HasCount(1, client.UpdateTestRunStateCalls); + Assert.AreEqual(4244, client.UpdateTestRunStateCalls[0].RunId); + Assert.AreEqual(AzureDevOpsLivePublishingConstants.AbortedTestRunState, client.UpdateTestRunStateCalls[0].State); + } + + [TestMethod] + public async Task OrchestratorLifetime_AfterRun_StopsHandingOutTheRunIdSoLaterProcessesDoNotPublishIntoAClosedRun() + { + using TestDirectory directory = CreateTestDirectory(); + Mock environment = CreateEnvironmentMockWithSettableRunId(); + AzureDevOpsTestRunOrchestratorLifetime lifetime = CreateOrchestratorLifetime(directory.Path, out FakeAzureDevOpsTestResultsClient client, out _, environment); + client.CreateTestRunAsyncFunc = (_, _) => Task.FromResult(4245); + + await lifetime.BeforeRunAsync(CancellationToken.None); + await lifetime.AfterRunAsync(0 /* ExitCode.Success */, CancellationToken.None); + + Assert.IsNull(AzureDevOpsConstants.TryGetInheritedTestRunId(environment.Object, buildId: 123)); + } + + [TestMethod] + public async Task OrchestratorLifetime_BeforeRun_RunIdAlreadyInEnvironment_LeavesTheAncestorRunAlone() + { + using TestDirectory directory = CreateTestDirectory(); + AzureDevOpsTestRunOrchestratorLifetime lifetime = CreateOrchestratorLifetime(directory.Path, out FakeAzureDevOpsTestResultsClient client, out _, CreateEnvironmentMockWithSettableRunId("123:777")); + + await lifetime.BeforeRunAsync(CancellationToken.None); + await lifetime.AfterRunAsync(0 /* ExitCode.Success */, CancellationToken.None); + + Assert.IsEmpty(client.CreateTestRunCalls); + Assert.IsEmpty(client.UpdateTestRunStateCalls); + } + + [TestMethod] + public async Task OrchestratorLifetime_BeforeRun_CreateRunFails_DoesNotPublishARunIdAndDoesNotThrow() + { + using TestDirectory directory = CreateTestDirectory(); + Mock environment = CreateEnvironmentMockWithSettableRunId(); + CollectingOutputDevice outputDevice = new(); + AzureDevOpsTestRunOrchestratorLifetime lifetime = CreateOrchestratorLifetime(directory.Path, out FakeAzureDevOpsTestResultsClient client, out CollectingLogger logger, environment, outputDevice); + client.CreateTestRunAsyncFunc = (_, _) => throw new HttpRequestException("boom"); + + await lifetime.BeforeRunAsync(CancellationToken.None); + await lifetime.AfterRunAsync(0 /* ExitCode.Success */, CancellationToken.None); + + Assert.IsNull(lifetime.RunId); + Assert.IsNull(AzureDevOpsConstants.TryGetInheritedTestRunId(environment.Object, buildId: 123)); + Assert.IsEmpty(client.UpdateTestRunStateCalls); + Assert.Contains(AzureDevOpsResources.AzureDevOpsLivePublishingCreateRunFailed, string.Join(Environment.NewLine, outputDevice.Warnings)); + Assert.Contains(AzureDevOpsResources.AzureDevOpsLivePublishingCreateRunFailed, string.Join(Environment.NewLine, logger.Logs)); + } + + [TestMethod] + public async Task Publisher_RunIdInEnvironment_JoinsTheRunInsteadOfCreatingItsOwn() + { + using TestDirectory directory = CreateTestDirectory(); + Mock environment = CreateEnvironmentMockWithSettableRunId("123:909"); + AzureDevOpsTestResultsPublisher publisher = CreatePublisher(directory.Path, options: new(10, TimeSpan.FromMinutes(1), 4, TimeSpan.FromMilliseconds(1)), out FakeAzureDevOpsTestResultsClient client, out _, out _, environment: environment); + + await StartPublisherAsync(publisher); + + Assert.AreEqual(909, publisher.RunId); + Assert.IsEmpty(client.CreateTestRunCalls); + } + + [TestMethod] + public async Task Publisher_RunIdInEnvironment_DoesNotCompleteTheRunSoLaterAttemptsCanStillPublish() + { + using TestDirectory directory = CreateTestDirectory(); + Mock environment = CreateEnvironmentMockWithSettableRunId("123:910"); + AzureDevOpsTestResultsPublisher publisher = CreatePublisher(directory.Path, options: new(10, TimeSpan.FromMinutes(1), 4, TimeSpan.FromMilliseconds(1)), out FakeAzureDevOpsTestResultsClient client, out _, out _, environment: environment); + + await StartPublisherAsync(publisher); + await publisher.OnTestSessionFinishingAsync(new Microsoft.Testing.Platform.Services.TestSessionContext(CancellationToken.None)); + + Assert.IsEmpty(client.UpdateTestRunStateCalls); + } + + [TestMethod] + public async Task Publisher_RunIdInEnvironment_StillPublishesResultsIntoTheInheritedRun() + { + using TestDirectory directory = CreateTestDirectory(); + Mock environment = CreateEnvironmentMockWithSettableRunId("123:911"); + AzureDevOpsTestResultsPublisher publisher = CreatePublisher(directory.Path, options: new(1, TimeSpan.FromMinutes(1), 4, TimeSpan.FromMilliseconds(1)), out FakeAzureDevOpsTestResultsClient client, out _, out _, environment: environment); + List publishedToRunIds = []; + client.PublishTestResultsAsyncFunc = (_, runId, results, _) => + { + publishedToRunIds.Add(runId); + return Task.FromResult?>([.. Enumerable.Range(1, results.Count)]); + }; + + await StartPublisherAsync(publisher); + await publisher.ConsumeAsync( + Mock.Of(), + CreateMessage(CreateNode("Test1", new PassedTestNodeStateProperty(), DateTimeOffset.UtcNow)), + CancellationToken.None); + + Assert.HasCount(1, publishedToRunIds); + Assert.AreEqual(911, publishedToRunIds[0]); + } + + [TestMethod] + public async Task Publisher_RunIdInEnvironment_WritesNoCoordinationFilesBecauseTheAncestorOwnsTheRun() + { + using TestDirectory directory = CreateTestDirectory(); + Mock environment = CreateEnvironmentMockWithSettableRunId("123:912"); + AzureDevOpsTestResultsPublisher publisher = CreatePublisher(directory.Path, options: new(10, TimeSpan.FromMinutes(1), 4, TimeSpan.FromMilliseconds(1)), out _, out _, out _, environment: environment); + + await StartPublisherAsync(publisher); + await publisher.OnTestSessionFinishingAsync(new Microsoft.Testing.Platform.Services.TestSessionContext(CancellationToken.None)); + + Assert.IsEmpty(Directory.GetFiles(directory.Path, "azdo-runid.*", SearchOption.AllDirectories)); + } + + [TestMethod] + [DataRow("")] + [DataRow("not-a-number")] + [DataRow("0")] + [DataRow("-1")] + [DataRow("123:0")] + [DataRow("123:-1")] + [DataRow("123:not-a-number")] + [DataRow(":42")] + [DataRow("999:42")] + public async Task Publisher_UnusableRunIdInEnvironment_FallsBackToCreatingItsOwnRun(string environmentValue) + { + // "999:42" is the important row: a handoff left behind by a different build must never redirect + // this build's results into that build's (probably already completed) run. + using TestDirectory directory = CreateTestDirectory(); + Mock environment = CreateEnvironmentMockWithSettableRunId(environmentValue); + AzureDevOpsTestResultsPublisher publisher = CreatePublisher(directory.Path, options: new(10, TimeSpan.FromMinutes(1), 4, TimeSpan.FromMilliseconds(1)), out FakeAzureDevOpsTestResultsClient client, out _, out _, environment: environment); + client.CreateTestRunAsyncFunc = (_, _) => Task.FromResult(913); + + await StartPublisherAsync(publisher); + + Assert.AreEqual(913, publisher.RunId); + Assert.HasCount(1, client.CreateTestRunCalls); + } + + [TestMethod] + public async Task OrchestratorLifetime_AfterRun_CanceledToken_StillClosesTheRunAsAborted() + { + using TestDirectory directory = CreateTestDirectory(); + AzureDevOpsTestRunOrchestratorLifetime lifetime = CreateOrchestratorLifetime(directory.Path, out FakeAzureDevOpsTestResultsClient client, out _); + client.CreateTestRunAsyncFunc = (_, _) => Task.FromResult(4246); + + await lifetime.BeforeRunAsync(CancellationToken.None); + + using CancellationTokenSource canceled = new(); +#pragma warning disable VSTHRD103 // CancelAsync is only available on .NET 8+; this project also targets .NET Framework. + canceled.Cancel(); +#pragma warning restore VSTHRD103 + await lifetime.AfterRunAsync(3 /* ExitCode.TestSessionAborted */, canceled.Token); + + // A run left "InProgress" never appears in the build's Tests tab, so cancellation must still close it. + Assert.HasCount(1, client.UpdateTestRunStateCalls); + Assert.AreEqual(4246, client.UpdateTestRunStateCalls[0].RunId); + Assert.AreEqual(AzureDevOpsLivePublishingConstants.AbortedTestRunState, client.UpdateTestRunStateCalls[0].State); + } + + [TestMethod] + public async Task OrchestratorLifetime_AfterRun_CalledTwice_FinalizesTheRunOnlyOnce() + { + using TestDirectory directory = CreateTestDirectory(); + AzureDevOpsTestRunOrchestratorLifetime lifetime = CreateOrchestratorLifetime(directory.Path, out FakeAzureDevOpsTestResultsClient client, out _); + client.CreateTestRunAsyncFunc = (_, _) => Task.FromResult(4247); + + await lifetime.BeforeRunAsync(CancellationToken.None); + await lifetime.AfterRunAsync(0 /* ExitCode.Success */, CancellationToken.None); + await lifetime.AfterRunAsync(0 /* ExitCode.Success */, CancellationToken.None); + + Assert.HasCount(1, client.UpdateTestRunStateCalls); + Assert.AreEqual(4247, client.UpdateTestRunStateCalls[0].RunId); + Assert.AreEqual(AzureDevOpsLivePublishingConstants.CompletedTestRunState, client.UpdateTestRunStateCalls[0].State); + } + + [TestMethod] + public async Task OrchestratorLifetime_AfterRun_WithoutBeforeRun_IsANoOp() + { + // The host calls AfterRunAsync on every lifetime once BeforeRunAsync has been attempted, including + // ones whose BeforeRunAsync never ran because an earlier lifetime faulted. + using TestDirectory directory = CreateTestDirectory(); + AzureDevOpsTestRunOrchestratorLifetime lifetime = CreateOrchestratorLifetime(directory.Path, out FakeAzureDevOpsTestResultsClient client, out _); + + await lifetime.AfterRunAsync(0 /* ExitCode.Success */, CancellationToken.None); + + Assert.IsEmpty(client.UpdateTestRunStateCalls); + } + + [TestMethod] + public async Task OrchestratorLifetime_HandoffFailsAfterRunCreated_StillClosesTheRun() + { + // Anything failing between run creation and the handoff must not discard the run: this process is + // the only one that can close it, so losing that state would strand it in "InProgress". + using TestDirectory directory = CreateTestDirectory(); + Mock environment = CreateEnvironmentMockWithSettableRunId(); + environment.Setup(x => x.SetEnvironmentVariable(AzureDevOpsConstants.TestRunIdEnvironmentVariableName, It.IsAny())) + .Throws(new SecurityException("environment is locked down")); + AzureDevOpsTestRunOrchestratorLifetime lifetime = CreateOrchestratorLifetime(directory.Path, out FakeAzureDevOpsTestResultsClient client, out CollectingLogger logger, environment); + client.CreateTestRunAsyncFunc = (_, _) => Task.FromResult(4248); + + await lifetime.BeforeRunAsync(CancellationToken.None); + await lifetime.AfterRunAsync(0 /* ExitCode.Success */, CancellationToken.None); + + Assert.HasCount(1, client.UpdateTestRunStateCalls); + Assert.AreEqual(4248, client.UpdateTestRunStateCalls[0].RunId); + Assert.AreEqual(AzureDevOpsLivePublishingConstants.CompletedTestRunState, client.UpdateTestRunStateCalls[0].State); + Assert.Contains(AzureDevOpsResources.AzureDevOpsLivePublishingRunIdHandoffFailed, string.Join(Environment.NewLine, logger.Logs)); + } + + [TestMethod] + public async Task OrchestratorLifetime_PeerOrchestratorsSharingAResultsDirectory_PublishIntoASingleRun() + { + // A multi-project 'dotnet test' runs one orchestrator process per test project, all sharing the + // user's results directory. They must consolidate into one run for the build, exactly as + // non-orchestrated test hosts already do. The peers are given distinct process ids so that each + // registers its own participant lease — with a shared id they would silently overwrite one + // another's and this test would pass even if joiners never registered at all. + using TestDirectory directory = CreateTestDirectory(); + AzureDevOpsTestRunOrchestratorLifetime first = CreateOrchestratorLifetime(directory.Path, out FakeAzureDevOpsTestResultsClient firstClient, out _, CreateEnvironmentMockWithSettableRunId(processId: GetAliveProcessId())); + AzureDevOpsTestRunOrchestratorLifetime second = CreateOrchestratorLifetime(directory.Path, out FakeAzureDevOpsTestResultsClient secondClient, out _, CreateEnvironmentMockWithSettableRunId(processId: GetAliveProcessId() + 1)); + firstClient.CreateTestRunAsyncFunc = (_, _) => Task.FromResult(4249); + secondClient.CreateTestRunAsyncFunc = (_, _) => Task.FromResult(-1); + + await first.BeforeRunAsync(CancellationToken.None); + await second.BeforeRunAsync(CancellationToken.None); + + // One run for the build, and the peer joined it rather than creating its own. + Assert.HasCount(1, firstClient.CreateTestRunCalls); + Assert.IsEmpty(secondClient.CreateTestRunCalls); + Assert.AreEqual(4249, first.RunId); + Assert.AreEqual(4249, second.RunId); + + // Both peers are registered participants, so the owner knows it must wait for the peer. + Assert.HasCount(2, Directory.GetFiles(directory.Path, "azdo-runid.*.participant.*.json", SearchOption.TopDirectoryOnly)); + + // The joiner must not close a run it does not own. + await second.AfterRunAsync(0 /* ExitCode.Success */, CancellationToken.None); + Assert.IsEmpty(secondClient.UpdateTestRunStateCalls); + Assert.HasCount(1, Directory.GetFiles(directory.Path, "azdo-runid.*.participant.*.json", SearchOption.TopDirectoryOnly)); + + // Only once every participant is gone does the owner complete the run, exactly once. + await first.AfterRunAsync(0 /* ExitCode.Success */, CancellationToken.None); + Assert.HasCount(1, firstClient.UpdateTestRunStateCalls); + Assert.AreEqual(AzureDevOpsLivePublishingConstants.CompletedTestRunState, firstClient.UpdateTestRunStateCalls[0].State); + } + + [TestMethod] + public async Task RunIdCoordinator_OwnerLeaseExpiredButOwnerProcessAlive_PeerJoinsInsteadOfCreatingASecondRun() + { + // An owner that never renews its lease (a run orchestrator holds one for the whole orchestration) + // still owns the run. Taking over from it once the wall-clock expiry passes would create a second + // Azure DevOps run for the same build and orphan the first. + using TestDirectory directory = CreateTestDirectory(); + FakeClock clock = new() { UtcNow = new DateTimeOffset(2025, 1, 1, 12, 0, 0, TimeSpan.Zero) }; + AzureDevOpsTestResultsPublisherOptions options = new(10, TimeSpan.FromMinutes(1), 2, TimeSpan.FromMilliseconds(1), TimeSpan.FromSeconds(30), TimeSpan.FromHours(4)); + AzureDevOpsPublishConfiguration configuration = new("https://dev.azure.com/org/", "project", "token", 123, "run", "storage", directory.Path); + + AzureDevOpsRunIdCoordinator owner = new(new SystemFileSystem(), new FakeTask(), clock, CreateEnvironmentMock(processId: GetAliveProcessId()).Object, new CollectingLogger(), options); + AzureDevOpsCoordinatedRun ownedRun = await owner.AcquireRunAsync(configuration, _ => Task.FromResult(900), CancellationToken.None); + Assert.IsTrue(ownedRun.IsOwner); + + // Move past the lease expiry without the owner ever renewing, then let a peer try to acquire. + clock.UtcNow += TimeSpan.FromHours(5); + AzureDevOpsRunIdCoordinator peer = new(new SystemFileSystem(), new FakeTask(), clock, CreateEnvironmentMock(processId: GetAliveProcessId() + 1).Object, new CollectingLogger(), options); + AzureDevOpsCoordinatedRun peerRun = await peer.AcquireRunAsync(configuration, _ => Task.FromResult(-1), CancellationToken.None); + + Assert.IsFalse(peerRun.IsOwner); + Assert.AreEqual(900, peerRun.RunId); + } + + [TestMethod] + public async Task RunIdCoordinator_FinalizeRunAsync_DoesNotCloseTheRunWhileAPeerProcessIsStillAlive() + { + // Consolidating several projects into one run is only safe if the owner does not close it while a + // peer is still publishing: Azure DevOps rejects everything sent to a completed run, so results + // that previously reached a separate run would simply be lost. + using TestDirectory directory = CreateTestDirectory(); + FakeClock clock = new() { UtcNow = new DateTimeOffset(2025, 1, 1, 12, 0, 0, TimeSpan.Zero) }; + AzureDevOpsTestResultsPublisherOptions options = new(10, TimeSpan.FromMinutes(1), 2, TimeSpan.FromMilliseconds(1), TimeSpan.FromSeconds(30), TimeSpan.FromHours(4)); + AzureDevOpsPublishConfiguration configuration = new("https://dev.azure.com/org/", "project", "token", 123, "run", "storage", directory.Path); + + // A peer participant whose lease names a process that is genuinely running, under a file name that + // cannot collide with the owner's own participant file. The owner reports a different process id so + // the peer is a genuine third party rather than the owner's own lease. + int ownerProcessId = GetAliveProcessId() + 1; + string peerParticipantPath = Path.Combine(directory.Path, "azdo-runid.123.participant.999999.json"); + Directory.CreateDirectory(directory.Path); + File.WriteAllText(peerParticipantPath, $"{{\"processId\":{GetAliveProcessId()},\"buildId\":123,\"expiresAt\":\"{clock.UtcNow.AddHours(4):O}\"}}"); + + int delayCount = 0; + FakeTask ownerTask = new(_ => + { + delayCount++; + + // Each poll costs 20s of wall clock, so the 30s grace period lapses on the second one. The + // peer only leaves much later; a coordinator that stops waiting for live peers would have + // completed the run long before that. + clock.UtcNow += TimeSpan.FromSeconds(20); + if (delayCount == 5) + { + File.Delete(peerParticipantPath); + } + }); + + AzureDevOpsRunIdCoordinator owner = new(new SystemFileSystem(), ownerTask, clock, CreateEnvironmentMock(processId: ownerProcessId).Object, new CollectingLogger(), options); + AzureDevOpsCoordinatedRun ownedRun = await owner.AcquireRunAsync(configuration, _ => Task.FromResult(950), CancellationToken.None); + Assert.IsTrue(ownedRun.IsOwner); + + int finalizeCalls = 0; + bool peerStillRegisteredWhenRunWasClosed = false; + await owner.FinalizeRunAsync( + ownedRun, + _ => + { + peerStillRegisteredWhenRunWasClosed = File.Exists(peerParticipantPath); + finalizeCalls++; + return Task.CompletedTask; + }, + CancellationToken.None); + + Assert.IsFalse(peerStillRegisteredWhenRunWasClosed, "The run was completed while a live peer was still registered as a participant."); + Assert.AreEqual(1, finalizeCalls); + Assert.IsGreaterThanOrEqualTo(5, delayCount); + } + + [TestMethod] + public async Task RunIdCoordinator_FinalizeRunAsync_OwnParticipantLeaseSurvivingDeletion_DoesNotWaitOnItself() + { + // Removing the owner's own lease is best-effort (an antivirus or indexer holding the handle makes + // it fail, which TryDeleteFile deliberately tolerates). The owner trivially passes every liveness + // check, so it must not treat its own leftover file as a peer that is still publishing — that + // would hold the run open for the whole hard cap for no reason. + using TestDirectory directory = CreateTestDirectory(); + FakeClock clock = new() { UtcNow = new DateTimeOffset(2025, 1, 1, 12, 0, 0, TimeSpan.Zero) }; + int delayCount = 0; + FakeTask task = new(_ => + { + delayCount++; + clock.UtcNow += TimeSpan.FromSeconds(20); + }); + AzureDevOpsTestResultsPublisherOptions options = new(10, TimeSpan.FromMinutes(1), 2, TimeSpan.FromMilliseconds(1), TimeSpan.FromSeconds(30), TimeSpan.FromHours(4)); + AzureDevOpsPublishConfiguration configuration = new("https://dev.azure.com/org/", "project", "token", 123, "run", "storage", directory.Path); + + UndeletableFileSystem fileSystem = new(); + AzureDevOpsRunIdCoordinator owner = new(fileSystem, task, clock, CreateEnvironmentMock(processId: GetAliveProcessId()).Object, new CollectingLogger(), options); + AzureDevOpsCoordinatedRun ownedRun = await owner.AcquireRunAsync(configuration, _ => Task.FromResult(960), CancellationToken.None); + + // From here every delete fails, so the owner's own participant lease stays on disk. + fileSystem.FailDeletes = true; + + int finalizeCalls = 0; + await owner.FinalizeRunAsync( + ownedRun, + _ => + { + finalizeCalls++; + return Task.CompletedTask; + }, + CancellationToken.None); + + Assert.IsTrue(File.Exists(ownedRun.ParticipantFilePath), "The test did not actually reproduce a surviving lease."); + Assert.AreEqual(1, finalizeCalls); + Assert.AreEqual(0, delayCount, "The owner polled instead of completing immediately, so it was waiting on its own lease."); + } + + [TestMethod] + public async Task RunIdCoordinator_AcquireRunAsync_RunIdFileWriteFailsUnderCancellation_StillReturnsTheCreatedRun() + { + // Once the run exists in Azure DevOps this process is the only one that can close it. If anything + // escapes the run-id file write - including cancellation, or a log provider throwing while + // reporting the write failure - AcquireRunAsync's cleanup deletes the leases and never hands the + // run back, leaving it "InProgress" forever. + using TestDirectory directory = CreateTestDirectory(); + using CancellationTokenSource canceled = new(); + FakeClock clock = new() { UtcNow = new DateTimeOffset(2025, 1, 1, 12, 0, 0, TimeSpan.Zero) }; + AzureDevOpsTestResultsPublisherOptions options = new(10, TimeSpan.FromMinutes(1), 2, TimeSpan.FromMilliseconds(1)); + AzureDevOpsPublishConfiguration configuration = new("https://dev.azure.com/org/", "project", "token", 123, "run", "storage", directory.Path); + + UnwritableFileSystem fileSystem = new(); + CollectingLogger logger = new(); + AzureDevOpsRunIdCoordinator coordinator = new(fileSystem, new FakeTask(), clock, CreateEnvironmentMock(processId: GetAliveProcessId()).Object, logger, options); + + AzureDevOpsCoordinatedRun run = await coordinator.AcquireRunAsync( + configuration, + _ => + { + // The run now exists remotely. Everything after this point must preserve ownership. + fileSystem.FailRunIdFileWrites = true; + logger.ThrowOnLog = true; +#pragma warning disable VSTHRD103 // CancelAsync is only available on .NET 8+; this project also targets .NET Framework. + canceled.Cancel(); +#pragma warning restore VSTHRD103 + return Task.FromResult(970); + }, + canceled.Token); + + Assert.AreEqual(970, run.RunId); + Assert.IsTrue(run.IsOwner); + } + + [TestMethod] + public async Task RunIdCoordinator_OwnerLeaseWithoutBuildContext_CanStillBeTakenOverEvenWhenThatPidIsAlive() + { + // A lease carrying the sentinel build id has no build context to vouch for it - that is how + // ReadLease reports the legacy plain-pid format, which it deliberately marks replaceable. A pid + // that has since been reused must not be mistaken for a live owner, or takeover is blocked forever. + using TestDirectory directory = CreateTestDirectory(); + FakeClock clock = new() { UtcNow = new DateTimeOffset(2025, 1, 1, 12, 0, 0, TimeSpan.Zero) }; + + // Advance the clock on every poll so that if takeover ever regresses the joiner wait reaches its + // deadline and the test fails, instead of spinning forever against a frozen clock. + FakeTask task = new(_ => clock.UtcNow += TimeSpan.FromSeconds(10)); + AzureDevOpsTestResultsPublisherOptions options = new(10, TimeSpan.FromMinutes(1), 2, TimeSpan.FromMilliseconds(1)); + AzureDevOpsPublishConfiguration configuration = new("https://dev.azure.com/org/", "project", "token", 123, "run", "storage", directory.Path); + + Directory.CreateDirectory(directory.Path); + File.WriteAllText( + Path.Combine(directory.Path, "azdo-runid.123.owner"), + JsonSerializer.Serialize(new AzureDevOpsLeaseFile(GetAliveProcessId(), 0, clock.UtcNow.AddHours(-1)))); + + AzureDevOpsRunIdCoordinator coordinator = new(new SystemFileSystem(), task, clock, CreateEnvironmentMock(processId: GetAliveProcessId() + 1).Object, new CollectingLogger(), options); + AzureDevOpsCoordinatedRun run = await coordinator.AcquireRunAsync(configuration, _ => Task.FromResult(980), CancellationToken.None); + + Assert.IsTrue(run.IsOwner, "A lease with no build context should never block takeover, whatever its pid is doing now."); + Assert.AreEqual(980, run.RunId); + } + + [TestMethod] + public async Task RunIdCoordinator_FinalizeRunAsync_TimeoutWarningThrows_StillClosesTheRun() + { + // The drain timeout warning sits directly in front of the call that completes the run. A log + // provider throwing there would skip it and leave the run "InProgress", which is exactly what the + // warning is reporting on. + using TestDirectory directory = CreateTestDirectory(); + FakeClock clock = new() { UtcNow = new DateTimeOffset(2025, 1, 1, 12, 0, 0, TimeSpan.Zero) }; + CollectingLogger logger = new(); + FakeTask task = new(timeSpan => clock.UtcNow += timeSpan); + AzureDevOpsTestResultsPublisherOptions options = new(10, TimeSpan.FromSeconds(5), 5, TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(30), TimeSpan.FromHours(4)); + int aliveProcessId = GetAliveProcessId(); + AzureDevOpsRunIdCoordinator coordinator = new(new SystemFileSystem(), task, clock, CreateEnvironmentMock(processId: aliveProcessId).Object, logger, options); + + string ownerFilePath = Path.Combine(directory.Path, "azdo-runid.123.owner"); + string runIdFilePath = Path.Combine(directory.Path, "azdo-runid.123.json"); + string participantFilePath = Path.Combine(directory.Path, $"azdo-runid.123.participant.{aliveProcessId}.json"); + File.WriteAllText(ownerFilePath, JsonSerializer.Serialize(new AzureDevOpsLeaseFile(aliveProcessId, 123, clock.UtcNow.AddHours(1)))); + File.WriteAllText(runIdFilePath, JsonSerializer.Serialize(new AzureDevOpsRunIdFile(5, 123, "https://dev.azure.com/org/", "project", clock.UtcNow.AddHours(1)))); + + // A participant that cannot be vouched for, so the short grace period lapses and the warning fires. + File.WriteAllText(Path.Combine(directory.Path, $"azdo-runid.123.participant.{int.MaxValue - 1}.json"), "not-json"); + logger.ThrowOnLog = true; + + int finalizeCalls = 0; + await coordinator.FinalizeRunAsync( + new AzureDevOpsCoordinatedRun(5, true, 123, directory.Path, runIdFilePath, ownerFilePath, participantFilePath), + _ => + { + finalizeCalls++; + return Task.CompletedTask; + }, + CancellationToken.None); + + Assert.AreEqual(1, finalizeCalls); + } + + [TestMethod] + public async Task RunIdCoordinator_FinalizeRunAsync_LivePeerThatNeverLeaves_StillFinalizesAtTheHardCap() + { + // The hard cap is what stops a leaked but still-running process from holding a run open forever. + // Without it the owner would keep renewing the grace period against a live peer indefinitely. + using TestDirectory directory = CreateTestDirectory(); + FakeClock clock = new() { UtcNow = new DateTimeOffset(2025, 1, 1, 12, 0, 0, TimeSpan.Zero) }; + AzureDevOpsTestResultsPublisherOptions options = new(10, TimeSpan.FromMinutes(1), 2, TimeSpan.FromMilliseconds(1), TimeSpan.FromSeconds(30), TimeSpan.FromHours(4)); + AzureDevOpsPublishConfiguration configuration = new("https://dev.azure.com/org/", "project", "token", 123, "run", "storage", directory.Path); + + // A peer that stays registered for the whole test and whose lease names a live process. + int ownerProcessId = GetAliveProcessId() + 1; + string peerParticipantPath = Path.Combine(directory.Path, "azdo-runid.123.participant.999998.json"); + Directory.CreateDirectory(directory.Path); + File.WriteAllText(peerParticipantPath, $"{{\"processId\":{GetAliveProcessId()},\"buildId\":123,\"expiresAt\":\"{clock.UtcNow.AddHours(4):O}\"}}"); + + int delayCount = 0; + int maxPolls = (int)(options.CoordinationFinalizeMaxWaitTime.TotalSeconds / 20) + 10; + FakeTask task = new(_ => + { + delayCount++; + + // Fail loudly rather than spinning forever if the hard cap ever stops bounding the wait: a + // hung suite is far harder to diagnose than a failed assertion. + Assert.IsLessThanOrEqualTo(maxPolls, delayCount, "The owner never stopped waiting for a live peer, so the hard cap is not bounding the drain loop."); + clock.UtcNow += TimeSpan.FromSeconds(20); + }); + + AzureDevOpsRunIdCoordinator owner = new(new SystemFileSystem(), task, clock, CreateEnvironmentMock(processId: ownerProcessId).Object, new CollectingLogger(), options); + AzureDevOpsCoordinatedRun ownedRun = await owner.AcquireRunAsync(configuration, _ => Task.FromResult(990), CancellationToken.None); + + int finalizeCalls = 0; + await owner.FinalizeRunAsync( + ownedRun, + _ => + { + finalizeCalls++; + return Task.CompletedTask; + }, + CancellationToken.None); + + Assert.AreEqual(1, finalizeCalls); + Assert.IsTrue(File.Exists(peerParticipantPath), "The peer was supposed to outlive the wait, so the hard cap is what released it."); + + // It waited well past the short grace period rather than giving up on a live peer immediately, + // and still stopped rather than waiting forever. + Assert.IsGreaterThan((int)(options.CoordinationFinalizeTimeout.TotalSeconds / 20), delayCount); + Assert.IsLessThanOrEqualTo((int)(options.CoordinationFinalizeMaxWaitTime.TotalSeconds / 20) + 2, delayCount); + } + + #endregion + + private static AzureDevOpsTestRunOrchestratorLifetime CreateOrchestratorLifetime( + string resultsDirectory, + out FakeAzureDevOpsTestResultsClient client, + out CollectingLogger logger, + Mock? environment = null, + CollectingOutputDevice? outputDevice = null) + { + Mock commandLineOptions = new(); + commandLineOptions.Setup(x => x.IsOptionSet(AzureDevOpsCommandLineOptions.PublishAzureDevOpsTestResultsOptionName)).Returns(true); + string[]? runNameArguments = null; + commandLineOptions.Setup(x => x.TryGetOptionArgumentList(AzureDevOpsCommandLineOptions.PublishAzureDevOpsRunNameOptionName, out runNameArguments)).Returns(false); + + Mock configuration = new(); + configuration.Setup(x => x[PlatformConfigurationConstants.PlatformResultDirectory]).Returns(resultsDirectory); + + environment ??= CreateEnvironmentMockWithSettableRunId(); + + Mock testApplicationModuleInfo = new(); + testApplicationModuleInfo.Setup(x => x.TryGetAssemblyName()).Returns("MyTests"); + testApplicationModuleInfo.Setup(x => x.GetCurrentTestApplicationFullPath()).Returns(Path.Combine("testfx-worktrees", "azdo-live", "artifacts", "MyTests.dll")); + + client = new FakeAzureDevOpsTestResultsClient(); + logger = new CollectingLogger(); + + // The fake clock advances on every poll so any coordination wait reaches its bound instead of + // spinning forever: FakeTask.Delay returns immediately, so a frozen clock would turn a future + // regression into a hung suite rather than a failing test. + FakeClock clock = new() { UtcNow = new DateTimeOffset(2025, 1, 1, 12, 0, 0, TimeSpan.Zero) }; + FakeTask task = new(_ => clock.UtcNow += TimeSpan.FromSeconds(30)); + + return new AzureDevOpsTestRunOrchestratorLifetime( + commandLineOptions.Object, + configuration.Object, + environment.Object, + new SystemFileSystem(), + outputDevice ?? new CollectingOutputDevice(), + testApplicationModuleInfo.Object, + client, + task, + clock, + logger, + new AzureDevOpsTestResultsPublisherOptions(10, TimeSpan.FromMinutes(1), 4, TimeSpan.FromMilliseconds(1))); + } + + /// + /// Makes the environment mock behave like a real process environment for the run-id handoff, so a value + /// written by the orchestrator lifetime is observable by everything that reads it afterwards. + /// + private static Mock CreateEnvironmentMockWithSettableRunId(string? initialRunId = null, int? processId = null) + { + Mock environment = CreateEnvironmentMock(processId: processId ?? GetAliveProcessId()); + string? runId = initialRunId; + environment.Setup(x => x.GetEnvironmentVariable(AzureDevOpsConstants.TestRunIdEnvironmentVariableName)).Returns(() => runId); + environment.Setup(x => x.SetEnvironmentVariable(AzureDevOpsConstants.TestRunIdEnvironmentVariableName, It.IsAny())) + .Callback((_, value) => runId = value); + return environment; + } + private TestDirectory CreateTestDirectory() => new(_directoriesToDelete); private static int GetAliveProcessId() @@ -1446,6 +2068,86 @@ private static TestNode CreateNode(string uid, IProperty state, DateTimeOffset s }; } + /// + /// A real file system whose run-id coordination file writes fail on demand. + /// + private sealed class UnwritableFileSystem : IFileSystem + { + private readonly SystemFileSystem _inner = new(); + + public bool FailRunIdFileWrites { get; set; } + + public IFileStream NewFileStream(string path, FileMode mode, FileAccess access, FileShare share) + => FailRunIdFileWrites && Path.GetFileName(path).EndsWith(".json", StringComparison.Ordinal) && !Path.GetFileName(path).Contains("participant") + ? throw new IOException($"The process cannot access the file '{path}' because it is being used by another process.") + : _inner.NewFileStream(path, mode, access, share); + + public void CopyFile(string sourceFileName, string destFileName, bool overwrite = false) => _inner.CopyFile(sourceFileName, destFileName, overwrite); + + public string CreateDirectory(string path) => _inner.CreateDirectory(path); + + public void DeleteFile(string path) => _inner.DeleteFile(path); + + public bool ExistDirectory(string? path) => _inner.ExistDirectory(path); + + public bool ExistFile(string path) => _inner.ExistFile(path); + + public string[] GetFiles(string path, string searchPattern, SearchOption searchOption) => _inner.GetFiles(path, searchPattern, searchOption); + + public void MoveFile(string sourceFileName, string destFileName, bool overwrite = false) => _inner.MoveFile(sourceFileName, destFileName, overwrite); + + public IFileStream NewFileStream(string path, FileMode mode) => _inner.NewFileStream(path, mode); + + public IFileStream NewFileStream(string path, FileMode mode, FileAccess access) => _inner.NewFileStream(path, mode, access); + + public string ReadAllText(string path) => _inner.ReadAllText(path); + + public Task ReadAllTextAsync(string path) => _inner.ReadAllTextAsync(path); + } + + /// + /// A real file system whose deletes fail, emulating a handle held by an antivirus or search indexer - + /// the situation the coordinator's best-effort deletes exist to tolerate. + /// + private sealed class UndeletableFileSystem : IFileSystem + { + private readonly SystemFileSystem _inner = new(); + + public bool FailDeletes { get; set; } + + public void DeleteFile(string path) + { + if (FailDeletes) + { + throw new IOException($"The process cannot access the file '{path}' because it is being used by another process."); + } + + _inner.DeleteFile(path); + } + + public void CopyFile(string sourceFileName, string destFileName, bool overwrite = false) => _inner.CopyFile(sourceFileName, destFileName, overwrite); + + public string CreateDirectory(string path) => _inner.CreateDirectory(path); + + public bool ExistDirectory(string? path) => _inner.ExistDirectory(path); + + public bool ExistFile(string path) => _inner.ExistFile(path); + + public string[] GetFiles(string path, string searchPattern, SearchOption searchOption) => _inner.GetFiles(path, searchPattern, searchOption); + + public void MoveFile(string sourceFileName, string destFileName, bool overwrite = false) => _inner.MoveFile(sourceFileName, destFileName, overwrite); + + public IFileStream NewFileStream(string path, FileMode mode) => _inner.NewFileStream(path, mode); + + public IFileStream NewFileStream(string path, FileMode mode, FileAccess access) => _inner.NewFileStream(path, mode, access); + + public IFileStream NewFileStream(string path, FileMode mode, FileAccess access, FileShare share) => _inner.NewFileStream(path, mode, access, share); + + public string ReadAllText(string path) => _inner.ReadAllText(path); + + public Task ReadAllTextAsync(string path) => _inner.ReadAllTextAsync(path); + } + private sealed class FakeClock : IClock { public DateTimeOffset UtcNow { get; set; } diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Hosts/TestHostOrchestratorHostTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Hosts/TestHostOrchestratorHostTests.cs new file mode 100644 index 0000000000..0185204d75 --- /dev/null +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Hosts/TestHostOrchestratorHostTests.cs @@ -0,0 +1,346 @@ +// 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.Extensions.TestHostOrchestrator; +using Microsoft.Testing.Platform.Helpers; +using Microsoft.Testing.Platform.Hosts; +using Microsoft.Testing.Platform.Logging; +using Microsoft.Testing.Platform.Services; +using Microsoft.Testing.Platform.TestHostOrchestrator; + +namespace Microsoft.Testing.Platform.UnitTests; + +/// +/// Covers the orchestrator host's application-lifetime contract: whatever BeforeRunAsync acquired +/// must be released on every exit path, including cancellation and failure. See +/// — an Azure DevOps test run created there +/// and never closed stays "InProgress" and never appears in the build's Tests tab. +/// +[TestClass] +public sealed class TestHostOrchestratorHostTests +{ + [TestMethod] + public async Task RunAsync_OrchestratorSucceeds_CallsAfterRunWithTheOrchestratorExitCode() + { + RecordingLifetime lifetime = new(); + TestHostOrchestratorHost host = CreateHost(new RecordingOrchestrator(exitCode: 7), lifetime, out _); + + int exitCode = await host.RunAsync(); + + Assert.AreEqual(7, exitCode); + Assert.AreEqual(1, lifetime.BeforeRunCount); + Assert.AreEqual(1, lifetime.AfterRunCount); + Assert.AreEqual(7, lifetime.LastExitCode); + Assert.AreEqual(1, lifetime.DisposeCount); + } + + [TestMethod] + public async Task RunAsync_OrchestratorCanceled_StillCallsAfterRunAndDisposes() + { + RecordingLifetime lifetime = new(); + TestHostOrchestratorHost host = CreateHost( + new RecordingOrchestrator(onOrchestrate: cancellationTokenSource => + { + cancellationTokenSource.Cancel(); + throw new OperationCanceledException(); + }), + lifetime, + out _); + + int exitCode = await host.RunAsync(); + + Assert.AreEqual((int)ExitCode.TestSessionAborted, exitCode); + Assert.AreEqual(1, lifetime.BeforeRunCount); + Assert.AreEqual(1, lifetime.AfterRunCount); + Assert.AreEqual((int)ExitCode.TestSessionAborted, lifetime.LastExitCode); + Assert.AreEqual(1, lifetime.DisposeCount); + } + + [TestMethod] + public async Task RunAsync_OrchestratorThrows_CallsAfterRunAndDisposesThenRethrows() + { + RecordingLifetime lifetime = new(); + TestHostOrchestratorHost host = CreateHost( + new RecordingOrchestrator(onOrchestrate: _ => throw new InvalidOperationException("orchestrator exploded")), + lifetime, + out _); + + InvalidOperationException exception = await Assert.ThrowsExactlyAsync(host.RunAsync); + + Assert.AreEqual("orchestrator exploded", exception.Message); + Assert.AreEqual(1, lifetime.BeforeRunCount); + Assert.AreEqual(1, lifetime.AfterRunCount); + Assert.AreEqual((int)ExitCode.GenericFailure, lifetime.LastExitCode); + Assert.AreEqual(1, lifetime.DisposeCount); + } + + [TestMethod] + public async Task RunAsync_LifetimeBeforeRunThrows_StillCallsAfterRunOnEveryLifetime() + { + // A lifetime whose BeforeRunAsync faulted, and one whose BeforeRunAsync never ran, both still get + // AfterRunAsync so neither can strand a resource it may have partially acquired. + RecordingLifetime faulting = new(beforeRunException: new InvalidOperationException("before-run exploded")); + RecordingLifetime never = new(); + TestHostOrchestratorHost host = CreateHost(new RecordingOrchestrator(exitCode: 0), [faulting, never], out _); + + await Assert.ThrowsExactlyAsync(host.RunAsync); + + Assert.AreEqual(1, faulting.BeforeRunCount); + Assert.AreEqual(1, faulting.AfterRunCount); + Assert.AreEqual((int)ExitCode.GenericFailure, faulting.LastExitCode); + Assert.AreEqual(1, faulting.DisposeCount); + Assert.AreEqual(0, never.BeforeRunCount); + Assert.AreEqual(1, never.AfterRunCount); + Assert.AreEqual((int)ExitCode.GenericFailure, never.LastExitCode); + Assert.AreEqual(1, never.DisposeCount); + } + + [TestMethod] + public async Task RunAsync_OrchestratorThrows_OneLifetimeFailingDoesNotBlockTheNext() + { + RecordingLifetime failing = new(afterRunException: new InvalidOperationException("cleanup exploded")); + RecordingLifetime healthy = new(); + TestHostOrchestratorHost host = CreateHost( + new RecordingOrchestrator(onOrchestrate: _ => throw new InvalidOperationException("orchestrator exploded")), + [failing, healthy], + out _); + + // The orchestrator's failure is what surfaces, not the cleanup failure. + InvalidOperationException exception = await Assert.ThrowsExactlyAsync(host.RunAsync); + + Assert.AreEqual("orchestrator exploded", exception.Message); + Assert.AreEqual(1, failing.BeforeRunCount); + Assert.AreEqual(1, failing.AfterRunCount); + Assert.AreEqual((int)ExitCode.GenericFailure, failing.LastExitCode); + Assert.AreEqual(1, failing.DisposeCount); + Assert.AreEqual(1, healthy.BeforeRunCount); + Assert.AreEqual(1, healthy.AfterRunCount); + Assert.AreEqual((int)ExitCode.GenericFailure, healthy.LastExitCode); + Assert.AreEqual(1, healthy.DisposeCount); + } + + [TestMethod] + public async Task RunAsync_OrchestratorCanceled_LifetimeAfterRunFailureIsSwallowed() + { + RecordingLifetime lifetime = new(afterRunException: new InvalidOperationException("cleanup exploded")); + TestHostOrchestratorHost host = CreateHost( + new RecordingOrchestrator(onOrchestrate: cancellationTokenSource => + { + cancellationTokenSource.Cancel(); + throw new OperationCanceledException(); + }), + lifetime, + out _); + + int exitCode = await host.RunAsync(); + + Assert.AreEqual((int)ExitCode.TestSessionAborted, exitCode); + Assert.AreEqual(1, lifetime.BeforeRunCount); + Assert.AreEqual(1, lifetime.AfterRunCount); + Assert.AreEqual((int)ExitCode.TestSessionAborted, lifetime.LastExitCode); + Assert.AreEqual(1, lifetime.DisposeCount); + } + + [TestMethod] + public async Task RunAsync_OrchestratorSucceeds_LifetimeIsNotInvokedTwice() + { + RecordingLifetime lifetime = new(); + TestHostOrchestratorHost host = CreateHost(new RecordingOrchestrator(exitCode: 0), lifetime, out _); + + await host.RunAsync(); + + Assert.AreEqual(1, lifetime.BeforeRunCount); + Assert.AreEqual(1, lifetime.AfterRunCount); + Assert.AreEqual(0, lifetime.LastExitCode); + Assert.AreEqual(1, lifetime.DisposeCount); + } + + [TestMethod] + public async Task RunAsync_LoggerThrows_StillCleansUpEveryLifetime() + { + // Diagnostic logging in the cleanup loop is best-effort: the aggregate logger propagates provider + // exceptions, so a broken log provider must not skip disposal or the remaining lifetimes - the very + // resources this loop exists to release. + RecordingLifetime failing = new(afterRunException: new InvalidOperationException("cleanup exploded")); + RecordingLifetime healthy = new(); + TestHostOrchestratorHost host = CreateHost( + new RecordingOrchestrator(onOrchestrate: _ => throw new InvalidOperationException("orchestrator exploded")), + [failing, healthy], + out _, + new ThrowingLoggerFactory()); + + InvalidOperationException exception = await Assert.ThrowsExactlyAsync(host.RunAsync); + + Assert.AreEqual("orchestrator exploded", exception.Message); + Assert.AreEqual(1, failing.BeforeRunCount); + Assert.AreEqual(1, failing.AfterRunCount); + Assert.AreEqual((int)ExitCode.GenericFailure, failing.LastExitCode); + Assert.AreEqual(1, failing.DisposeCount); + Assert.AreEqual(1, healthy.BeforeRunCount); + Assert.AreEqual(1, healthy.AfterRunCount); + Assert.AreEqual((int)ExitCode.GenericFailure, healthy.LastExitCode); + Assert.AreEqual(1, healthy.DisposeCount); + } + + private static TestHostOrchestratorHost CreateHost( + RecordingOrchestrator orchestrator, + RecordingLifetime lifetime, + out FakeApplicationCancellationTokenSource cancellationTokenSource) + => CreateHost(orchestrator, [lifetime], out cancellationTokenSource); + + private static TestHostOrchestratorHost CreateHost( + RecordingOrchestrator orchestrator, + RecordingLifetime[] lifetimes, + out FakeApplicationCancellationTokenSource cancellationTokenSource, + ILoggerFactory? loggerFactory = null) + { + ServiceProvider serviceProvider = new(); + cancellationTokenSource = new FakeApplicationCancellationTokenSource(); + orchestrator.CancellationTokenSource = cancellationTokenSource; + serviceProvider.AddService(cancellationTokenSource); + serviceProvider.AddService(loggerFactory ?? new NopLoggerFactory()); + serviceProvider.AddServices([.. lifetimes]); + + return new TestHostOrchestratorHost(new TestHostOrchestratorConfiguration([orchestrator]), serviceProvider); + } + + private sealed class RecordingOrchestrator : ITestHostExecutionOrchestrator + { + private readonly Action? _onOrchestrate; + + public RecordingOrchestrator(int exitCode = 0, Action? onOrchestrate = null) + { + ExitCode = exitCode; + _onOrchestrate = onOrchestrate; + } + + public int ExitCode { get; } + + public FakeApplicationCancellationTokenSource CancellationTokenSource { get; set; } = new(); + + public string Uid => nameof(RecordingOrchestrator); + + public string Version => "1.0.0"; + + public string DisplayName => nameof(RecordingOrchestrator); + + public string Description => nameof(RecordingOrchestrator); + + public Task IsEnabledAsync() => Task.FromResult(true); + + public Task OrchestrateTestHostExecutionAsync(CancellationToken cancellationToken) + { + _onOrchestrate?.Invoke(CancellationTokenSource); + return Task.FromResult(ExitCode); + } + } + + private sealed class RecordingLifetime : ITestHostOrchestratorApplicationLifetime, IDisposable + { + private static int s_instanceCount; + private readonly Exception? _beforeRunException; + private readonly Exception? _afterRunException; + + public RecordingLifetime(Exception? beforeRunException = null, Exception? afterRunException = null) + { + _beforeRunException = beforeRunException; + _afterRunException = afterRunException; + Uid = $"{nameof(RecordingLifetime)}-{Interlocked.Increment(ref s_instanceCount)}"; + } + + public int BeforeRunCount { get; private set; } + + public int AfterRunCount { get; private set; } + + public int DisposeCount { get; private set; } + + public int? LastExitCode { get; private set; } + + public string Uid { get; } + + public string Version => "1.0.0"; + + public string DisplayName => Uid; + + public string Description => Uid; + + public Task IsEnabledAsync() => Task.FromResult(true); + + public Task BeforeRunAsync(CancellationToken cancellationToken) + { + BeforeRunCount++; + return _beforeRunException is null ? Task.CompletedTask : throw _beforeRunException; + } + + public Task AfterRunAsync(int exitCode, CancellationToken cancellationToken) + { + AfterRunCount++; + LastExitCode = exitCode; + return _afterRunException is null ? Task.CompletedTask : throw _afterRunException; + } + + public void Dispose() => DisposeCount++; + } + + private sealed class FakeApplicationCancellationTokenSource : ITestApplicationCancellationTokenSource, IDisposable + { + private readonly CancellationTokenSource _cancellationTokenSource = new(); + + public CancellationToken CancellationToken => _cancellationTokenSource.Token; + +#pragma warning disable VSTHRD103 // CancelAsync is only available on .NET 8+; this project also targets .NET Framework. + public void Cancel() => _cancellationTokenSource.Cancel(); +#pragma warning restore VSTHRD103 + + public void Dispose() => _cancellationTokenSource.Dispose(); + } + + private sealed class NopLoggerFactory : ILoggerFactory + { + public ILogger CreateLogger(string categoryName) => new NopLogger(); + + private sealed class NopLogger : ILogger + { + public bool IsEnabled(LogLevel logLevel) => false; + + public void Log(LogLevel logLevel, TState state, Exception? exception, Func formatter) + { + } + + public Task LogAsync(LogLevel logLevel, TState state, Exception? exception, Func formatter) + => Task.CompletedTask; + } + } + + /// + /// A logger whose provider throws for the levels the cleanup loop uses, mirroring the aggregate + /// logger's behaviour of propagating provider exceptions to the caller. Other levels pass through so + /// the host's own startup logging, which is outside the cleanup path, still works. + /// + private sealed class ThrowingLoggerFactory : ILoggerFactory + { + public ILogger CreateLogger(string categoryName) => new ThrowingLogger(); + + private sealed class ThrowingLogger : ILogger + { + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log(LogLevel logLevel, TState state, Exception? exception, Func formatter) + => ThrowIfCleanupLevel(logLevel); + + public Task LogAsync(LogLevel logLevel, TState state, Exception? exception, Func formatter) + { + ThrowIfCleanupLevel(logLevel); + return Task.CompletedTask; + } + + private static void ThrowIfCleanupLevel(LogLevel logLevel) + { + if (logLevel is LogLevel.Warning or LogLevel.Debug) + { + throw new InvalidOperationException("log provider exploded"); + } + } + } + } +}