Skip to content

Publish one Azure DevOps test run per build when retrying failed tests - #10375

Merged
Amaury Levé (Evangelink) merged 7 commits into
mainfrom
dev/amauryleve/effective-invention
Aug 3, 2026
Merged

Amaury Levé (Evangelink) merged 7 commits into
mainfrom
dev/amauryleve/effective-invention

Conversation

@Evangelink

@Evangelink Amaury Levé (Evangelink) commented Aug 1, 2026 •

Copy link
Copy Markdown
Member

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-results combined with --retry-failed-tests created and completed one Azure DevOps test run per attempt. 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, and the recovered test stayed Failed forever 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.

  • BeforeRunAsync acquires 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 inherited TESTINGPLATFORM_AZUREDEVOPS_TESTRUNID variable (scoped as <buildId>:<runId> so a stale value from another build cannot redirect results).
  • Attempts read that variable, join the run, and never create or complete it.
  • 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:

  • Orchestrator lifetimes were only cleaned up on success. AfterRunAsync and disposal now also run when the orchestration is canceled or throws. Without this a run created in BeforeRunAsync was left InProgress and never appeared in the build's Tests tab. This is deterministic for --retry-failed-tests with --server or hot reload, which throw before running anything.
  • The owner could close a run while a peer was still publishing. It gave up after a fixed 30 second grace period. Now that builds are consolidated, that would make Azure DevOps reject everything the remaining projects sent. Participants whose process is provably alive are now waited for, bounded by a hard cap so a leaked process cannot stall a build.
  • A peer could take over ownership of a live run. An orchestrator holds its lease for the whole orchestration without renewing it, so past the expiry a peer would seize ownership, create a duplicate run, and have it orphaned. Process liveness now beats wall-clock expiry, matching how participants were already treated.
  • A created run could be lost if writing the local run-id file failed, or if a log provider threw while reporting that failure. The run exists remotely at that point and only this process can close it, so nothing is allowed to escape there any more.
  • Diagnostics could strand the very resources they were reporting on. The aggregate logger propagates provider exceptions, so a broken log provider could escape a cleanup path and skip the work that releases the resource. Cleanup logging is now best-effort in both the orchestrator host and the coordinator.

Worth a careful look

  • TestHostOchestratorHost.RunAsync is shared platform code. It now guarantees AfterRunAsync runs on every exit path, which is a new expectation on implementations of a public [TPEXP] interface. I documented it on ITestHostOrchestratorApplicationLifetime.AfterRunAsync: implementations must tolerate being called when their BeforeRunAsync did not run or complete, should not throw, and must not assume the token is still usable.
  • The coordinator changes affect the plain single-process publisher path too, not just retry.

Not in scope

A test rescued by a retry still contributes one result per attempt inside the single run (Failed then Passed). Collapsing those into one result carrying the final outcome needs PATCH .../runs/{id}/results plus 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:

  • Process-identity (for example start time) alongside the pid in lease files. The coordination has always relied on bare pid liveness, so a recycled pid can misidentify an owner; this PR extends that existing assumption rather than introducing it, and fixing it properly means changing the lease file format.
  • Peers cannot join when the run-id file write fails; they wait, then report that live publishing could not start.
  • An orphaned attempt process in a narrow RetryTestHostRunner cancellation race.
  • Cross-machine and sharded builds: the coordination relies on process liveness, which is machine-local.

Validation

  • 909 tests in Microsoft.Testing.Extensions.UnitTests and 1984 in Microsoft.Testing.Platform.UnitTests, including new coverage for the orchestrator lifetime, the inherited-run path, and each coordinator behaviour above.
  • Every behavioural fix here was mutation tested: reverting it individually makes a specific test fail.
  • End to end against a stub Azure DevOps endpoint with a real packed MSTest.Sdk project:
scenario before after
retry, flaky test recovers 2 runs created / 2 completed 1 created / 1 completed (Completed)
retries exhausted, still failing one run per attempt 1 created / 1 completed (Completed)
orchestrator faults after run creation 1 created / 0 completed (InProgress) 1 created / 1 completed (Aborted)
no retry 1 / 1 1 / 1, unchanged

