Skip to content

[dotnet test] Coordinate MTP invocation-lifetime handlers across test modules - #57357

Merged
Evangelink merged 9 commits into
dotnet:mainfrom
Evangelink:dev/amauryleve/sdk-invocation-lifetime-hooks
Nov 27, 2026
Merged

Evangelink merged 9 commits into
dotnet:mainfrom
Evangelink:dev/amauryleve/sdk-invocation-lifetime-hooks

Conversation

@Evangelink

@Evangelink Evangelink commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: 11f01d97b99149c1e504ed137b5c611a59b666ab

Dimension Assessment Rationale
Change confidence 8.5/10 ↑ 39/39 composed scenarios pass at this head against final packed TestFx producer code, including genuine Phase 1 binaries, actual control loss, owner termination, shutdown failures and optimistic legacy metadata.
↑ 140/140 related SDK cases pass; all three demonstrated review defects have regression coverage.
↑ 254 runtime DLL hash records verified; no surviving task-owned module processes.
↓ OS Ctrl+C, live-owner policy-exception and custom target/output replacement paths remain unverified.
↓ New-head build 1702285 failed only Monitor Helix Jobs: a macOS arm64 dotnet-new.IntegrationTests hang dump (Helix InfrastructureError, cf. #57241), outside this diff; /azp run was rejected, a REST retry of the failed stage is running, and SDK human approval remains required.

Note

Companion PR for microsoft/testfx#12633. It depends on Microsoft.Testing.Platform protocol 1.5.0, which has not shipped yet. Do not merge until the TestFx side ships and the contract is final.

Summary

This PR adds the dotnet test (Microsoft.Testing.Platform mode) consumer side of invocation-lifetime coordination. The design is described in microsoft/testfx RFC 024 §8.1–8.4, which remains the decision record.

When several test modules register the same invocation-lifetime handlers, the SDK picks one owner module. Setup and cleanup then run once for the whole dotnet test invocation instead of once per module:

  • Owner selection. InvocationLifetimeOwnerSelector uses the MSBuild handler metadata, or picks an owner automatically.
  • Handshake. The owner advertises its enabled handler UIDs in handshake property 23 (a JSON array). The SDK replies with property 24, InvocationLifetimeCoordinationAccepted=true. The owner starts setup only after it receives that explicit acceptance.
  • Sibling launch. Siblings start only after InvocationSetupCompleted (serializer 16). They receive the coordinated handler UIDs and their setup outputs.
  • Cleanup. After every module finishes (ModuleTestsCompleted, serializer 17), the SDK sends RunInvocationCleanup (server control kind 3, with fields AggregateExitCode and IsCanceled). It sends it only to the owner's control connection. The owner then reports InvocationCleanupCompleted (serializer 18).
  • Terminal slot. ModuleTestsCompleted releases the detached owner's parallelism and terminal worker slots while its process stays alive for cleanup.
  • Policies. Test policies (minimum expected tests, zero tests, ignore exit codes) are applied before cleanup runs. Cleanup therefore receives the same aggregate exit code that dotnet test returns.

Compatibility and fallback

In the following cases the SDK uses Phase 1 behavior: each module runs its own handlers, and the SDK prints at most one concise warning before any module starts.

  • Protocol below 1.5, or no named-pipe control capability.
  • Missing handler metadata, a UID mismatch, or a sibling that does not support coordination.
  • Discovery (--list-tests). MTP never runs invocation handlers during discovery, so the SDK prints no warning here.
  • --no-build. The SDK cannot prove that the runnable binaries are current.
  • --no-dependencies or BuildProjectReferences=false. Project-reference outputs might be stale.

If a failure happens after setup might have started, the SDK fails without launching siblings. When no module registers handlers, behavior is unchanged.

If a launched sibling contradicts optimistic support metadata by negotiating an older protocol, the SDK stops it without replying to its handshake: a rejection reply could itself enable unsafe Phase 1 fallback. Subsequent launches stop, already active participants drain, and the owner still receives cleanup. Unexpected final owner failures and shutdown deadlines cannot become successful invocations after successful cleanup.

User-visible changes

  • New localized warnings explain why coordination fell back to Phase 1 (--no-build, --no-dependencies, unsupported sibling).
  • The SDK exports the role and coordinated-UID environment variables to modules only in coordinated runs.
  • Incompatible coordinated siblings and post-cleanup owner shutdown failures now produce localized infrastructure diagnostics and a nonzero result.

Validation

Final head: 11f01d97b99149c1e504ed137b5c611a59b666ab. The redist dotnet.dll SHA256 is CB37B4266E4E0B6F1C71A5CD71F97ED84D2344635F4FC91F0261F5D835C16527, equal to the current product build output. The CLI/outer host is net12.0; composed shipping consumers are net10.0.

Focused tests

The focused tests ran with scripts\RunTests.cs against test\dotnet.Tests at this head. Result: 140/140 passed, no failures/skips.

.\.dotnet\dotnet build src\Cli\dotnet\dotnet.csproj -c Debug -v q -nologo
# Deploy dotnet.dll and localized satellite assemblies to the existing redist SDK.
.\.dotnet\dotnet.exe scripts\RunTests.cs -- --project test\dotnet.Tests\dotnet.Tests.csproj --filter "FullyQualifiedName~InvocationLifetime|FullyQualifiedName~TestApplicationLaunchTests|FullyQualifiedName~TestRunPolicy|FullyQualifiedName~TestApplicationActionQueue"

Retained TRX/binlog: artifacts\log\test-runs\dotnet.Tests\20261127-093619-83208. The regression cases cover cleanup/shutdown timeout, final exit comparison and ignored policies, rejected sibling handshakes and owner cleanup after rejection. An already received cleanup acknowledgment also wins over racing process-exit notification.

At 694c8303653, the earlier focused run that also covered GivenDotnetTestBuildsAndRunsTests passed 280/280. That run included the real-SDK --no-dependencies rows.

Composed end-to-end tests

The composed tests used the redist built from this head and locally packed TestFx 3.0.0-dev. Each case ran dotnet test --solution E2E.slnx plus the listed arguments. The environment set:

  • DOTNET_ROOT
  • DOTNET_CLI_HOME
  • NUGET_PACKAGES
  • DOTNET_ADD_GLOBAL_TOOLS_TO_PATH=0
  • DOTNET_CLI_UI_LANGUAGE=en
  • DOTNET_CLI_TELEMETRY_OPTOUT=1

A pass in Phase 2 means 2 setup and 2 cleanup callbacks, all in the Owner, with cleanup order B then A. A pass in Phase 1 means 6 setup and 6 cleanup callbacks, 2 per module. All 33 existing cases plus 6 new real fault/regression cases passed (39/39).

Case Args / env Exit Callbacks
happy — 0 Phase 2
serial --max-parallel-test-modules 1 0 Phase 2
retry-owner / retry-sibling --retry-failed-tests 2, flaky module 0 / 0 Phase 2
owner-failure / sibling-failure failing test 2 / 2 Phase 2
setup-failure handler B throws in setup 1 Phase 2, siblings not launched
cancel --timeout 5s, SibA blocks 3 Phase 2, cleanup canceled
discovery / no-build-discovery --list-tests 0 / 0 none, no warning
automatic-owner, partial-declaration — 0 Phase 2
uid-mismatch, no-handler-metadata — 0 Phase 1
zero-results zero tests 8 Phase 2, cleanup aggregate 8
no-build / -serial / -retry --no-build 0 Phase 1, 1 warning
no-dependencies / -property --no-dependencies / --property:BuildProjectReferences=false 0 Phase 1, 1 warning
no-dependencies-no-handlers --no-dependencies 0 Phase 1, no warning
mixed-no-build / -serial / -retry old Phase 1 SibA binary, --no-build 0 Phase 1, 1 warning
mixed-build E2E-mixed.slnx (SibA restored from Phase 1 package) 0 Phase 1, 1 warning before any module starts
policies (8 cases) zero / minimum / ignore-exit-codes / setup and cleanup infrastructure failures 8, 9, 0, 0, 0, 1, 1, 1 as expected
successful cleanup, unexpected owner exit harness owner returns 134 after RunAsync and disposal 1 2 Owner setups/cleanups, cleanup aggregate 0
successful cleanup, hung owner shutdown harness owner holds after disposal; coordination timeout 5 seconds 1 2 Owner setups/cleanups, cleanup aggregate 0; bounded termination
optimistic old/new binary metadata --solution E2E-mixed.slnx --max-parallel-test-modules 1 --property:TestingPlatformInvocationLifetimeCoordinationSupported=true 1 2 Owner setups/cleanups; no legacy setup/test callbacks
transparent control proxy named-pipe relay, no injected loss 0 Phase 2
actual owner control-pipe loss hold SibA; sever only cleanup control relay; release SibA explicitly 1 no cleanup during held interval; 2 Owner cleanups after participant drain
actual owner process termination hold SibA; terminate only path-verified task-owned Owner PID 3 participant cancellation/drain; no cleanup, no surviving modules

The three shutdown/legacy regressions complete in 4.03s, 9.26s (including the 5-second deadline), and 3.65s respectively. Control loss terminates 3.41s after injection; owner termination finishes in 2.98s with the established nonzero participant-cancellation verdict 3, not false success.

Injection changes are harness-only: the shipping SDK and TestFx sources are not modified to simulate faults, and no shared console is signaled. Exact command lines, console logs, callback events and result JSON are retained in files\aligned-composed\runs\final11f01-* in this session. Harness entry points are matrix.ps1, mixed.ps1, mixed-build.ps1, policies.ps1, review-regressions.ps1 and faults.ps1, each with -Tag final11f01.

Package provenance

Feed Built from nupkg SHA256 (Platform / Retry) Loaded Platform DLL SHA256
New, version 3.0.0-dev microsoft/testfx@45cfda5 73DF853F5E4849EC1F570DCB15814275D39C325C518CA56C44531907AFF80107 / 2E8D63EDF32ECDAA615B324952577AA339FEF5DBBB9E3E39E03B4F82108911D5 EEC5607BD1767615DD92E02C704C5CF1A61DC8989C9691C1C666830A3AC92390
Old (Phase 1) microsoft/testfx@09c9014 (microsoft/testfx#12602) 7DD54815…F2FA / 7DD749B5…DD78 6B7B023F…DA8C

The final feed and initially fresh isolated caches contain the exact supplied packages. Nuspec repository commits and packed DLL hashes were independently verified. The newer TestFx PR head 61e7cdb4ab97a4bd64fa749c2174325b6b40a9c1 changes only RFC documentation relative to the packed producer code.

The loaded-assembly hashes recorded in each run confirm that the mixed cases loaded the old Platform DLL in SibA and the new one in Owner and SibB. All 254 Platform/Retry runtime hash records were checked against the correct package lineage. The new loaded Retry DLL SHA256 is BA571D3BD37B23AF7DAD97F8DCB6227E9085ADD44650912CF5A7E741A33AF854. No task-owned module process survives these runs.

Comparison at 694c830

The same harness also ran against a pinned layout of 694c8303653313d9da8cb45fa7374c4063721625 (dotnet.dll A5272A73…A978). 24 of the 25 matrix and mixed cases passed.

zero-results failed at that revision: cleanup received aggregate 0 while dotnet test exited with 8. Commit 2c1136d in this PR fixes that.

Remaining gaps

  • The old Phase 1 package was packed locally from 09c90145; it is not a shipped package.
  • Not covered:
    • OS Ctrl+C and live-owner policy-exception paths;
    • custom build or run target overrides;
    • outputs modified between build and launch.
  • Build 1699691 failed on a Windows telemetry assertion matching known issue [Known Build Error] PersistentStorageTelemetryE2ETests.ItPersistsTraceTelemetryToTheStorageDirectory fails: trace telemetry not persisted #57169, outside this change. New-head build 1702285 passed every build job but failed Monitor Helix Jobs on one work item, dotnet-new.IntegrationTests.dll.1 (osx.15.arm64.open): it hit the 48-minute hang-dump timeout in template tests (exit 7, test host 137, Helix failureCategory InfrastructureError). This matches the open macOS arm64 dotnet-new hang issue [AI discovered CI] dotnet-new IntegrationTests hangs on macOS arm64 during AllCommonItemsCreate #57241 by job and hang pattern, and this PR does not touch template or dotnet new code. A /azp run dotnet-sdk-public-ci comment was rejected ("No pipelines are associated with this pull request"), so the failed stage was retried through the Azure DevOps retry API (attempt 2 running). SDK human approval remains required.
  • Main is the only intended target. The TestFx/protocol shipping dependency must be ready before this SDK PR lands; no servicing/backport rollout is enabled here.

Evangelink and others added 8 commits November 25, 2026 14:39
Implements the SDK consumer side of microsoft/testfx RFC 024 sections 8.1-8.4:
owner selection from TestingPlatformInvocationLifetimeOwner metadata, handshake
properties 23/24, serializers 16-18, control kind 3 (RunInvocationCleanup),
owner-first scheduling, sibling gating with setup outputs, and cleanup after
all modules finish. Missing metadata, pre-1.5 owners, rejected handshakes and
ambiguous/HTTP owners fall back to Phase 1 behavior.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…st controller handshake

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
- Gate Phase 2 on TestingPlatformInvocationLifetimeCoordinationSupported=true for
  every MTP module when any module declares lifetime handlers; otherwise fall back
  to Phase 1 with a warning before any owner setup.
- Warn when a coordinated sibling handshakes with protocol older than 1.5.
- Detect owner control-pipe loss; stop launching siblings and drain running ones.
- Hold the owner's ModuleTestsCompleted reply until every sibling completes and
  cleanup is requested, so the owner cannot clean up before siblings drain.
- Release the held reply on completion/dispose without waiting on owner data writes.
- Add regression tests, including cancellation while the reply is held.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Disable invocation-lifetime coordination before enqueueing modules when --no-build leaves runnable binary capabilities unverified. Preserve silent no-handler and discovery paths; cover the fallback with real SDK/MTP execution and stale evaluated metadata.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
--no-dependencies (BuildProjectReferences=false) builds test projects but reuses existing project-reference outputs, so a handler or MTP produced by a referenced project can be stale while evaluation reports current coordination capability. Disable invocation-lifetime coordination before any module launches when any MTP module evaluates BuildProjectReferences=false, mirroring the --no-build fallback. Cover the gate with unit and real SDK/MTP tests.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Compute cancellation and run-level test verdicts before releasing the held owner for cleanup. Preserve lifecycle infrastructure failure state so ignore-exit-code cannot mask setup or cleanup failures. Cover policy completion and aggregate verdicts on the canceled owner's real control pipe.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Run coordinator completion in finally after all readers have drained. Use an infrastructure-failure verdict if a reader or run-policy callback throws, preserve the exception, and cover policy failure propagation.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).
2 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@Evangelink
Evangelink marked this pull request as ready for review November 27, 2026 08:43
@Evangelink
Evangelink requested a review from a team as a code owner November 27, 2026 08:43
Copilot AI balanced review requested due to automatic review settings November 27, 2026 08:43

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.

🟡 Changes recommended

Critical coordination defects can report success despite owner process failures or shutdown timeouts and allow incompatible siblings to run duplicate lifetime handlers.

3 open issues
What changed in this PR

This PR adds invocation-lifetime coordination to dotnet test in Microsoft.Testing.Platform mode, allowing shared setup and cleanup handlers to run once across multiple test modules. It is the SDK companion to microsoft/testfx#12633 and depends on the finalized protocol 1.5 contract.

Changes:

  • Selects an owner module, gates sibling launches on setup, and requests cleanup after applying run policies.
  • Adds lifecycle messages, dedicated owner control-channel handling, compatibility fallbacks, and diagnostics.
  • Adds tests for coordination, cancellation, serialization, launch environments, and stale-build fallbacks.
File Description
test/​dotnet.Tests/​CommandTests/​Test/​TestApplicationProtocolVersionTests.cs Tests protocol 1.4 and 1.5 negotiation.
test/​dotnet.Tests/​CommandTests/​Test/​TestApplicationLaunchTests.cs Tests coordination environments, control routing, and cancellation.
test/​dotnet.Tests/​CommandTests/​Test/​TestApplicationActionQueueTests.cs Tests fallback gates, worker reuse, and policy application.
test/​dotnet.Tests/​CommandTests/​Test/​ServerControlMessageSerializerTests.cs Tests lifecycle message IDs and serialization.
test/​dotnet.Tests/​CommandTests/​Test/​IPCTests.cs Tests control-channel disconnect handling.
test/​dotnet.Tests/​CommandTests/​Test/​InvocationLifetimeOwnerSelectorTests.cs Tests owner selection and participant eligibility.
test/​dotnet.Tests/​CommandTests/​Test/​InvocationLifetimeCoordinatorTests.cs Tests lifecycle transitions, failures, and timeouts.
test/​dotnet.Tests/​CommandTests/​Test/​GivenDotnetTestBuildsAndRunsTests.cs Tests no-build and no-dependencies fallbacks.
src/​Cli/​dotnet/​Commands/​xlf/​CliCommandStrings.zh-Hant.xlf Adds Traditional Chinese localization entries for diagnostics.
src/​Cli/​dotnet/​Commands/​xlf/​CliCommandStrings.zh-Hans.xlf Adds Simplified Chinese localization entries for diagnostics.
src/​Cli/​dotnet/​Commands/​xlf/​CliCommandStrings.tr.xlf Adds Turkish localization entries for diagnostics.
src/​Cli/​dotnet/​Commands/​xlf/​CliCommandStrings.ru.xlf Adds Russian localization entries for diagnostics.
src/​Cli/​dotnet/​Commands/​xlf/​CliCommandStrings.pt-BR.xlf Adds Brazilian Portuguese localization entries for diagnostics.
src/​Cli/​dotnet/​Commands/​xlf/​CliCommandStrings.pl.xlf Adds Polish localization entries for diagnostics.
src/​Cli/​dotnet/​Commands/​xlf/​CliCommandStrings.ko.xlf Adds Korean localization entries for diagnostics.
src/​Cli/​dotnet/​Commands/​xlf/​CliCommandStrings.ja.xlf Adds Japanese localization entries for diagnostics.
src/​Cli/​dotnet/​Commands/​xlf/​CliCommandStrings.it.xlf Adds Italian localization entries for diagnostics.
src/​Cli/​dotnet/​Commands/​xlf/​CliCommandStrings.fr.xlf Adds French localization entries for diagnostics.
src/​Cli/​dotnet/​Commands/​xlf/​CliCommandStrings.es.xlf Adds Spanish localization entries for diagnostics.
src/​Cli/​dotnet/​Commands/​xlf/​CliCommandStrings.de.xlf Adds German localization entries for diagnostics.
src/​Cli/​dotnet/​Commands/​xlf/​CliCommandStrings.cs.xlf Adds Czech localization entries for diagnostics.
src/​Cli/​dotnet/​Commands/​Test/​MTP/​TestApplicationHandler.cs Forwards owner worker-release notifications.
src/​Cli/​dotnet/​Commands/​Test/​MTP/​TestApplicationActionQueue.cs Integrates coordination with scheduling and run policies.
src/​Cli/​dotnet/​Commands/​Test/​MTP/​TestApplication.cs Handles lifecycle handshakes, environments, control messages, and cancellation.
src/​Cli/​dotnet/​Commands/​Test/​MTP/​Terminal/​TestProgressStateAwareTerminal.cs Handles released worker slots safely.
src/​Cli/​dotnet/​Commands/​Test/​MTP/​Terminal/​TerminalTestReporter.cs Releases owner progress slots before process exit.
src/​Cli/​dotnet/​Commands/​Test/​MTP/​SolutionAndProjectUtility.cs Reads coordination metadata from evaluated projects.
src/​Cli/​dotnet/​Commands/​Test/​MTP/​MSBuildHandler.cs Schedules the selected owner group first.
src/​Cli/​dotnet/​Commands/​Test/​MTP/​Models.cs Adds module coordination and build metadata.
src/​Cli/​dotnet/​Commands/​Test/​MTP/​MicrosoftTestingPlatformTestCommand.cs Applies run policies before invocation cleanup.
src/​Cli/​dotnet/​Commands/​Test/​MTP/​IPC/​Serializers/​ServerControlMessageSerializer.cs Serializes cleanup result and cancellation fields.
src/​Cli/​dotnet/​Commands/​Test/​MTP/​IPC/​Serializers/​RegisterSerializers.cs Registers lifecycle message serializers.
src/​Cli/​dotnet/​Commands/​Test/​MTP/​IPC/​Serializers/​InvocationLifetimeSerializers.cs Implements lifecycle message serialization.
src/​Cli/​dotnet/​Commands/​Test/​MTP/​IPC/​ObjectFieldIds.cs Defines lifecycle serializer and field IDs.
src/​Cli/​dotnet/​Commands/​Test/​MTP/​IPC/​NamedPipeServer.cs Detects control-client disconnection during pending responses.
src/​Cli/​dotnet/​Commands/​Test/​MTP/​IPC/​Models/​ServerControlMessage.cs Adds aggregate result and cancellation data.
src/​Cli/​dotnet/​Commands/​Test/​MTP/​IPC/​Models/​InvocationLifetimeMessages.cs Defines lifecycle messages and secret-conscious output formatting.
src/​Cli/​dotnet/​Commands/​Test/​MTP/​InvocationLifetimeOwnerSelector.cs Selects an eligible coordination owner.
src/​Cli/​dotnet/​Commands/​Test/​MTP/​InvocationLifetimeCoordinator.cs Implements setup, sibling release, cleanup, and failure coordination.
src/​Cli/​dotnet/​Commands/​Test/​CliConstants.cs Defines protocol capabilities, environment variables, and metadata names.
src/​Cli/​dotnet/​Commands/​CliCommandStrings.resx Adds coordination warnings and failure messages.

Review effort: Balanced

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@Evangelink

Copy link
Copy Markdown
Member Author

/azp run dotnet-sdk-public-ci

Build 1702285 failed only in the macOS arm64 dotnet-new.IntegrationTests.dll.1 work item. All build jobs passed. The test host reached its 48-minute hang threshold with CanInstallRemoteNuGetPackageWithVersionWildcard, FeaturesSupport and CannotInstantiateTemplate_WithoutRequiredParams still active; the host was killed with exit 137 and the work item returned 7. The 159 recovered results contain no reported failed assertions.

A similar multi-test macOS arm64 template-host hang is independently recorded on main in #57241 (build 1690864). This is evidence of a pre-existing failure pattern, not proof of an identical root cause. Build Analysis did not classify the current failure. No change in this PR touches the dotnet-new test paths, and no PR-related cause has been demonstrated. Requesting one fresh run at unchanged head 11f01d9; keeping required checks and review protections intact.

Current console: https://helix.dot.net/api/2019-06-17/jobs/78927039-c50d-4af4-904c-1d61f485d48a/workitems/dotnet-new.IntegrationTests.dll.1/console

@azure-pipelines

Copy link
Copy Markdown
No pipelines are associated with this pull request.

@Evangelink
Evangelink enabled auto-merge (squash) November 27, 2026 11:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants