Repository navigation
Publish one Azure DevOps test run per build when retrying failed tests - #10375
Conversation
`--publish-azdo-test-results` combined with `--retry-failed-tests` created and completed one Azure DevOps test run per attempt, so a test that failed and then passed on a retry was recorded as Failed in one run and Passed in another, with nothing tying them together. The live-results publisher was registered only as a test host extension, and each retry attempt is a separate process running a full create-run, publish, complete lifecycle. The one consolidation mechanism, AzureDevOpsRunIdCoordinator, is scoped to `--results-directory`, which the retry orchestrator rewrites per attempt, and attempts are sequential so attempt 1 closed its run before attempt 2 started. Move the run's lifetime to the orchestrator process, the only one that outlives every attempt, using the existing ITestHostOrchestratorApplicationLifetime. It acquires the run through the coordinator (so several projects sharing a results directory still land in one run), hands the id to the attempts through the inherited TESTINGPLATFORM_AZUREDEVOPS_TESTRUNID variable, and completes the run once. The Retry package is unchanged. Also fix related correctness gaps found while reviewing this area: - Run the orchestrator application lifetimes' AfterRunAsync and disposal when the orchestration is canceled or fails, not only when it succeeds. A run created in BeforeRunAsync was otherwise left InProgress and never appeared in the build's Tests tab. - Keep a run open while a peer test project whose process is still alive has yet to publish. The owner previously gave up after a fixed 30 second grace period, which now that builds are consolidated would make Azure DevOps reject the remaining projects' results. - Do not take over ownership from, or discard the run-id file of, an owner whose lease expired but whose process is still running. An orchestrator holds its lease for the whole orchestration without renewing it, so a peer could otherwise create a duplicate run and orphan the first. - Scope the run-id handoff to the build id so a stale variable inherited from an earlier build cannot redirect results into an unrelated run. - Keep ownership of a created run when writing the local run-id file fails, instead of discarding it and stranding the run. A test rescued by a retry still contributes one result per attempt inside the single run; collapsing those into one result carrying the final outcome needs the test result update API and is tracked separately. Co-authored-by: Copilot App <[email protected]> Copilot-Session: 64c1ea56-9892-4908-803a-77751517ad1b
There was a problem hiding this comment.
Pull request overview
Moves Azure DevOps test-run ownership to the orchestrator so retries share one run.
Changes:
- Adds build-scoped run-ID handoff between orchestrator and test hosts.
- Improves coordination, peer waiting, and cleanup behavior.
- Adds API tracking, tests, and changelog entries.
Show a summary per file
| File | Description |
|---|---|
TestHostOrchestratorHostTests.cs |
Tests orchestrator cleanup paths. |
AzureDevOpsLivePublishingTests.cs |
Tests handoff and coordination behavior. |
ITestHostOrchestratorApplicationLifetime.cs |
Documents cleanup guarantees. |
TestHostOchestratorHost.cs |
Runs cleanup after cancellation or failure. |
InternalAPI.Unshipped.txt |
Tracks new internal APIs. |
AzureDevOpsTestRunOrchestratorLifetime.cs |
Owns runs across retry attempts. |
AzureDevOpsTestResultsPublisher.cs |
Joins inherited runs. |
AzureDevOpsRunIdCoordinator.cs |
Extends ownership and peer coordination. |
AzureDevOpsPublishConfigurationFactory.cs |
Shares publishing configuration creation. |
AzureDevOpsLivePublishingModels.cs |
Adds maximum finalization wait. |
AzureDevOpsExtensions.cs |
Registers the orchestrator lifetime. |
AzureDevOpsConstants.cs |
Adds build-scoped run-ID handoff. |
Changelog-Platform.md |
Documents the fixes. |
Review details
Suppressed comments (1)
src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsRunIdCoordinator.cs:480
- Once
createRunAsynchas returned, the remote run already exists, but cancellation during this file write is excluded from the recovery catch.AcquireRunAsyncthen deletes the leases and the caller never receives/stores the coordinated run, soAfterRunAsynccannot complete it and it remainsInProgress. Treat every write failure after successful creation—including cancellation—as best-effort while retaining ownership; the warning itself must also be non-throwing.
catch (Exception ex) when (!cancellationToken.IsCancellationRequested)
{
_logger.LogWarning($"{AzureDevOpsResources.AzureDevOpsLivePublishingFailedToDeleteCoordinationFile} {runIdFilePath}: {ex.Message}");
- Files reviewed: 13/13 changed files
- Comments generated: 3
- Review effort level: Balanced
There was a problem hiding this comment.
🤖 Automated content by GitHub Copilot. Generated by the Grade Tests on PR (on open / sync) workflow. · sonnet46 105.5 AIC · ⌖ 4.49 AIC · ⊞ 11.8K · ◷
Make orchestrator cleanup and its diagnostics robust, and report the right message for each failure mode. - Diagnostic logging in the orchestrator cleanup loop is now best-effort. The aggregate logger propagates provider exceptions, so a broken log provider could previously escape the loop and skip disposal or the remaining lifetimes, stranding the very resources the loop exists to release. - Cleanup failures are now swallowed on the cancellation path as well as the faulted path. The orchestration already has an outcome to report there, so turning a cleanup failure into an unhandled exception was strictly worse than returning the aborted exit code. They still surface after a normally completed orchestration. - Document on ITestHostOrchestratorApplicationLifetime.AfterRunAsync that implementations should not throw, and that on the cancellation and failure paths any exception they do throw is logged and suppressed. - Report the deadline that actually fired when the finalize wait gives up, so the warning no longer claims a 30 second wait when the run was held for the hard cap instead. - Add a coordination-file write failure message instead of reusing the delete one, so a stranded run does not point at deletion code. - Add a run id handoff failure message instead of reusing the create-run one. The handoff catch runs only after the run exists, so claiming the run could not be created was misleading. Tests: cover a throwing log provider and a lifetime that fails cleanup during cancellation, and pin the call sequence (BeforeRunAsync count, the exit code handed to AfterRunAsync, disposal of a lifetime whose cleanup threw) plus the run id and final state on the Azure DevOps finalize assertions. Co-authored-by: Copilot App <[email protected]> Copilot-Session: 64c1ea56-9892-4908-803a-77751517ad1b
There was a problem hiding this comment.
Review details
Suppressed comments (2)
src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsRunIdCoordinator.cs:486
- Once
createRunAsynchas returned, cancellation during the cancellable file write must not escape: the outercatchdeletes the owner files,AcquireRunAsyncnever returns the run handle, andAfterRunAsynctherefore cannot close the already-created Azure DevOps run. The warning also needs guarding because logger providers can throw and cause the same ownership loss. Swallow both failures here so the owner handle is returned and teardown can finalize the run.
catch (Exception ex) when (!cancellationToken.IsCancellationRequested)
{
_logger.LogWarning($"{AzureDevOpsResources.AzureDevOpsLivePublishingFailedToWriteCoordinationFile} {runIdFilePath}: {ex.Message}");
src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsRunIdCoordinator.cs:57
- If this write fails, the owner still keeps its lease but publishes no run-id file. A peer then waits in
WaitForRunIdFileAsync, cannot take over because the owner process is alive, and eventually throwsAzureDevOpsLivePublishingMissingRunIdFile; live publishing is disabled for that peer rather than falling back to its own run as the new recovery-path comment claims. Preserve the created run, but also put coordination into a state where peers can either discover this ID or safely create independent runs.
This issue also appears on line 484 of the same file.
await TryWriteRunIdFileAsync(runIdFilePath, configuration, runId, cancellationToken).ConfigureAwait(false);
- Files reviewed: 27/27 changed files
- Comments generated: 0 new
- Review effort level: Balanced
There was a problem hiding this comment.
🤖 Automated content by GitHub Copilot. Generated by the Grade Tests on PR (on open / sync) workflow. · sonnet46 177.7 AIC · ⌖ 4.49 AIC · ⊞ 11.8K · ◷
Once createRunAsync returns, the run exists in Azure DevOps and this process is the only one that can close it. Anything escaping the run-id file write unwinds into AcquireRunAsync's cleanup, which deletes the leases and never hands the run back, so AfterRunAsync cannot finalize it and the run stays InProgress forever. Two paths could still escape: cancellation, which the catch filter deliberately let through, and the logger itself, since the aggregate logger propagates provider exceptions. Neither is worth losing a run over, so the write is now tolerant of both. TryDeleteFile's warnings go through the same non-throwing helper, because it is called from cleanup paths where a throwing provider would replace the failure being handled. Also corrects the remark on the write helper: peers do not fall back to creating their own run when the file is missing, they wait for it and then report that live publishing could not start. Co-authored-by: Copilot App <[email protected]> Copilot-Session: 64c1ea56-9892-4908-803a-77751517ad1b
|
Picked up the two suppressed comments on
Fixed in 20d11e9 - this was a real gap in my own earlier fix.
Correct that my remark was wrong, and I have rewritten it to say what actually happens. I deliberately did not change the coordination behaviour: making peers take over or create independent runs here means either releasing an owner lease this process is still using, or a second owner whose lease the original owner would later delete on finalize. That is a real design question rather than a small fix, and it only triggers when a local write to a just-created results directory fails, so I would rather not land it unreviewed in this PR. |
Assert the exit code handed to AfterRunAsync and the BeforeRunAsync count where they were missing, and the run id and final state on the Azure DevOps finalize assertions, so a mutation that cleans up the wrong run, or with the wrong exit code or state, cannot survive. Co-authored-by: Copilot App <[email protected]> Copilot-Session: 64c1ea56-9892-4908-803a-77751517ad1b
There was a problem hiding this comment.
Review details
Suppressed comments (4)
src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsRunIdCoordinator.cs:187
- Calling the logger directly here can prevent the run from being finalized. Logging providers are allowed to throw, and this call occurs before
finalizeRunAsync; if it throws at either deadline, the run remainsInProgress. Use the existing best-effort logging helper so diagnostics cannot interrupt cleanup.
_logger.LogWarning(string.Format(CultureInfo.InvariantCulture, AzureDevOpsResources.AzureDevOpsLivePublishingFinalizeWaitTimedOut, timeout, participantFiles.Length));
src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsRunIdCoordinator.cs:416
- A live PID does not prove that the lease owner is still alive because operating systems reuse process IDs. If the original owner exits or crashes and its expired files survive, an unrelated process can later acquire the same PID; this helper then treats the stale owner as authoritative,
WaitForRunIdFileAsyncreturns the old run ID, and results can be sent to a completed/orphaned run without any process owning finalization. Persist and compare a process-identity value such as start time alongside the PID, or renew the orchestrator lease so expiry can remain authoritative.
private static bool IsOwnerStillAlive(LeaseReadResult lease)
=> lease.Lease is { } ownerLease && IsProcessAlive(ownerLease.ProcessId);
docs/Changelog-Platform.md:33
- This says the remaining final-outcome work is tracked in #10360, but the PR description uses
Fixes #10360, which will close that issue on merge even though its expected behavior includes collapsing attempts into one final result. Create and link a separate follow-up issue here, or remove the closing keyword, so the explicitly deferred requirement remains tracked.
* 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)
src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsRunIdCoordinator.cs:156
- The hard-cap behavior is not exercised by the new coordinator tests: the live-participant test deletes its lease before this deadline, while the timeout test uses an unresponsive participant. Removing this deadline would therefore leave all tests passing and allow a leaked-but-live process to stall finalization indefinitely. Add a test that keeps a live participant registered beyond
CoordinationFinalizeMaxWaitTimeand verifies the run is finalized once.
This issue also appears on line 187 of the same file.
DateTimeOffset unresponsiveDeadline = _clock.UtcNow + _options.CoordinationFinalizeTimeout;
DateTimeOffset hardDeadline = _clock.UtcNow + _options.CoordinationFinalizeMaxWaitTime;
- Files reviewed: 27/27 changed files
- Comments generated: 0 new
- Review effort level: Balanced
This comment has been minimized.
This comment has been minimized.
ReadLease reports a lease that carries no build id as expired precisely so it can be replaced, but the liveness override then treated it as authoritative whenever its pid happened to be alive. A reused pid could therefore block takeover indefinitely and strand live publishing. Exclude the sentinel build id from the override, and route the joiner's owner-liveness check through the same helper so both paths agree on what counts as a live owner. Co-authored-by: Copilot App <[email protected]> Copilot-Session: 64c1ea56-9892-4908-803a-77751517ad1b
The warning sits directly in front of the call that completes the Azure DevOps run, and the aggregate logger propagates provider failures, so a broken log provider would skip it and leave the run InProgress - which is exactly what the warning is reporting on. Route it through the existing non-throwing helper. Co-authored-by: Copilot App <[email protected]> Copilot-Session: 64c1ea56-9892-4908-803a-77751517ad1b
There was a problem hiding this comment.
Review details
Suppressed comments (1)
src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsRunIdCoordinator.cs:622
- C# records expose a
Deconstructmethod; “deconstructor” incorrectly names the generated API this comment is preserving. Use the actual member name.
/// record's constructor and deconstructor signatures. An inherited run has no coordination files of
- Files reviewed: 27/27 changed files
- Comments generated: 0 new
- Review effort level: Balanced
This comment has been minimized.
This comment has been minimized.
The drain loop's hard cap is what stops a leaked but still-running peer from holding a run open forever, but no test exercised it: the live-peer test removes its lease before the cap, and the timeout test uses a participant that cannot be proven alive. Removing the cap left every test passing. The new test keeps a live peer registered for the whole wait and asserts the run is still finalized exactly once. It also bounds its own polling so that losing the cap fails the test rather than hanging the suite. Co-authored-by: Copilot App <[email protected]> Copilot-Session: 64c1ea56-9892-4908-803a-77751517ad1b
|
Worked through the four suppressed comments from the review at 22:59Z.
Already fixed in 968920d, and that was the last direct logger call left in the coordinator, so the whole file now goes through the non-throwing helper.
Correct, and a good catch. Fixed in 4bf8683 with a test that keeps a live peer registered for the whole wait and asserts the run is still finalized exactly once. Removing the cap now fails it. I also had it bound its own polling, because the first version of that test caught the regression by hanging rather than failing, and a hung suite is much worse to diagnose than a failed assertion.
Right, those contradicted each other. I have dropped the closing keyword from the description so the issue stays open for the final-outcome work, and said so explicitly under "Not in scope".
Valid, and I have listed it under "Not in scope" rather than fixing it here. Bare-pid liveness is what the coordination has always used ( |
🧪 Test quality grade — PR #10375
This advisory comment was generated automatically. Grades are heuristic and informational — they do not block merging. All 40 test methods across 2 files grade A: the improvements from the previous review round were fully incorporated. Re-run with
|
Follow-up to #10375, which made `--publish-azdo-test-results` combined with `--retry-failed-tests` produce a single test run per build. Within that run each attempt still POSTed a fresh result, so a test that failed and then passed on retry appeared as two independent rows: neither row was the truth on its own, and pass-rate analytics counted the same test more than once. A retry attempt now updates the result the earlier attempt created, appending itself as a sub-result under `resultGroupType: rerun`, so one test that ran several times stays one result with its attempts recorded underneath it. The parent takes the latest attempt's outcome. Azure DevOps computes run metrics from the parent rather than from the sub-results, so this is what stops a test rescued by a retry being reported as failed — which is the same verdict the pipeline's own exit code already reaches. The earlier attempts are not erased; they remain visible as sub-results, which is what makes the flakiness apparent. Carrying the mapping from test to result id across attempts needs a shared file, because the process publishing attempt 2 is not the one that published attempt 1 and environment variables only flow parent-to-child at launch. It cannot live in the publisher's own results directory either: the retry orchestrator gives every attempt a directory of its own, so a file written there would be invisible to the next attempt. The orchestrator therefore chooses the path, names it after its own process id, and hands it down. That also scopes merging to a single orchestration, so test hosts that merely run alongside each other — the same assembly multi-targeted, say — keep publishing independent results exactly as before. The handoff is a separate environment variable rather than another field of the existing one, because an older process parses that value positionally and would reject a longer form, silently undoing the one-run-per-build guarantee. Every failure path degrades to publishing a separate result rather than to silence: an unparseable map, a create response without ids, a rejected update and a failed map write all leave the run with more rows than ideal, never with fewer results than tests. The map only advances once Azure DevOps has accepted an update, so retrying a rejected one cannot list the same execution twice, and it is written once at the end of the session rather than after every batch, which would be quadratic in the size of the suite and would be paid even by runs that never retry anything. Attachments from a retry attempt go to the parent result, named per attempt. Azure DevOps accumulates rather than replaces them, so two attempts would otherwise both contribute a `stdout.log` with no way to tell them apart. Co-authored-by: Copilot App <[email protected]> Copilot-Session: 522344b1-f0e0-47a5-a8d0-cf897db28152
Addresses #10360 (deliberately not using a closing keyword: the final-outcome half of that issue is still open, see Not in scope below)
Why
--publish-azdo-test-resultscombined with--retry-failed-testscreated and completed one Azure DevOps test run per attempt. A test that failed and then passed on a retry was recorded asFailedin one run andPassedin another, with nothing tying them together, and the recovered test stayedFailedforever in the earlier run.This is on our side, not an Azure DevOps limitation. The live-results publisher was registered only as a test host extension, and every retry attempt is a separate process running a full create-run / publish / complete lifecycle. The one consolidation mechanism,
AzureDevOpsRunIdCoordinator, is keyed by build id but located in--results-directory, which the retry orchestrator rewrites per attempt (RetryArgumentsBuilder.ComputeIndicesToCleanup). Attempts are also sequential, so attempt 1 always closed its run before attempt 2 started.Approach
Move the run's lifetime to the orchestrator process, the only one that outlives every attempt, using the pre-existing
[TPEXP]ITestHostOrchestratorApplicationLifetime. No new platform API, and the Retry package is untouched.BeforeRunAsyncacquires the run through the coordinator, so several test projects sharing a results directory still consolidate into a single run, then publishes the id in the inheritedTESTINGPLATFORM_AZUREDEVOPS_TESTRUNIDvariable (scoped as<buildId>:<runId>so a stale value from another build cannot redirect results).AfterRunAsync(exitCode)completes or aborts the run exactly once.An attempt genuinely cannot own the run: the retry options are stripped from its command line, so it can never know whether it is the last one. The orchestrator lifetime is only built when an orchestrator is active, so this is inert for a normal run.
Also fixed in this area
Reviewing the surrounding code turned up several related defects, some pre-existing and affecting non-retry multi-project builds today:
AfterRunAsyncand disposal now also run when the orchestration is canceled or throws. Without this a run created inBeforeRunAsyncwas leftInProgressand never appeared in the build's Tests tab. This is deterministic for--retry-failed-testswith--serveror hot reload, which throw before running anything.Worth a careful look
TestHostOchestratorHost.RunAsyncis shared platform code. It now guaranteesAfterRunAsyncruns on every exit path, which is a new expectation on implementations of a public[TPEXP]interface. I documented it onITestHostOrchestratorApplicationLifetime.AfterRunAsync: implementations must tolerate being called when theirBeforeRunAsyncdid not run or complete, should not throw, and must not assume the token is still usable.Not in scope
A test rescued by a retry still contributes one result per attempt inside the single run (
FailedthenPassed). Collapsing those into one result carrying the final outcome needsPATCH .../runs/{id}/resultsplus an attempt-to-attempt result-id map, and is worth a separate change. That is why this PR does not close #10360.Also out of scope, and worth separate follow-ups:
RetryTestHostRunnercancellation race.Validation
Microsoft.Testing.Extensions.UnitTestsand 1984 inMicrosoft.Testing.Platform.UnitTests, including new coverage for the orchestrator lifetime, the inherited-run path, and each coordinator behaviour above.MSTest.Sdkproject:Completed)Completed)InProgress)Aborted)