`--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
Copilot AI review requested due to automatic review settings August 1, 2026 07:36

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 createRunAsync has returned, the remote run already exists, but cancellation during this file write is excluded from the recovery catch. AcquireRunAsync then deletes the leases and the caller never receives/stores the coordinated run, so AfterRunAsync cannot complete it and it remains InProgress. 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

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 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 · ◷

@Evangelink Amaury Levé (Evangelink) added the state/needs-review Awaiting review from the team. label Aug 2, 2026
@Evangelink
Amaury Levé (Evangelink) enabled auto-merge (squash) August 2, 2026 22:05
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
Copilot AI review requested due to automatic review settings August 2, 2026 22:31

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review details

Suppressed comments (2)

src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsRunIdCoordinator.cs:486

  • Once createRunAsync has returned, cancellation during the cancellable file write must not escape: the outer catch deletes the owner files, AcquireRunAsync never returns the run handle, and AfterRunAsync therefore 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 throws AzureDevOpsLivePublishingMissingRunIdFile; 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

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 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
Copilot AI review requested due to automatic review settings August 2, 2026 22:48
@Evangelink

Copy link
Copy Markdown
Member Author

Picked up the two suppressed comments on AzureDevOpsRunIdCoordinator from the latest review.

Once createRunAsync has returned, cancellation during the cancellable file write must not escape [...] The warning also needs guarding because logger providers can throw and cause the same ownership loss.

Fixed in 20d11e9 - this was a real gap in my own earlier fix. TryWriteRunIdFileAsync excluded cancellation from its catch, so a cancel landing in the window right after the run was created unwound into AcquireRunAsync's cleanup, which deletes the leases and never returns the handle, leaving the run InProgress with nobody able to close it. The logger point is the same class of bug I had just fixed in the orchestrator host, so warnings there and in TryDeleteFile now go through a non-throwing helper. Covered by RunIdCoordinator_AcquireRunAsync_RunIdFileWriteFailsUnderCancellation_StillReturnsTheCreatedRun, which fails if the cancellation filter is put back.

If this write fails, the owner still keeps its lease but publishes no run-id file. A peer then waits [...] and eventually throws AzureDevOpsLivePublishingMissingRunIdFile; live publishing is disabled for that peer rather than falling back to its own run as the new recovery-path comment claims.

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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review details

  • Files reviewed: 27/27 changed files
  • Comments generated: 1
  • Review effort level: Balanced

Copilot AI review requested due to automatic review settings August 2, 2026 22:53

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 remains InProgress. 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, WaitForRunIdFileAsync returns 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 CoordinationFinalizeMaxWaitTime and 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

@github-actions

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
Copilot AI review requested due to automatic review settings August 2, 2026 23:19

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review details

  • Files reviewed: 27/27 changed files
  • Comments generated: 1
  • Review effort level: Balanced

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
Copilot AI review requested due to automatic review settings August 2, 2026 23:30

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review details

Suppressed comments (1)

src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsRunIdCoordinator.cs:622

  • C# records expose a Deconstruct method; “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

@github-actions

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
Copilot AI review requested due to automatic review settings August 2, 2026 23:47
@Evangelink

Copy link
Copy Markdown
Member Author

Worked through the four suppressed comments from the review at 22:59Z.

Calling the logger directly here can prevent the run from being finalized [...] Use the existing best-effort logging helper

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.

The hard-cap behavior is not exercised by the new coordinator tests [...] Removing this deadline would therefore leave all tests passing

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.

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

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".

A live PID does not prove that the lease owner is still alive because operating systems reuse process IDs

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 (CleanupStaleParticipants predates this PR and relies on it); this change extends that existing assumption to owner leases rather than introducing it. Doing it properly means persisting a process-identity value in the lease file, which changes the file format and needs to stay readable across versions, so it deserves its own change rather than being folded in here unreviewed.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review details

  • Files reviewed: 27/27 changed files
  • Comments generated: 0 new
  • Review effort level: Balanced

@github-actions

github-actions Bot commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

🧪 Test quality grade — PR #10375

GradeTestMutationNotesHow to improve
A (90–100) new TestHostOrchestratorHostTests.
RunAsync_
LoggerThrows_
StillCleansUpEveryLifetime
4/4 killed Full call-sequence assertions on both lifetimes; throwing logger cannot skip disposal. —
A (90–100) new TestHostOrchestratorHostTests.
RunAsync_
LifetimeBeforeRunThrows_
StillCallsAfterRunOnEveryLifetime
4/4 killed Both faulting and never-ran lifetimes get AfterRunAsync with GenericFailure exit code asserted. —
A (90–100) new TestHostOrchestratorHostTests.
RunAsync_
OrchestratorCanceled_
LifetimeAfterRunFailureIsSwallowed
4/4 killed exitCode, BeforeRunCount, AfterRunCount, LastExitCode, DisposeCount all pinned for canceled path. —
A (90–100) new TestHostOrchestratorHostTests.
RunAsync_
OrchestratorCanceled_
StillCallsAfterRunAndDisposes
4/4 killed Full call sequence including BeforeRunCount and TestSessionAborted exit code asserted. —
A (90–100) new TestHostOrchestratorHostTests.
RunAsync_
OrchestratorSucceeds_
CallsAfterRunWithTheOrchestratorExitCode
4/4 killed exitCode, all lifecycle counts, and LastExitCode=7 asserted; no mutation survives. —
A (90–100) new TestHostOrchestratorHostTests.
RunAsync_
OrchestratorSucceeds_
LifetimeIsNotInvokedTwice
4/4 killed BeforeRunCount, AfterRunCount, LastExitCode=0, DisposeCount all asserted; full sequence pinned. —
A (90–100) new TestHostOrchestratorHostTests.
RunAsync_
OrchestratorThrows_
CallsAfterRunAndDisposesThenRethrows
4/4 killed Exception message, full call sequence, and GenericFailure exit code asserted on fault path. —
A (90–100) new TestHostOrchestratorHostTests.
RunAsync_
OrchestratorThrows_
OneLifetimeFailingDoesNotBlockTheNext
4/4 killed Both failing and healthy lifetimes fully asserted; cleanup chain isolation verified. —
A (90–100) new AzureDevOpsLivePublishingTests.
OnTestSessionFinishingAsync_
AttachmentFailsAndLogProviderThrows_
CountsEveryAttachment
3/3 killed Upload attempt count (2) and warning message with count=2 both asserted. —
A (90–100) new AzureDevOpsLivePublishingTests.
OnTestSessionFinishingAsync_
AttachmentUploadFailure_
WarnsWithCountOnOutputDevice
3/3 killed Output device warning with formatted count=1 is verified; message mutation would be caught. —
A (90–100) new AzureDevOpsLivePublishingTests.
OnTestSessionFinishingAsync_
FinalizeCanceled_
DoesNotFailTheRun
3/3 killed Both warning message strings asserted; cancellation-as-failure path well covered. —
A (90–100) new AzureDevOpsLivePublishingTests.
OnTestSessionFinishingAsync_
PublishFailsAndLogProviderThrows_
DoesNotFailTheRun
3/3 killed Console summary reports dropped result count despite broken log provider. —
A (90–100) new AzureDevOpsLivePublishingTests.
OnTestSessionStartingAsync_
LogProviderThrows_
DoesNotFailTheRun
3/3 killed Output line count and SYSTEM_ACCESSTOKEN presence both pinned. —
A (90–100) new AzureDevOpsLivePublishingTests.
OrchestratorLifetime_
AfterRun_
CalledTwice_
FinalizesTheRunOnlyOnce
3/3 killed HasCount=1, RunId=4247, State=Completed all pinned; idempotency fully covered. —
A (90–100) new AzureDevOpsLivePublishingTests.
OrchestratorLifetime_
AfterRun_
CanceledToken_
StillClosesTheRunAsAborted
3/3 killed HasCount=1, RunId=4246, State=Aborted asserted; cancellation-path closure fully pinned. —
A (90–100) new AzureDevOpsLivePublishingTests.
OrchestratorLifetime_
AfterRun_
CompletesTheRunItCreated
3/3 killed UpdateTestRunStateCalls count, RunId=4243, and State=Completed all verified. —
A (90–100) new AzureDevOpsLivePublishingTests.
OrchestratorLifetime_
AfterRun_
NonTestResultExitCodeAbortsTheRun
3/3 killed HasCount=1, RunId=4244, State=Aborted asserted; abort-vs-complete decision fully pinned. —
A (90–100) new AzureDevOpsLivePublishingTests.
OrchestratorLifetime_
AfterRun_
StopsHandingOutTheRunIdSoLaterProcessesDoNotPublishIntoAClosedRun
2/2 killed TryGetInheritedTestRunId returns null after AfterRunAsync; handoff-withdrawal pinned. —
A (90–100) new AzureDevOpsLivePublishingTests.
OrchestratorLifetime_
AfterRun_
WithoutBeforeRun_
IsANoOp
2/2 killed UpdateTestRunStateCalls.IsEmpty confirms no-op; only meaningful assertion for this path. —
A (90–100) new AzureDevOpsLivePublishingTests.
OrchestratorLifetime_
BeforeRun_
CreateRunFails_
DoesNotPublishARunIdAndDoesNotThrow
4/4 killed RunId null, env null, no update calls, and warning in both output device and logger verified. —
A (90–100) new AzureDevOpsLivePublishingTests.
OrchestratorLifetime_
BeforeRun_
CreatesRunOnceAndPublishesItToOrchestratedProcesses
3/3 killed CreateTestRunCalls.HasCount=1, RunId=4242, and inherited env value all asserted. —
A (90–100) new AzureDevOpsLivePublishingTests.
OrchestratorLifetime_
BeforeRun_
RunIdAlreadyInEnvironment_
LeavesTheAncestorRunAlone
2/2 killed Both create and update call lists are empty; ancestor-ownership guard fully pinned. —
A (90–100) new AzureDevOpsLivePublishingTests.
OrchestratorLifetime_
HandoffFailsAfterRunCreated_
StillClosesTheRun
4/4 killed HasCount=1, RunId=4248, State=Completed, and handoff-failure log message all pinned. —
A (90–100) new AzureDevOpsLivePublishingTests.
OrchestratorLifetime_
PeerOrchestratorsSharingAResultsDirectory_
PublishIntoASingleRun
5/5 killed Single run created, peer joined, participant counts, and final state all verified step-by-step. —
A (90–100) new AzureDevOpsLivePublishingTests.
Publisher_
RunIdInEnvironment_
DoesNotCompleteTheRunSoLaterAttemptsCanStillPublish
2/2 killed UpdateTestRunStateCalls.IsEmpty confirms the inherited-run path skips finalization. —
A (90–100) new AzureDevOpsLivePublishingTests.
Publisher_
RunIdInEnvironment_
JoinsTheRunInsteadOfCreatingItsOwn
2/2 killed RunId=909 and no create calls; inherited-run join fully pinned. —
A (90–100) new AzureDevOpsLivePublishingTests.
Publisher_
RunIdInEnvironment_
StillPublishesResultsIntoTheInheritedRun
3/3 killed Publish called once with RunId=911; result is routed to the inherited run, not a new one. —
A (90–100) new AzureDevOpsLivePublishingTests.
Publisher_
RunIdInEnvironment_
WritesNoCoordinationFilesBecauseTheAncestorOwnsTheRun
2/2 killed No coordination files in directory; inherited-run path skips file coordination entirely. —
A (90–100) new AzureDevOpsLivePublishingTests.
Publisher_
UnusableRunIdInEnvironment_
FallsBackToCreatingItsOwnRun
3/3 killed 9 DataRow inputs (including cross-build "999:42") all assert RunId=913 and HasCount=1. —
A (90–100) mod AzureDevOpsLivePublishingTests.
RunIdCoordinator_
FinalizeRunAsync_
TimesOutAndLogsWarning
4/4 killed finalizeCalls=1, "timed out" log, and both files deleted; grace-period expiry fully verified. —
A (90–100) new AzureDevOpsLivePublishingTests.
RunIdCoordinator_
AcquireRunAsync_
JoinerGivesUpWhenOwnerLeaseExpires
3/3 killed RunId=123 and IsOwner=true confirm takeover from an expired, dead-process owner. —
A (90–100) new AzureDevOpsLivePublishingTests.
RunIdCoordinator_
AcquireRunAsync_
JoinerKeepsWaitingWhileOwnerLeaseValid
3/3 killed RunId=77, IsOwner=false, and delayCalls>2 confirm owner-lease-aware extended wait. —
A (90–100) new AzureDevOpsLivePublishingTests.
RunIdCoordinator_
AcquireRunAsync_
RunIdFileWriteFailsUnderCancellation_
StillReturnsTheCreatedRun
3/3 killed RunId=970, IsOwner=true; run ownership is preserved even when write + logger + token all fail. —
A (90–100) new AzureDevOpsLivePublishingTests.
RunIdCoordinator_
AcquireRunAsync_
TransientUnreadableOwnerPreservesItForRetry
3/3 killed Exception type, message, and owner file still present all asserted; partial-write guard verified. —
A (90–100) new AzureDevOpsLivePublishingTests.
RunIdCoordinator_
FinalizeRunAsync_
DoesNotCloseTheRunWhileAPeerProcessIsStillAlive
4/4 killed peerStillRegistered=false, finalizeCalls=1, delayCount≥5 pin the full wait-then-close contract. —
A (90–100) new AzureDevOpsLivePublishingTests.
RunIdCoordinator_
FinalizeRunAsync_
LivePeerThatNeverLeaves_
StillFinalizesAtTheHardCap
4/4 killed finalizeCalls=1, peer file still exists, and delay count bounded both above and below. —
A (90–100) new AzureDevOpsLivePublishingTests.
RunIdCoordinator_
FinalizeRunAsync_
OwnParticipantLeaseSurvivingDeletion_
DoesNotWaitOnItself
4/4 killed Own lease still on disk, finalizeCalls=1, delayCount=0 confirms no self-wait regression. —
A (90–100) new AzureDevOpsLivePublishingTests.
RunIdCoordinator_
FinalizeRunAsync_
TimeoutWarningThrows_
StillClosesTheRun
2/2 killed finalizeCalls=1 confirms the run is closed even when the timeout-warning log provider throws. —
A (90–100) new AzureDevOpsLivePublishingTests.
RunIdCoordinator_
OwnerLeaseExpiredButOwnerProcessAlive_
PeerJoinsInsteadOfCreatingASecondRun
3/3 killed IsOwner=false and RunId=900 confirm a live owner is not displaced by wall-clock expiry. —
A (90–100) new AzureDevOpsLivePublishingTests.
RunIdCoordinator_
OwnerLeaseWithoutBuildContext_
CanStillBeTakenOverEvenWhenThatPidIsAlive
3/3 killed IsOwner=true with assertion message, RunId=980; sentinel-buildId lease is replaceable. —

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 /grade-tests.

🤖 Automated content by GitHub Copilot. Generated by the Grade Tests on PR (on open / sync) workflow. · sonnet46 295.8 AIC · ⌖ 6.11 AIC · ⊞ 11.8K · [◷]( · ◷)

@Evangelink
Amaury Levé (Evangelink) merged commit e7052f8 into main Aug 3, 2026
31 checks passed
@Evangelink
Amaury Levé (Evangelink) deleted the dev/amauryleve/effective-invention branch August 3, 2026 08:21
Amaury Levé (Evangelink) added a commit that referenced this pull request Aug 4, 2026
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

state/needs-review Awaiting review from the team.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

--publish-azdo-test-results creates one Azure DevOps test run per --retry-failed-tests attempt instead of one run per build

3 participants