Add server-initiated session cancellation to the dotnet test IPC protocol (#8691) - #9549

Merged
Amaury Levé (Evangelink) merged 3 commits into
mainfrom
dev/amauryleve/server-session-cancellation-design
Jul 2, 2026
Merged

Add server-initiated session cancellation to the dotnet test IPC protocol (#8691)#9549
Amaury Levé (Evangelink) merged 3 commits into
mainfrom
dev/amauryleve/server-session-cancellation-design

Conversation

@Evangelink

Copy link
Copy Markdown
Member

Closes#8691.

Implements the RFC's recommended Option B — a reverse "server control" pipe — so dotnet test-level features (global --maximum-failed-tests, --timeout, graceful Ctrl+C drain) can ask a Microsoft.Testing.Platform test app to stop cooperatively instead of only letting it run to completion or Process.Kill-ing it.

How it works

sequenceDiagram
participant SDK as dotnet test (SDK)
participant App as MTP test app
App->>SDK: Handshake (advertises 1.4.0)
SDK-->>App: Handshake reply (ServerControlPipeName=<pipe>)
App->>SDK: WaitForServerControlRequest (parks on control pipe)
Note over SDK: global budget reached
SDK-->>App: ServerControlMessage(CancelSession)
App->>App: IGracefulStopTestExecutionCapability.StopTestExecutionAsync()
App->>SDK: final results + TestSessionEnd (data pipe)
App-->>SDK: exit
Loading
  • The SDK advertises a control-pipe name in its handshake reply. Its presence is the capability signal (no separate boolean), gated per-connection — an older SDK never advertises it, so the feature stays off.
  • The test host opens a second NamedPipeClient and parks a long-poll WaitForServerControlRequest; the SDK completes it with a ServerControlMessage. This is a true server push, so it works even when the app is silent/hung — the crux for --timeout.
  • On CancelSession the host stops gracefully via IGracefulStopTestExecutionCapability (the same path --maximum-failed-tests uses), so trx/logs/artifacts for anything that completed are still emitted. It falls back to hard token cancellation only when the running framework has no graceful-stop capability.
  • The connect + long-poll run entirely on a background task, so test start is never blocked on the auxiliary channel. A dropped control pipe is treated as "host went away → cancel"; the new NamedPipeClient.exitProcessOnConnectionLoss flag keeps that from killing the host (the shared data-pipe behavior is unchanged). On exit the parked read is force-aborted (dispose-before-await), so shutdown can't hang — including on .NET Framework where cancelling an in-flight named-pipe read is unreliable.

Protocol changes (mirror in dotnet/sdk in lockstep)

  • ProtocolConstants bumped to add 1.4.0.
  • Handshake property ServerControlPipeName = 12.
  • Serializers WaitForServerControlRequest = 13, ServerControlMessage = 14 (Kind byte, CancelSession = 1). Note the RFC's "id 11 is next free" was stale — 11/12 are already AzureDevOpsLogMessage/DisplayMessage.
  • The ServerControlPipeName doc spells out the SDK-side contract: accept one control connection per connecting process, and keep the pipe open until the data session ends (an early drop is read as cancel).

Notes vs. the RFC

  • The version-negotiation "latent bug" is already effectively fixed in the current tree (the SDK returns a single negotiated version and the host tracks per-connection capability), so it's out of scope here.
  • The reaction is a graceful stop, not CancellationTokenSource.Cancel() as the RFC sketched, precisely so reporting survives.

Tests

  • Contract + round-trip unit tests for the two new serializers, plus id/property/version stability (ProtocolTests, DotnetTestProtocolContractTests).
  • End-to-end acceptance tests (DotnetTestPipeServerCancellationTests): a graceful server-initiated cancel still reports a result + TestSessionEnd and exits cleanly; an SDK that doesn't advertise the pipe is a no-op.
  • Extended the FakeDotnetTestSdk harness to stand up the control pipe and push CancelSession.

All 13 DotnetTestPipe acceptance tests, the protocol unit tests, and the contract tests pass; the strict -pack build is green.

An expert review pass was run and its findings addressed (background connect, force-abort-on-exit, protocol-contract docs) in the second commit.

⚠️ The protocol files are duplicated in dotnet/sdk — a matching PR must land there in coordination.

amauryleveand others added 2 commits July 1, 2026 16:49
…ocol (#8691)
Implements Option B from the RFC: a reverse "server control" pipe. The SDK
advertises a control pipe name in its handshake reply; the test host connects
back and parks a long-poll WaitForServerControlRequest that the SDK completes
with a ServerControlMessage (CancelSession). On cancel the host stops
gracefully via IGracefulStopTestExecutionCapability so trx/artifacts survive,
falling back to hard cancellation when no graceful capability exists. A dropped
control pipe is treated as "host gone => cancel".
- Protocol 1.4.0; handshake property ServerControlPipeName=12; serializer ids
WaitForServerControlRequest=13, ServerControlMessage=14.
- NamedPipeClient gains exitProcessOnConnectionLoss so the control channel does
not kill the host on disconnect.
- Contract + round-trip unit tests and end-to-end acceptance tests (graceful
cancel still reports; no-advertise is a no-op).
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
… the parked read on exit
- StartServerControlChannelAsync no longer blocks test start on the control-pipe
connect; connect + long-poll now run entirely on the background listener task
(fixes up-to-30s startup stall and de-risks multi-process contention).
- OnExitAsync now cancels then disposes the control pipe client before a bounded
wait, so the parked long-poll read is force-aborted even on .NET Framework where
cancelling an in-flight named-pipe read is unreliable (fixes potential exit hang).
- Documented the SDK-side contract for ServerControlPipeName (one control
connection per connecting process; SDK must keep the pipe open for the whole
data session, since an early drop is treated as cancel).
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings July 1, 2026 15:14

CopilotAI 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

Adds server-initiated session cancellation support to the dotnet test IPC protocol (MTP “server mode”) by introducing a reverse “server control” named pipe that the SDK can use to push a cooperative CancelSession signal to the test host, allowing graceful shutdown with reporting preserved.

Changes:

  • Extend the dotnet-test pipe protocol with v1.4.0, a new handshake property (ServerControlPipeName), and two new message types (WaitForServerControlRequest, ServerControlMessage).
  • Implement host-side listening/handling for server control messages (including a graceful-stop path via IGracefulStopTestExecutionCapability, with a cancellation fallback).
  • Add protocol/unit/contract coverage plus an end-to-end acceptance test and enhance the fake SDK harness to drive the control channel.
Show a summary per file
FileDescription
test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.csAdds round-trip tests for new serializers, updates stable IDs/handshake property list, and bumps supported protocol versions to include 1.4.0.
test/UnitTests/Microsoft.Testing.Platform.DotnetTestProtocolContract.UnitTests/DotnetTestProtocolContractTests.csMirrors the protocol contract stability assertions for new IDs/properties and version list.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/FakeDotnetTestSdkResult.csTracks control-pipe observations (connected + cancel sent) for acceptance assertions.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/FakeDotnetTestSdk.csAdds optional reverse control pipe server and drives CancelSession message in the fake SDK harness.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/DotnetTestPipeServerCancellationTests.csNew end-to-end acceptance tests validating graceful server-initiated cancellation behavior and the no-advertisement case.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/DotnetTestPipeProtocol.csExtends black-box protocol contract helper with new serializer IDs, handshake property ID, and server-control message encoding.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/DotnetTestPipeBaselineTests.csUpdates baseline advertised protocol versions to include 1.4.0.
src/Platform/Microsoft.Testing.Platform/ServerMode/IPushOnlyProtocol.csAdds control-channel capability flag and a start method to begin listening for server control signals.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/WaitForServerControlRequestSerializer.csNew serializer for an empty long-poll request used on the control pipe.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/ServerControlMessageSerializer.csNew serializer for a server-pushed control message (currently Kind only).
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/ObjectFieldIds.csDefines stable serializer IDs/field IDs for the new control messages.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/WaitForServerControlRequest.csNew model representing the parked long-poll request.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/ServerControlMessage.csNew model representing the server’s control reply (e.g., CancelSession).
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Constants.csAdds handshake property constant for ServerControlPipeName, defines ServerControlKinds, and bumps supported versions to include 1.4.0.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.csImplements control-pipe negotiation, background connect/listen loop, and one-time cancel dispatch + teardown behavior.
src/Platform/Microsoft.Testing.Platform/IPC/Serializers/RegisterSerializers.csRegisters the two new serializers on named-pipe endpoints.
src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeClient.csAdds exitProcessOnConnectionLoss flag to allow auxiliary channels to surface disconnects without terminating the process.
src/Platform/Microsoft.Testing.Platform/Hosts/TestHostOchestratorHost.csWires control-channel cancel to application token cancellation for orchestrator host scenario.
src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.csStarts server-control listener after a successful handshake and maps cancel to graceful-stop capability (or token cancellation fallback).

Review details

  • Files reviewed: 19/19 changed files
  • Comments generated: 1
  • Review effort level: Low

@Evangelink
Amaury Levé (Evangelink) marked this pull request as ready for review July 2, 2026 17:56
…l-safe check
- FakeDotnetTestSdk: declare the reverse control-pipe server stream with 'await
using' so its OS handle is released on every exit path (incl. exceptions),
removing the manual DisposeAsync block.
- DotnetTestConnection: use 'is true' instead of '== true' for the nullable-bool
handshake property check.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@Evangelink
Amaury Levé (Evangelink) enabled auto-merge (squash) July 2, 2026 18:21
@EvangelinkAmaury Levé (Evangelink) added the state/needs-review Awaiting review from the team. label Jul 2, 2026
@Evangelink
Amaury Levé (Evangelink) merged commit 7e8ab49 into mainJul 2, 2026
58 of 59 checks passed
@Evangelink
Amaury Levé (Evangelink) deleted the dev/amauryleve/server-session-cancellation-design branch July 2, 2026 18:57
github-actionsBot added a commit that referenced this pull request Jul 4, 2026
- Add --report-azdo-groups/--report-azdo-annotations toggles (#9542) to Platform changelog
- Add re-print errored assemblies in end-of-run recap (#9545) to Platform changelog
- Add server-initiated session cancellation (#9549) to Platform changelog
- Add fix for CloneWithUpdatedSource mutating this (#9581) to MSTest changelog
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Amaury Levé (Evangelink) added a commit that referenced this pull request Jul 5, 2026
…9613)
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

state/needs-reviewAwaiting review from the team.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[RFC] Server-initiated session cancellation in the dotnet test IPC protocol

3 participants

@Evangelink@0101
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Add server-initiated session cancellation to the dotnet test IPC protocol (#8691) - #9549

Merged
Amaury Levé (Evangelink) merged 3 commits into
mainfrom
dev/amauryleve/server-session-cancellation-design
Jul 2, 2026
Merged

Add server-initiated session cancellation to the dotnet test IPC protocol (#8691)#9549
Amaury Levé (Evangelink) merged 3 commits into
mainfrom
dev/amauryleve/server-session-cancellation-design

Conversation

@Evangelink

Copy link
Copy Markdown
Member

Closes#8691.

Implements the RFC's recommended Option B — a reverse "server control" pipe — so dotnet test-level features (global --maximum-failed-tests, --timeout, graceful Ctrl+C drain) can ask a Microsoft.Testing.Platform test app to stop cooperatively instead of only letting it run to completion or Process.Kill-ing it.

How it works

sequenceDiagram
participant SDK as dotnet test (SDK)
participant App as MTP test app
App->>SDK: Handshake (advertises 1.4.0)
SDK-->>App: Handshake reply (ServerControlPipeName=<pipe>)
App->>SDK: WaitForServerControlRequest (parks on control pipe)
Note over SDK: global budget reached
SDK-->>App: ServerControlMessage(CancelSession)
App->>App: IGracefulStopTestExecutionCapability.StopTestExecutionAsync()
App->>SDK: final results + TestSessionEnd (data pipe)
App-->>SDK: exit
Loading
  • The SDK advertises a control-pipe name in its handshake reply. Its presence is the capability signal (no separate boolean), gated per-connection — an older SDK never advertises it, so the feature stays off.
  • The test host opens a second NamedPipeClient and parks a long-poll WaitForServerControlRequest; the SDK completes it with a ServerControlMessage. This is a true server push, so it works even when the app is silent/hung — the crux for --timeout.
  • On CancelSession the host stops gracefully via IGracefulStopTestExecutionCapability (the same path --maximum-failed-tests uses), so trx/logs/artifacts for anything that completed are still emitted. It falls back to hard token cancellation only when the running framework has no graceful-stop capability.
  • The connect + long-poll run entirely on a background task, so test start is never blocked on the auxiliary channel. A dropped control pipe is treated as "host went away → cancel"; the new NamedPipeClient.exitProcessOnConnectionLoss flag keeps that from killing the host (the shared data-pipe behavior is unchanged). On exit the parked read is force-aborted (dispose-before-await), so shutdown can't hang — including on .NET Framework where cancelling an in-flight named-pipe read is unreliable.

Protocol changes (mirror in dotnet/sdk in lockstep)

  • ProtocolConstants bumped to add 1.4.0.
  • Handshake property ServerControlPipeName = 12.
  • Serializers WaitForServerControlRequest = 13, ServerControlMessage = 14 (Kind byte, CancelSession = 1). Note the RFC's "id 11 is next free" was stale — 11/12 are already AzureDevOpsLogMessage/DisplayMessage.
  • The ServerControlPipeName doc spells out the SDK-side contract: accept one control connection per connecting process, and keep the pipe open until the data session ends (an early drop is read as cancel).

Notes vs. the RFC

  • The version-negotiation "latent bug" is already effectively fixed in the current tree (the SDK returns a single negotiated version and the host tracks per-connection capability), so it's out of scope here.
  • The reaction is a graceful stop, not CancellationTokenSource.Cancel() as the RFC sketched, precisely so reporting survives.

Tests

  • Contract + round-trip unit tests for the two new serializers, plus id/property/version stability (ProtocolTests, DotnetTestProtocolContractTests).
  • End-to-end acceptance tests (DotnetTestPipeServerCancellationTests): a graceful server-initiated cancel still reports a result + TestSessionEnd and exits cleanly; an SDK that doesn't advertise the pipe is a no-op.
  • Extended the FakeDotnetTestSdk harness to stand up the control pipe and push CancelSession.

All 13 DotnetTestPipe acceptance tests, the protocol unit tests, and the contract tests pass; the strict -pack build is green.

An expert review pass was run and its findings addressed (background connect, force-abort-on-exit, protocol-contract docs) in the second commit.

⚠️ The protocol files are duplicated in dotnet/sdk — a matching PR must land there in coordination.

amauryleveand others added 2 commits July 1, 2026 16:49
…ocol (#8691)
Implements Option B from the RFC: a reverse "server control" pipe. The SDK
advertises a control pipe name in its handshake reply; the test host connects
back and parks a long-poll WaitForServerControlRequest that the SDK completes
with a ServerControlMessage (CancelSession). On cancel the host stops
gracefully via IGracefulStopTestExecutionCapability so trx/artifacts survive,
falling back to hard cancellation when no graceful capability exists. A dropped
control pipe is treated as "host gone => cancel".
- Protocol 1.4.0; handshake property ServerControlPipeName=12; serializer ids
WaitForServerControlRequest=13, ServerControlMessage=14.
- NamedPipeClient gains exitProcessOnConnectionLoss so the control channel does
not kill the host on disconnect.
- Contract + round-trip unit tests and end-to-end acceptance tests (graceful
cancel still reports; no-advertise is a no-op).
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
… the parked read on exit
- StartServerControlChannelAsync no longer blocks test start on the control-pipe
connect; connect + long-poll now run entirely on the background listener task
(fixes up-to-30s startup stall and de-risks multi-process contention).
- OnExitAsync now cancels then disposes the control pipe client before a bounded
wait, so the parked long-poll read is force-aborted even on .NET Framework where
cancelling an in-flight named-pipe read is unreliable (fixes potential exit hang).
- Documented the SDK-side contract for ServerControlPipeName (one control
connection per connecting process; SDK must keep the pipe open for the whole
data session, since an early drop is treated as cancel).
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings July 1, 2026 15:14

CopilotAI 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

Adds server-initiated session cancellation support to the dotnet test IPC protocol (MTP “server mode”) by introducing a reverse “server control” named pipe that the SDK can use to push a cooperative CancelSession signal to the test host, allowing graceful shutdown with reporting preserved.

Changes:

  • Extend the dotnet-test pipe protocol with v1.4.0, a new handshake property (ServerControlPipeName), and two new message types (WaitForServerControlRequest, ServerControlMessage).
  • Implement host-side listening/handling for server control messages (including a graceful-stop path via IGracefulStopTestExecutionCapability, with a cancellation fallback).
  • Add protocol/unit/contract coverage plus an end-to-end acceptance test and enhance the fake SDK harness to drive the control channel.
Show a summary per file
FileDescription
test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.csAdds round-trip tests for new serializers, updates stable IDs/handshake property list, and bumps supported protocol versions to include 1.4.0.
test/UnitTests/Microsoft.Testing.Platform.DotnetTestProtocolContract.UnitTests/DotnetTestProtocolContractTests.csMirrors the protocol contract stability assertions for new IDs/properties and version list.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/FakeDotnetTestSdkResult.csTracks control-pipe observations (connected + cancel sent) for acceptance assertions.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/FakeDotnetTestSdk.csAdds optional reverse control pipe server and drives CancelSession message in the fake SDK harness.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/DotnetTestPipeServerCancellationTests.csNew end-to-end acceptance tests validating graceful server-initiated cancellation behavior and the no-advertisement case.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/DotnetTestPipeProtocol.csExtends black-box protocol contract helper with new serializer IDs, handshake property ID, and server-control message encoding.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/DotnetTestPipeBaselineTests.csUpdates baseline advertised protocol versions to include 1.4.0.
src/Platform/Microsoft.Testing.Platform/ServerMode/IPushOnlyProtocol.csAdds control-channel capability flag and a start method to begin listening for server control signals.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/WaitForServerControlRequestSerializer.csNew serializer for an empty long-poll request used on the control pipe.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/ServerControlMessageSerializer.csNew serializer for a server-pushed control message (currently Kind only).
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/ObjectFieldIds.csDefines stable serializer IDs/field IDs for the new control messages.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/WaitForServerControlRequest.csNew model representing the parked long-poll request.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/ServerControlMessage.csNew model representing the server’s control reply (e.g., CancelSession).
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Constants.csAdds handshake property constant for ServerControlPipeName, defines ServerControlKinds, and bumps supported versions to include 1.4.0.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.csImplements control-pipe negotiation, background connect/listen loop, and one-time cancel dispatch + teardown behavior.
src/Platform/Microsoft.Testing.Platform/IPC/Serializers/RegisterSerializers.csRegisters the two new serializers on named-pipe endpoints.
src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeClient.csAdds exitProcessOnConnectionLoss flag to allow auxiliary channels to surface disconnects without terminating the process.
src/Platform/Microsoft.Testing.Platform/Hosts/TestHostOchestratorHost.csWires control-channel cancel to application token cancellation for orchestrator host scenario.
src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.csStarts server-control listener after a successful handshake and maps cancel to graceful-stop capability (or token cancellation fallback).

Review details

  • Files reviewed: 19/19 changed files
  • Comments generated: 1
  • Review effort level: Low

@Evangelink
Amaury Levé (Evangelink) marked this pull request as ready for review July 2, 2026 17:56
…l-safe check
- FakeDotnetTestSdk: declare the reverse control-pipe server stream with 'await
using' so its OS handle is released on every exit path (incl. exceptions),
removing the manual DisposeAsync block.
- DotnetTestConnection: use 'is true' instead of '== true' for the nullable-bool
handshake property check.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@Evangelink
Amaury Levé (Evangelink) enabled auto-merge (squash) July 2, 2026 18:21
@EvangelinkAmaury Levé (Evangelink) added the state/needs-review Awaiting review from the team. label Jul 2, 2026
@Evangelink
Amaury Levé (Evangelink) merged commit 7e8ab49 into mainJul 2, 2026
58 of 59 checks passed
@Evangelink
Amaury Levé (Evangelink) deleted the dev/amauryleve/server-session-cancellation-design branch July 2, 2026 18:57
github-actionsBot added a commit that referenced this pull request Jul 4, 2026
- Add --report-azdo-groups/--report-azdo-annotations toggles (#9542) to Platform changelog
- Add re-print errored assemblies in end-of-run recap (#9545) to Platform changelog
- Add server-initiated session cancellation (#9549) to Platform changelog
- Add fix for CloneWithUpdatedSource mutating this (#9581) to MSTest changelog
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Amaury Levé (Evangelink) added a commit that referenced this pull request Jul 5, 2026
…9613)
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

state/needs-reviewAwaiting review from the team.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[RFC] Server-initiated session cancellation in the dotnet test IPC protocol

3 participants

@Evangelink@0101
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Add server-initiated session cancellation to the dotnet test IPC protocol (#8691) - #9549

Merged
Amaury Levé (Evangelink) merged 3 commits into
mainfrom
dev/amauryleve/server-session-cancellation-design
Jul 2, 2026
Merged

Add server-initiated session cancellation to the dotnet test IPC protocol (#8691)#9549
Amaury Levé (Evangelink) merged 3 commits into
mainfrom
dev/amauryleve/server-session-cancellation-design

Conversation

@Evangelink

Copy link
Copy Markdown
Member

Closes#8691.

Implements the RFC's recommended Option B — a reverse "server control" pipe — so dotnet test-level features (global --maximum-failed-tests, --timeout, graceful Ctrl+C drain) can ask a Microsoft.Testing.Platform test app to stop cooperatively instead of only letting it run to completion or Process.Kill-ing it.

How it works

sequenceDiagram
participant SDK as dotnet test (SDK)
participant App as MTP test app
App->>SDK: Handshake (advertises 1.4.0)
SDK-->>App: Handshake reply (ServerControlPipeName=<pipe>)
App->>SDK: WaitForServerControlRequest (parks on control pipe)
Note over SDK: global budget reached
SDK-->>App: ServerControlMessage(CancelSession)
App->>App: IGracefulStopTestExecutionCapability.StopTestExecutionAsync()
App->>SDK: final results + TestSessionEnd (data pipe)
App-->>SDK: exit
Loading
  • The SDK advertises a control-pipe name in its handshake reply. Its presence is the capability signal (no separate boolean), gated per-connection — an older SDK never advertises it, so the feature stays off.
  • The test host opens a second NamedPipeClient and parks a long-poll WaitForServerControlRequest; the SDK completes it with a ServerControlMessage. This is a true server push, so it works even when the app is silent/hung — the crux for --timeout.
  • On CancelSession the host stops gracefully via IGracefulStopTestExecutionCapability (the same path --maximum-failed-tests uses), so trx/logs/artifacts for anything that completed are still emitted. It falls back to hard token cancellation only when the running framework has no graceful-stop capability.
  • The connect + long-poll run entirely on a background task, so test start is never blocked on the auxiliary channel. A dropped control pipe is treated as "host went away → cancel"; the new NamedPipeClient.exitProcessOnConnectionLoss flag keeps that from killing the host (the shared data-pipe behavior is unchanged). On exit the parked read is force-aborted (dispose-before-await), so shutdown can't hang — including on .NET Framework where cancelling an in-flight named-pipe read is unreliable.

Protocol changes (mirror in dotnet/sdk in lockstep)

  • ProtocolConstants bumped to add 1.4.0.
  • Handshake property ServerControlPipeName = 12.
  • Serializers WaitForServerControlRequest = 13, ServerControlMessage = 14 (Kind byte, CancelSession = 1). Note the RFC's "id 11 is next free" was stale — 11/12 are already AzureDevOpsLogMessage/DisplayMessage.
  • The ServerControlPipeName doc spells out the SDK-side contract: accept one control connection per connecting process, and keep the pipe open until the data session ends (an early drop is read as cancel).

Notes vs. the RFC

  • The version-negotiation "latent bug" is already effectively fixed in the current tree (the SDK returns a single negotiated version and the host tracks per-connection capability), so it's out of scope here.
  • The reaction is a graceful stop, not CancellationTokenSource.Cancel() as the RFC sketched, precisely so reporting survives.

Tests

  • Contract + round-trip unit tests for the two new serializers, plus id/property/version stability (ProtocolTests, DotnetTestProtocolContractTests).
  • End-to-end acceptance tests (DotnetTestPipeServerCancellationTests): a graceful server-initiated cancel still reports a result + TestSessionEnd and exits cleanly; an SDK that doesn't advertise the pipe is a no-op.
  • Extended the FakeDotnetTestSdk harness to stand up the control pipe and push CancelSession.

All 13 DotnetTestPipe acceptance tests, the protocol unit tests, and the contract tests pass; the strict -pack build is green.

An expert review pass was run and its findings addressed (background connect, force-abort-on-exit, protocol-contract docs) in the second commit.

⚠️ The protocol files are duplicated in dotnet/sdk — a matching PR must land there in coordination.

amauryleveand others added 2 commits July 1, 2026 16:49
…ocol (#8691)
Implements Option B from the RFC: a reverse "server control" pipe. The SDK
advertises a control pipe name in its handshake reply; the test host connects
back and parks a long-poll WaitForServerControlRequest that the SDK completes
with a ServerControlMessage (CancelSession). On cancel the host stops
gracefully via IGracefulStopTestExecutionCapability so trx/artifacts survive,
falling back to hard cancellation when no graceful capability exists. A dropped
control pipe is treated as "host gone => cancel".
- Protocol 1.4.0; handshake property ServerControlPipeName=12; serializer ids
WaitForServerControlRequest=13, ServerControlMessage=14.
- NamedPipeClient gains exitProcessOnConnectionLoss so the control channel does
not kill the host on disconnect.
- Contract + round-trip unit tests and end-to-end acceptance tests (graceful
cancel still reports; no-advertise is a no-op).
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
… the parked read on exit
- StartServerControlChannelAsync no longer blocks test start on the control-pipe
connect; connect + long-poll now run entirely on the background listener task
(fixes up-to-30s startup stall and de-risks multi-process contention).
- OnExitAsync now cancels then disposes the control pipe client before a bounded
wait, so the parked long-poll read is force-aborted even on .NET Framework where
cancelling an in-flight named-pipe read is unreliable (fixes potential exit hang).
- Documented the SDK-side contract for ServerControlPipeName (one control
connection per connecting process; SDK must keep the pipe open for the whole
data session, since an early drop is treated as cancel).
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings July 1, 2026 15:14

CopilotAI 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

Adds server-initiated session cancellation support to the dotnet test IPC protocol (MTP “server mode”) by introducing a reverse “server control” named pipe that the SDK can use to push a cooperative CancelSession signal to the test host, allowing graceful shutdown with reporting preserved.

Changes:

  • Extend the dotnet-test pipe protocol with v1.4.0, a new handshake property (ServerControlPipeName), and two new message types (WaitForServerControlRequest, ServerControlMessage).
  • Implement host-side listening/handling for server control messages (including a graceful-stop path via IGracefulStopTestExecutionCapability, with a cancellation fallback).
  • Add protocol/unit/contract coverage plus an end-to-end acceptance test and enhance the fake SDK harness to drive the control channel.
Show a summary per file
FileDescription
test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.csAdds round-trip tests for new serializers, updates stable IDs/handshake property list, and bumps supported protocol versions to include 1.4.0.
test/UnitTests/Microsoft.Testing.Platform.DotnetTestProtocolContract.UnitTests/DotnetTestProtocolContractTests.csMirrors the protocol contract stability assertions for new IDs/properties and version list.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/FakeDotnetTestSdkResult.csTracks control-pipe observations (connected + cancel sent) for acceptance assertions.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/FakeDotnetTestSdk.csAdds optional reverse control pipe server and drives CancelSession message in the fake SDK harness.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/DotnetTestPipeServerCancellationTests.csNew end-to-end acceptance tests validating graceful server-initiated cancellation behavior and the no-advertisement case.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/DotnetTestPipeProtocol.csExtends black-box protocol contract helper with new serializer IDs, handshake property ID, and server-control message encoding.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/DotnetTestPipeBaselineTests.csUpdates baseline advertised protocol versions to include 1.4.0.
src/Platform/Microsoft.Testing.Platform/ServerMode/IPushOnlyProtocol.csAdds control-channel capability flag and a start method to begin listening for server control signals.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/WaitForServerControlRequestSerializer.csNew serializer for an empty long-poll request used on the control pipe.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/ServerControlMessageSerializer.csNew serializer for a server-pushed control message (currently Kind only).
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/ObjectFieldIds.csDefines stable serializer IDs/field IDs for the new control messages.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/WaitForServerControlRequest.csNew model representing the parked long-poll request.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/ServerControlMessage.csNew model representing the server’s control reply (e.g., CancelSession).
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Constants.csAdds handshake property constant for ServerControlPipeName, defines ServerControlKinds, and bumps supported versions to include 1.4.0.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.csImplements control-pipe negotiation, background connect/listen loop, and one-time cancel dispatch + teardown behavior.
src/Platform/Microsoft.Testing.Platform/IPC/Serializers/RegisterSerializers.csRegisters the two new serializers on named-pipe endpoints.
src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeClient.csAdds exitProcessOnConnectionLoss flag to allow auxiliary channels to surface disconnects without terminating the process.
src/Platform/Microsoft.Testing.Platform/Hosts/TestHostOchestratorHost.csWires control-channel cancel to application token cancellation for orchestrator host scenario.
src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.csStarts server-control listener after a successful handshake and maps cancel to graceful-stop capability (or token cancellation fallback).

Review details

  • Files reviewed: 19/19 changed files
  • Comments generated: 1
  • Review effort level: Low

@Evangelink
Amaury Levé (Evangelink) marked this pull request as ready for review July 2, 2026 17:56
…l-safe check
- FakeDotnetTestSdk: declare the reverse control-pipe server stream with 'await
using' so its OS handle is released on every exit path (incl. exceptions),
removing the manual DisposeAsync block.
- DotnetTestConnection: use 'is true' instead of '== true' for the nullable-bool
handshake property check.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@Evangelink
Amaury Levé (Evangelink) enabled auto-merge (squash) July 2, 2026 18:21
@EvangelinkAmaury Levé (Evangelink) added the state/needs-review Awaiting review from the team. label Jul 2, 2026
@Evangelink
Amaury Levé (Evangelink) merged commit 7e8ab49 into mainJul 2, 2026
58 of 59 checks passed
@Evangelink
Amaury Levé (Evangelink) deleted the dev/amauryleve/server-session-cancellation-design branch July 2, 2026 18:57
github-actionsBot added a commit that referenced this pull request Jul 4, 2026
- Add --report-azdo-groups/--report-azdo-annotations toggles (#9542) to Platform changelog
- Add re-print errored assemblies in end-of-run recap (#9545) to Platform changelog
- Add server-initiated session cancellation (#9549) to Platform changelog
- Add fix for CloneWithUpdatedSource mutating this (#9581) to MSTest changelog
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Amaury Levé (Evangelink) added a commit that referenced this pull request Jul 5, 2026
…9613)
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

state/needs-reviewAwaiting review from the team.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[RFC] Server-initiated session cancellation in the dotnet test IPC protocol

3 participants

@Evangelink@0101
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Add server-initiated session cancellation to the dotnet test IPC protocol (#8691) - #9549

Merged
Amaury Levé (Evangelink) merged 3 commits into
mainfrom
dev/amauryleve/server-session-cancellation-design
Jul 2, 2026
Merged

Add server-initiated session cancellation to the dotnet test IPC protocol (#8691)#9549
Amaury Levé (Evangelink) merged 3 commits into
mainfrom
dev/amauryleve/server-session-cancellation-design

Conversation

@Evangelink

Copy link
Copy Markdown
Member

Closes#8691.

Implements the RFC's recommended Option B — a reverse "server control" pipe — so dotnet test-level features (global --maximum-failed-tests, --timeout, graceful Ctrl+C drain) can ask a Microsoft.Testing.Platform test app to stop cooperatively instead of only letting it run to completion or Process.Kill-ing it.

How it works

sequenceDiagram
participant SDK as dotnet test (SDK)
participant App as MTP test app
App->>SDK: Handshake (advertises 1.4.0)
SDK-->>App: Handshake reply (ServerControlPipeName=<pipe>)
App->>SDK: WaitForServerControlRequest (parks on control pipe)
Note over SDK: global budget reached
SDK-->>App: ServerControlMessage(CancelSession)
App->>App: IGracefulStopTestExecutionCapability.StopTestExecutionAsync()
App->>SDK: final results + TestSessionEnd (data pipe)
App-->>SDK: exit
Loading
  • The SDK advertises a control-pipe name in its handshake reply. Its presence is the capability signal (no separate boolean), gated per-connection — an older SDK never advertises it, so the feature stays off.
  • The test host opens a second NamedPipeClient and parks a long-poll WaitForServerControlRequest; the SDK completes it with a ServerControlMessage. This is a true server push, so it works even when the app is silent/hung — the crux for --timeout.
  • On CancelSession the host stops gracefully via IGracefulStopTestExecutionCapability (the same path --maximum-failed-tests uses), so trx/logs/artifacts for anything that completed are still emitted. It falls back to hard token cancellation only when the running framework has no graceful-stop capability.
  • The connect + long-poll run entirely on a background task, so test start is never blocked on the auxiliary channel. A dropped control pipe is treated as "host went away → cancel"; the new NamedPipeClient.exitProcessOnConnectionLoss flag keeps that from killing the host (the shared data-pipe behavior is unchanged). On exit the parked read is force-aborted (dispose-before-await), so shutdown can't hang — including on .NET Framework where cancelling an in-flight named-pipe read is unreliable.

Protocol changes (mirror in dotnet/sdk in lockstep)

  • ProtocolConstants bumped to add 1.4.0.
  • Handshake property ServerControlPipeName = 12.
  • Serializers WaitForServerControlRequest = 13, ServerControlMessage = 14 (Kind byte, CancelSession = 1). Note the RFC's "id 11 is next free" was stale — 11/12 are already AzureDevOpsLogMessage/DisplayMessage.
  • The ServerControlPipeName doc spells out the SDK-side contract: accept one control connection per connecting process, and keep the pipe open until the data session ends (an early drop is read as cancel).

Notes vs. the RFC

  • The version-negotiation "latent bug" is already effectively fixed in the current tree (the SDK returns a single negotiated version and the host tracks per-connection capability), so it's out of scope here.
  • The reaction is a graceful stop, not CancellationTokenSource.Cancel() as the RFC sketched, precisely so reporting survives.

Tests

  • Contract + round-trip unit tests for the two new serializers, plus id/property/version stability (ProtocolTests, DotnetTestProtocolContractTests).
  • End-to-end acceptance tests (DotnetTestPipeServerCancellationTests): a graceful server-initiated cancel still reports a result + TestSessionEnd and exits cleanly; an SDK that doesn't advertise the pipe is a no-op.
  • Extended the FakeDotnetTestSdk harness to stand up the control pipe and push CancelSession.

All 13 DotnetTestPipe acceptance tests, the protocol unit tests, and the contract tests pass; the strict -pack build is green.

An expert review pass was run and its findings addressed (background connect, force-abort-on-exit, protocol-contract docs) in the second commit.

⚠️ The protocol files are duplicated in dotnet/sdk — a matching PR must land there in coordination.

amauryleveand others added 2 commits July 1, 2026 16:49
…ocol (#8691)
Implements Option B from the RFC: a reverse "server control" pipe. The SDK
advertises a control pipe name in its handshake reply; the test host connects
back and parks a long-poll WaitForServerControlRequest that the SDK completes
with a ServerControlMessage (CancelSession). On cancel the host stops
gracefully via IGracefulStopTestExecutionCapability so trx/artifacts survive,
falling back to hard cancellation when no graceful capability exists. A dropped
control pipe is treated as "host gone => cancel".
- Protocol 1.4.0; handshake property ServerControlPipeName=12; serializer ids
WaitForServerControlRequest=13, ServerControlMessage=14.
- NamedPipeClient gains exitProcessOnConnectionLoss so the control channel does
not kill the host on disconnect.
- Contract + round-trip unit tests and end-to-end acceptance tests (graceful
cancel still reports; no-advertise is a no-op).
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
… the parked read on exit
- StartServerControlChannelAsync no longer blocks test start on the control-pipe
connect; connect + long-poll now run entirely on the background listener task
(fixes up-to-30s startup stall and de-risks multi-process contention).
- OnExitAsync now cancels then disposes the control pipe client before a bounded
wait, so the parked long-poll read is force-aborted even on .NET Framework where
cancelling an in-flight named-pipe read is unreliable (fixes potential exit hang).
- Documented the SDK-side contract for ServerControlPipeName (one control
connection per connecting process; SDK must keep the pipe open for the whole
data session, since an early drop is treated as cancel).
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings July 1, 2026 15:14

CopilotAI 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

Adds server-initiated session cancellation support to the dotnet test IPC protocol (MTP “server mode”) by introducing a reverse “server control” named pipe that the SDK can use to push a cooperative CancelSession signal to the test host, allowing graceful shutdown with reporting preserved.

Changes:

  • Extend the dotnet-test pipe protocol with v1.4.0, a new handshake property (ServerControlPipeName), and two new message types (WaitForServerControlRequest, ServerControlMessage).
  • Implement host-side listening/handling for server control messages (including a graceful-stop path via IGracefulStopTestExecutionCapability, with a cancellation fallback).
  • Add protocol/unit/contract coverage plus an end-to-end acceptance test and enhance the fake SDK harness to drive the control channel.
Show a summary per file
FileDescription
test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.csAdds round-trip tests for new serializers, updates stable IDs/handshake property list, and bumps supported protocol versions to include 1.4.0.
test/UnitTests/Microsoft.Testing.Platform.DotnetTestProtocolContract.UnitTests/DotnetTestProtocolContractTests.csMirrors the protocol contract stability assertions for new IDs/properties and version list.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/FakeDotnetTestSdkResult.csTracks control-pipe observations (connected + cancel sent) for acceptance assertions.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/FakeDotnetTestSdk.csAdds optional reverse control pipe server and drives CancelSession message in the fake SDK harness.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/DotnetTestPipeServerCancellationTests.csNew end-to-end acceptance tests validating graceful server-initiated cancellation behavior and the no-advertisement case.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/DotnetTestPipeProtocol.csExtends black-box protocol contract helper with new serializer IDs, handshake property ID, and server-control message encoding.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/DotnetTestPipeBaselineTests.csUpdates baseline advertised protocol versions to include 1.4.0.
src/Platform/Microsoft.Testing.Platform/ServerMode/IPushOnlyProtocol.csAdds control-channel capability flag and a start method to begin listening for server control signals.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/WaitForServerControlRequestSerializer.csNew serializer for an empty long-poll request used on the control pipe.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/ServerControlMessageSerializer.csNew serializer for a server-pushed control message (currently Kind only).
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/ObjectFieldIds.csDefines stable serializer IDs/field IDs for the new control messages.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/WaitForServerControlRequest.csNew model representing the parked long-poll request.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/ServerControlMessage.csNew model representing the server’s control reply (e.g., CancelSession).
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Constants.csAdds handshake property constant for ServerControlPipeName, defines ServerControlKinds, and bumps supported versions to include 1.4.0.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.csImplements control-pipe negotiation, background connect/listen loop, and one-time cancel dispatch + teardown behavior.
src/Platform/Microsoft.Testing.Platform/IPC/Serializers/RegisterSerializers.csRegisters the two new serializers on named-pipe endpoints.
src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeClient.csAdds exitProcessOnConnectionLoss flag to allow auxiliary channels to surface disconnects without terminating the process.
src/Platform/Microsoft.Testing.Platform/Hosts/TestHostOchestratorHost.csWires control-channel cancel to application token cancellation for orchestrator host scenario.
src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.csStarts server-control listener after a successful handshake and maps cancel to graceful-stop capability (or token cancellation fallback).

Review details

  • Files reviewed: 19/19 changed files
  • Comments generated: 1
  • Review effort level: Low

@Evangelink
Amaury Levé (Evangelink) marked this pull request as ready for review July 2, 2026 17:56
…l-safe check
- FakeDotnetTestSdk: declare the reverse control-pipe server stream with 'await
using' so its OS handle is released on every exit path (incl. exceptions),
removing the manual DisposeAsync block.
- DotnetTestConnection: use 'is true' instead of '== true' for the nullable-bool
handshake property check.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@Evangelink
Amaury Levé (Evangelink) enabled auto-merge (squash) July 2, 2026 18:21
@EvangelinkAmaury Levé (Evangelink) added the state/needs-review Awaiting review from the team. label Jul 2, 2026
@Evangelink
Amaury Levé (Evangelink) merged commit 7e8ab49 into mainJul 2, 2026
58 of 59 checks passed
@Evangelink
Amaury Levé (Evangelink) deleted the dev/amauryleve/server-session-cancellation-design branch July 2, 2026 18:57
github-actionsBot added a commit that referenced this pull request Jul 4, 2026
- Add --report-azdo-groups/--report-azdo-annotations toggles (#9542) to Platform changelog
- Add re-print errored assemblies in end-of-run recap (#9545) to Platform changelog
- Add server-initiated session cancellation (#9549) to Platform changelog
- Add fix for CloneWithUpdatedSource mutating this (#9581) to MSTest changelog
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Amaury Levé (Evangelink) added a commit that referenced this pull request Jul 5, 2026
…9613)
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

state/needs-reviewAwaiting review from the team.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[RFC] Server-initiated session cancellation in the dotnet test IPC protocol

3 participants

@Evangelink@0101
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Add server-initiated session cancellation to the dotnet test IPC protocol (#8691) - #9549

Merged
Amaury Levé (Evangelink) merged 3 commits into
mainfrom
dev/amauryleve/server-session-cancellation-design
Jul 2, 2026
Merged

Add server-initiated session cancellation to the dotnet test IPC protocol (#8691)#9549
Amaury Levé (Evangelink) merged 3 commits into
mainfrom
dev/amauryleve/server-session-cancellation-design

Conversation

@Evangelink

Copy link
Copy Markdown
Member

Closes#8691.

Implements the RFC's recommended Option B — a reverse "server control" pipe — so dotnet test-level features (global --maximum-failed-tests, --timeout, graceful Ctrl+C drain) can ask a Microsoft.Testing.Platform test app to stop cooperatively instead of only letting it run to completion or Process.Kill-ing it.

How it works

sequenceDiagram
participant SDK as dotnet test (SDK)
participant App as MTP test app
App->>SDK: Handshake (advertises 1.4.0)
SDK-->>App: Handshake reply (ServerControlPipeName=<pipe>)
App->>SDK: WaitForServerControlRequest (parks on control pipe)
Note over SDK: global budget reached
SDK-->>App: ServerControlMessage(CancelSession)
App->>App: IGracefulStopTestExecutionCapability.StopTestExecutionAsync()
App->>SDK: final results + TestSessionEnd (data pipe)
App-->>SDK: exit
Loading
  • The SDK advertises a control-pipe name in its handshake reply. Its presence is the capability signal (no separate boolean), gated per-connection — an older SDK never advertises it, so the feature stays off.
  • The test host opens a second NamedPipeClient and parks a long-poll WaitForServerControlRequest; the SDK completes it with a ServerControlMessage. This is a true server push, so it works even when the app is silent/hung — the crux for --timeout.
  • On CancelSession the host stops gracefully via IGracefulStopTestExecutionCapability (the same path --maximum-failed-tests uses), so trx/logs/artifacts for anything that completed are still emitted. It falls back to hard token cancellation only when the running framework has no graceful-stop capability.
  • The connect + long-poll run entirely on a background task, so test start is never blocked on the auxiliary channel. A dropped control pipe is treated as "host went away → cancel"; the new NamedPipeClient.exitProcessOnConnectionLoss flag keeps that from killing the host (the shared data-pipe behavior is unchanged). On exit the parked read is force-aborted (dispose-before-await), so shutdown can't hang — including on .NET Framework where cancelling an in-flight named-pipe read is unreliable.

Protocol changes (mirror in dotnet/sdk in lockstep)

  • ProtocolConstants bumped to add 1.4.0.
  • Handshake property ServerControlPipeName = 12.
  • Serializers WaitForServerControlRequest = 13, ServerControlMessage = 14 (Kind byte, CancelSession = 1). Note the RFC's "id 11 is next free" was stale — 11/12 are already AzureDevOpsLogMessage/DisplayMessage.
  • The ServerControlPipeName doc spells out the SDK-side contract: accept one control connection per connecting process, and keep the pipe open until the data session ends (an early drop is read as cancel).

Notes vs. the RFC

  • The version-negotiation "latent bug" is already effectively fixed in the current tree (the SDK returns a single negotiated version and the host tracks per-connection capability), so it's out of scope here.
  • The reaction is a graceful stop, not CancellationTokenSource.Cancel() as the RFC sketched, precisely so reporting survives.

Tests

  • Contract + round-trip unit tests for the two new serializers, plus id/property/version stability (ProtocolTests, DotnetTestProtocolContractTests).
  • End-to-end acceptance tests (DotnetTestPipeServerCancellationTests): a graceful server-initiated cancel still reports a result + TestSessionEnd and exits cleanly; an SDK that doesn't advertise the pipe is a no-op.
  • Extended the FakeDotnetTestSdk harness to stand up the control pipe and push CancelSession.

All 13 DotnetTestPipe acceptance tests, the protocol unit tests, and the contract tests pass; the strict -pack build is green.

An expert review pass was run and its findings addressed (background connect, force-abort-on-exit, protocol-contract docs) in the second commit.

⚠️ The protocol files are duplicated in dotnet/sdk — a matching PR must land there in coordination.

amauryleveand others added 2 commits July 1, 2026 16:49
…ocol (#8691)
Implements Option B from the RFC: a reverse "server control" pipe. The SDK
advertises a control pipe name in its handshake reply; the test host connects
back and parks a long-poll WaitForServerControlRequest that the SDK completes
with a ServerControlMessage (CancelSession). On cancel the host stops
gracefully via IGracefulStopTestExecutionCapability so trx/artifacts survive,
falling back to hard cancellation when no graceful capability exists. A dropped
control pipe is treated as "host gone => cancel".
- Protocol 1.4.0; handshake property ServerControlPipeName=12; serializer ids
WaitForServerControlRequest=13, ServerControlMessage=14.
- NamedPipeClient gains exitProcessOnConnectionLoss so the control channel does
not kill the host on disconnect.
- Contract + round-trip unit tests and end-to-end acceptance tests (graceful
cancel still reports; no-advertise is a no-op).
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
… the parked read on exit
- StartServerControlChannelAsync no longer blocks test start on the control-pipe
connect; connect + long-poll now run entirely on the background listener task
(fixes up-to-30s startup stall and de-risks multi-process contention).
- OnExitAsync now cancels then disposes the control pipe client before a bounded
wait, so the parked long-poll read is force-aborted even on .NET Framework where
cancelling an in-flight named-pipe read is unreliable (fixes potential exit hang).
- Documented the SDK-side contract for ServerControlPipeName (one control
connection per connecting process; SDK must keep the pipe open for the whole
data session, since an early drop is treated as cancel).
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings July 1, 2026 15:14

CopilotAI 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

Adds server-initiated session cancellation support to the dotnet test IPC protocol (MTP “server mode”) by introducing a reverse “server control” named pipe that the SDK can use to push a cooperative CancelSession signal to the test host, allowing graceful shutdown with reporting preserved.

Changes:

  • Extend the dotnet-test pipe protocol with v1.4.0, a new handshake property (ServerControlPipeName), and two new message types (WaitForServerControlRequest, ServerControlMessage).
  • Implement host-side listening/handling for server control messages (including a graceful-stop path via IGracefulStopTestExecutionCapability, with a cancellation fallback).
  • Add protocol/unit/contract coverage plus an end-to-end acceptance test and enhance the fake SDK harness to drive the control channel.
Show a summary per file
FileDescription
test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.csAdds round-trip tests for new serializers, updates stable IDs/handshake property list, and bumps supported protocol versions to include 1.4.0.
test/UnitTests/Microsoft.Testing.Platform.DotnetTestProtocolContract.UnitTests/DotnetTestProtocolContractTests.csMirrors the protocol contract stability assertions for new IDs/properties and version list.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/FakeDotnetTestSdkResult.csTracks control-pipe observations (connected + cancel sent) for acceptance assertions.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/FakeDotnetTestSdk.csAdds optional reverse control pipe server and drives CancelSession message in the fake SDK harness.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/DotnetTestPipeServerCancellationTests.csNew end-to-end acceptance tests validating graceful server-initiated cancellation behavior and the no-advertisement case.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/DotnetTestPipeProtocol.csExtends black-box protocol contract helper with new serializer IDs, handshake property ID, and server-control message encoding.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/DotnetTestPipeBaselineTests.csUpdates baseline advertised protocol versions to include 1.4.0.
src/Platform/Microsoft.Testing.Platform/ServerMode/IPushOnlyProtocol.csAdds control-channel capability flag and a start method to begin listening for server control signals.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/WaitForServerControlRequestSerializer.csNew serializer for an empty long-poll request used on the control pipe.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/ServerControlMessageSerializer.csNew serializer for a server-pushed control message (currently Kind only).
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/ObjectFieldIds.csDefines stable serializer IDs/field IDs for the new control messages.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/WaitForServerControlRequest.csNew model representing the parked long-poll request.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/ServerControlMessage.csNew model representing the server’s control reply (e.g., CancelSession).
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Constants.csAdds handshake property constant for ServerControlPipeName, defines ServerControlKinds, and bumps supported versions to include 1.4.0.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.csImplements control-pipe negotiation, background connect/listen loop, and one-time cancel dispatch + teardown behavior.
src/Platform/Microsoft.Testing.Platform/IPC/Serializers/RegisterSerializers.csRegisters the two new serializers on named-pipe endpoints.
src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeClient.csAdds exitProcessOnConnectionLoss flag to allow auxiliary channels to surface disconnects without terminating the process.
src/Platform/Microsoft.Testing.Platform/Hosts/TestHostOchestratorHost.csWires control-channel cancel to application token cancellation for orchestrator host scenario.
src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.csStarts server-control listener after a successful handshake and maps cancel to graceful-stop capability (or token cancellation fallback).

Review details

  • Files reviewed: 19/19 changed files
  • Comments generated: 1
  • Review effort level: Low

@Evangelink
Amaury Levé (Evangelink) marked this pull request as ready for review July 2, 2026 17:56
…l-safe check
- FakeDotnetTestSdk: declare the reverse control-pipe server stream with 'await
using' so its OS handle is released on every exit path (incl. exceptions),
removing the manual DisposeAsync block.
- DotnetTestConnection: use 'is true' instead of '== true' for the nullable-bool
handshake property check.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@Evangelink
Amaury Levé (Evangelink) enabled auto-merge (squash) July 2, 2026 18:21
@EvangelinkAmaury Levé (Evangelink) added the state/needs-review Awaiting review from the team. label Jul 2, 2026
@Evangelink
Amaury Levé (Evangelink) merged commit 7e8ab49 into mainJul 2, 2026
58 of 59 checks passed
@Evangelink
Amaury Levé (Evangelink) deleted the dev/amauryleve/server-session-cancellation-design branch July 2, 2026 18:57
github-actionsBot added a commit that referenced this pull request Jul 4, 2026
- Add --report-azdo-groups/--report-azdo-annotations toggles (#9542) to Platform changelog
- Add re-print errored assemblies in end-of-run recap (#9545) to Platform changelog
- Add server-initiated session cancellation (#9549) to Platform changelog
- Add fix for CloneWithUpdatedSource mutating this (#9581) to MSTest changelog
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Amaury Levé (Evangelink) added a commit that referenced this pull request Jul 5, 2026
…9613)
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

state/needs-reviewAwaiting review from the team.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[RFC] Server-initiated session cancellation in the dotnet test IPC protocol

3 participants

@Evangelink@0101
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Add server-initiated session cancellation to the dotnet test IPC protocol (#8691) - #9549

Merged
Amaury Levé (Evangelink) merged 3 commits into
mainfrom
dev/amauryleve/server-session-cancellation-design
Jul 2, 2026
Merged

Add server-initiated session cancellation to the dotnet test IPC protocol (#8691)#9549
Amaury Levé (Evangelink) merged 3 commits into
mainfrom
dev/amauryleve/server-session-cancellation-design

Conversation

@Evangelink

Copy link
Copy Markdown
Member

Closes#8691.

Implements the RFC's recommended Option B — a reverse "server control" pipe — so dotnet test-level features (global --maximum-failed-tests, --timeout, graceful Ctrl+C drain) can ask a Microsoft.Testing.Platform test app to stop cooperatively instead of only letting it run to completion or Process.Kill-ing it.

How it works

sequenceDiagram
participant SDK as dotnet test (SDK)
participant App as MTP test app
App->>SDK: Handshake (advertises 1.4.0)
SDK-->>App: Handshake reply (ServerControlPipeName=<pipe>)
App->>SDK: WaitForServerControlRequest (parks on control pipe)
Note over SDK: global budget reached
SDK-->>App: ServerControlMessage(CancelSession)
App->>App: IGracefulStopTestExecutionCapability.StopTestExecutionAsync()
App->>SDK: final results + TestSessionEnd (data pipe)
App-->>SDK: exit
Loading
  • The SDK advertises a control-pipe name in its handshake reply. Its presence is the capability signal (no separate boolean), gated per-connection — an older SDK never advertises it, so the feature stays off.
  • The test host opens a second NamedPipeClient and parks a long-poll WaitForServerControlRequest; the SDK completes it with a ServerControlMessage. This is a true server push, so it works even when the app is silent/hung — the crux for --timeout.
  • On CancelSession the host stops gracefully via IGracefulStopTestExecutionCapability (the same path --maximum-failed-tests uses), so trx/logs/artifacts for anything that completed are still emitted. It falls back to hard token cancellation only when the running framework has no graceful-stop capability.
  • The connect + long-poll run entirely on a background task, so test start is never blocked on the auxiliary channel. A dropped control pipe is treated as "host went away → cancel"; the new NamedPipeClient.exitProcessOnConnectionLoss flag keeps that from killing the host (the shared data-pipe behavior is unchanged). On exit the parked read is force-aborted (dispose-before-await), so shutdown can't hang — including on .NET Framework where cancelling an in-flight named-pipe read is unreliable.

Protocol changes (mirror in dotnet/sdk in lockstep)

  • ProtocolConstants bumped to add 1.4.0.
  • Handshake property ServerControlPipeName = 12.
  • Serializers WaitForServerControlRequest = 13, ServerControlMessage = 14 (Kind byte, CancelSession = 1). Note the RFC's "id 11 is next free" was stale — 11/12 are already AzureDevOpsLogMessage/DisplayMessage.
  • The ServerControlPipeName doc spells out the SDK-side contract: accept one control connection per connecting process, and keep the pipe open until the data session ends (an early drop is read as cancel).

Notes vs. the RFC

  • The version-negotiation "latent bug" is already effectively fixed in the current tree (the SDK returns a single negotiated version and the host tracks per-connection capability), so it's out of scope here.
  • The reaction is a graceful stop, not CancellationTokenSource.Cancel() as the RFC sketched, precisely so reporting survives.

Tests

  • Contract + round-trip unit tests for the two new serializers, plus id/property/version stability (ProtocolTests, DotnetTestProtocolContractTests).
  • End-to-end acceptance tests (DotnetTestPipeServerCancellationTests): a graceful server-initiated cancel still reports a result + TestSessionEnd and exits cleanly; an SDK that doesn't advertise the pipe is a no-op.
  • Extended the FakeDotnetTestSdk harness to stand up the control pipe and push CancelSession.

All 13 DotnetTestPipe acceptance tests, the protocol unit tests, and the contract tests pass; the strict -pack build is green.

An expert review pass was run and its findings addressed (background connect, force-abort-on-exit, protocol-contract docs) in the second commit.

⚠️ The protocol files are duplicated in dotnet/sdk — a matching PR must land there in coordination.

amauryleveand others added 2 commits July 1, 2026 16:49
…ocol (#8691)
Implements Option B from the RFC: a reverse "server control" pipe. The SDK
advertises a control pipe name in its handshake reply; the test host connects
back and parks a long-poll WaitForServerControlRequest that the SDK completes
with a ServerControlMessage (CancelSession). On cancel the host stops
gracefully via IGracefulStopTestExecutionCapability so trx/artifacts survive,
falling back to hard cancellation when no graceful capability exists. A dropped
control pipe is treated as "host gone => cancel".
- Protocol 1.4.0; handshake property ServerControlPipeName=12; serializer ids
WaitForServerControlRequest=13, ServerControlMessage=14.
- NamedPipeClient gains exitProcessOnConnectionLoss so the control channel does
not kill the host on disconnect.
- Contract + round-trip unit tests and end-to-end acceptance tests (graceful
cancel still reports; no-advertise is a no-op).
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
… the parked read on exit
- StartServerControlChannelAsync no longer blocks test start on the control-pipe
connect; connect + long-poll now run entirely on the background listener task
(fixes up-to-30s startup stall and de-risks multi-process contention).
- OnExitAsync now cancels then disposes the control pipe client before a bounded
wait, so the parked long-poll read is force-aborted even on .NET Framework where
cancelling an in-flight named-pipe read is unreliable (fixes potential exit hang).
- Documented the SDK-side contract for ServerControlPipeName (one control
connection per connecting process; SDK must keep the pipe open for the whole
data session, since an early drop is treated as cancel).
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings July 1, 2026 15:14

CopilotAI 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

Adds server-initiated session cancellation support to the dotnet test IPC protocol (MTP “server mode”) by introducing a reverse “server control” named pipe that the SDK can use to push a cooperative CancelSession signal to the test host, allowing graceful shutdown with reporting preserved.

Changes:

  • Extend the dotnet-test pipe protocol with v1.4.0, a new handshake property (ServerControlPipeName), and two new message types (WaitForServerControlRequest, ServerControlMessage).
  • Implement host-side listening/handling for server control messages (including a graceful-stop path via IGracefulStopTestExecutionCapability, with a cancellation fallback).
  • Add protocol/unit/contract coverage plus an end-to-end acceptance test and enhance the fake SDK harness to drive the control channel.
Show a summary per file
FileDescription
test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.csAdds round-trip tests for new serializers, updates stable IDs/handshake property list, and bumps supported protocol versions to include 1.4.0.
test/UnitTests/Microsoft.Testing.Platform.DotnetTestProtocolContract.UnitTests/DotnetTestProtocolContractTests.csMirrors the protocol contract stability assertions for new IDs/properties and version list.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/FakeDotnetTestSdkResult.csTracks control-pipe observations (connected + cancel sent) for acceptance assertions.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/FakeDotnetTestSdk.csAdds optional reverse control pipe server and drives CancelSession message in the fake SDK harness.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/DotnetTestPipeServerCancellationTests.csNew end-to-end acceptance tests validating graceful server-initiated cancellation behavior and the no-advertisement case.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/DotnetTestPipeProtocol.csExtends black-box protocol contract helper with new serializer IDs, handshake property ID, and server-control message encoding.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/DotnetTestPipeBaselineTests.csUpdates baseline advertised protocol versions to include 1.4.0.
src/Platform/Microsoft.Testing.Platform/ServerMode/IPushOnlyProtocol.csAdds control-channel capability flag and a start method to begin listening for server control signals.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/WaitForServerControlRequestSerializer.csNew serializer for an empty long-poll request used on the control pipe.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/ServerControlMessageSerializer.csNew serializer for a server-pushed control message (currently Kind only).
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/ObjectFieldIds.csDefines stable serializer IDs/field IDs for the new control messages.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/WaitForServerControlRequest.csNew model representing the parked long-poll request.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/ServerControlMessage.csNew model representing the server’s control reply (e.g., CancelSession).
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Constants.csAdds handshake property constant for ServerControlPipeName, defines ServerControlKinds, and bumps supported versions to include 1.4.0.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.csImplements control-pipe negotiation, background connect/listen loop, and one-time cancel dispatch + teardown behavior.
src/Platform/Microsoft.Testing.Platform/IPC/Serializers/RegisterSerializers.csRegisters the two new serializers on named-pipe endpoints.
src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeClient.csAdds exitProcessOnConnectionLoss flag to allow auxiliary channels to surface disconnects without terminating the process.
src/Platform/Microsoft.Testing.Platform/Hosts/TestHostOchestratorHost.csWires control-channel cancel to application token cancellation for orchestrator host scenario.
src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.csStarts server-control listener after a successful handshake and maps cancel to graceful-stop capability (or token cancellation fallback).

Review details

  • Files reviewed: 19/19 changed files
  • Comments generated: 1
  • Review effort level: Low

@Evangelink
Amaury Levé (Evangelink) marked this pull request as ready for review July 2, 2026 17:56
…l-safe check
- FakeDotnetTestSdk: declare the reverse control-pipe server stream with 'await
using' so its OS handle is released on every exit path (incl. exceptions),
removing the manual DisposeAsync block.
- DotnetTestConnection: use 'is true' instead of '== true' for the nullable-bool
handshake property check.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@Evangelink
Amaury Levé (Evangelink) enabled auto-merge (squash) July 2, 2026 18:21
@EvangelinkAmaury Levé (Evangelink) added the state/needs-review Awaiting review from the team. label Jul 2, 2026
@Evangelink
Amaury Levé (Evangelink) merged commit 7e8ab49 into mainJul 2, 2026
58 of 59 checks passed
@Evangelink
Amaury Levé (Evangelink) deleted the dev/amauryleve/server-session-cancellation-design branch July 2, 2026 18:57
github-actionsBot added a commit that referenced this pull request Jul 4, 2026
- Add --report-azdo-groups/--report-azdo-annotations toggles (#9542) to Platform changelog
- Add re-print errored assemblies in end-of-run recap (#9545) to Platform changelog
- Add server-initiated session cancellation (#9549) to Platform changelog
- Add fix for CloneWithUpdatedSource mutating this (#9581) to MSTest changelog
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Amaury Levé (Evangelink) added a commit that referenced this pull request Jul 5, 2026
…9613)
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

state/needs-reviewAwaiting review from the team.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[RFC] Server-initiated session cancellation in the dotnet test IPC protocol

3 participants

@Evangelink@0101
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Add server-initiated session cancellation to the dotnet test IPC protocol (#8691) - #9549

Merged
Amaury Levé (Evangelink) merged 3 commits into
mainfrom
dev/amauryleve/server-session-cancellation-design
Jul 2, 2026
Merged

Add server-initiated session cancellation to the dotnet test IPC protocol (#8691)#9549
Amaury Levé (Evangelink) merged 3 commits into
mainfrom
dev/amauryleve/server-session-cancellation-design

Conversation

@Evangelink

Copy link
Copy Markdown
Member

Closes#8691.

Implements the RFC's recommended Option B — a reverse "server control" pipe — so dotnet test-level features (global --maximum-failed-tests, --timeout, graceful Ctrl+C drain) can ask a Microsoft.Testing.Platform test app to stop cooperatively instead of only letting it run to completion or Process.Kill-ing it.

How it works

sequenceDiagram
participant SDK as dotnet test (SDK)
participant App as MTP test app
App->>SDK: Handshake (advertises 1.4.0)
SDK-->>App: Handshake reply (ServerControlPipeName=<pipe>)
App->>SDK: WaitForServerControlRequest (parks on control pipe)
Note over SDK: global budget reached
SDK-->>App: ServerControlMessage(CancelSession)
App->>App: IGracefulStopTestExecutionCapability.StopTestExecutionAsync()
App->>SDK: final results + TestSessionEnd (data pipe)
App-->>SDK: exit
Loading
  • The SDK advertises a control-pipe name in its handshake reply. Its presence is the capability signal (no separate boolean), gated per-connection — an older SDK never advertises it, so the feature stays off.
  • The test host opens a second NamedPipeClient and parks a long-poll WaitForServerControlRequest; the SDK completes it with a ServerControlMessage. This is a true server push, so it works even when the app is silent/hung — the crux for --timeout.
  • On CancelSession the host stops gracefully via IGracefulStopTestExecutionCapability (the same path --maximum-failed-tests uses), so trx/logs/artifacts for anything that completed are still emitted. It falls back to hard token cancellation only when the running framework has no graceful-stop capability.
  • The connect + long-poll run entirely on a background task, so test start is never blocked on the auxiliary channel. A dropped control pipe is treated as "host went away → cancel"; the new NamedPipeClient.exitProcessOnConnectionLoss flag keeps that from killing the host (the shared data-pipe behavior is unchanged). On exit the parked read is force-aborted (dispose-before-await), so shutdown can't hang — including on .NET Framework where cancelling an in-flight named-pipe read is unreliable.

Protocol changes (mirror in dotnet/sdk in lockstep)

  • ProtocolConstants bumped to add 1.4.0.
  • Handshake property ServerControlPipeName = 12.
  • Serializers WaitForServerControlRequest = 13, ServerControlMessage = 14 (Kind byte, CancelSession = 1). Note the RFC's "id 11 is next free" was stale — 11/12 are already AzureDevOpsLogMessage/DisplayMessage.
  • The ServerControlPipeName doc spells out the SDK-side contract: accept one control connection per connecting process, and keep the pipe open until the data session ends (an early drop is read as cancel).

Notes vs. the RFC

  • The version-negotiation "latent bug" is already effectively fixed in the current tree (the SDK returns a single negotiated version and the host tracks per-connection capability), so it's out of scope here.
  • The reaction is a graceful stop, not CancellationTokenSource.Cancel() as the RFC sketched, precisely so reporting survives.

Tests

  • Contract + round-trip unit tests for the two new serializers, plus id/property/version stability (ProtocolTests, DotnetTestProtocolContractTests).
  • End-to-end acceptance tests (DotnetTestPipeServerCancellationTests): a graceful server-initiated cancel still reports a result + TestSessionEnd and exits cleanly; an SDK that doesn't advertise the pipe is a no-op.
  • Extended the FakeDotnetTestSdk harness to stand up the control pipe and push CancelSession.

All 13 DotnetTestPipe acceptance tests, the protocol unit tests, and the contract tests pass; the strict -pack build is green.

An expert review pass was run and its findings addressed (background connect, force-abort-on-exit, protocol-contract docs) in the second commit.

⚠️ The protocol files are duplicated in dotnet/sdk — a matching PR must land there in coordination.

amauryleveand others added 2 commits July 1, 2026 16:49
…ocol (#8691)
Implements Option B from the RFC: a reverse "server control" pipe. The SDK
advertises a control pipe name in its handshake reply; the test host connects
back and parks a long-poll WaitForServerControlRequest that the SDK completes
with a ServerControlMessage (CancelSession). On cancel the host stops
gracefully via IGracefulStopTestExecutionCapability so trx/artifacts survive,
falling back to hard cancellation when no graceful capability exists. A dropped
control pipe is treated as "host gone => cancel".
- Protocol 1.4.0; handshake property ServerControlPipeName=12; serializer ids
WaitForServerControlRequest=13, ServerControlMessage=14.
- NamedPipeClient gains exitProcessOnConnectionLoss so the control channel does
not kill the host on disconnect.
- Contract + round-trip unit tests and end-to-end acceptance tests (graceful
cancel still reports; no-advertise is a no-op).
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
… the parked read on exit
- StartServerControlChannelAsync no longer blocks test start on the control-pipe
connect; connect + long-poll now run entirely on the background listener task
(fixes up-to-30s startup stall and de-risks multi-process contention).
- OnExitAsync now cancels then disposes the control pipe client before a bounded
wait, so the parked long-poll read is force-aborted even on .NET Framework where
cancelling an in-flight named-pipe read is unreliable (fixes potential exit hang).
- Documented the SDK-side contract for ServerControlPipeName (one control
connection per connecting process; SDK must keep the pipe open for the whole
data session, since an early drop is treated as cancel).
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings July 1, 2026 15:14

CopilotAI 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

Adds server-initiated session cancellation support to the dotnet test IPC protocol (MTP “server mode”) by introducing a reverse “server control” named pipe that the SDK can use to push a cooperative CancelSession signal to the test host, allowing graceful shutdown with reporting preserved.

Changes:

  • Extend the dotnet-test pipe protocol with v1.4.0, a new handshake property (ServerControlPipeName), and two new message types (WaitForServerControlRequest, ServerControlMessage).
  • Implement host-side listening/handling for server control messages (including a graceful-stop path via IGracefulStopTestExecutionCapability, with a cancellation fallback).
  • Add protocol/unit/contract coverage plus an end-to-end acceptance test and enhance the fake SDK harness to drive the control channel.
Show a summary per file
FileDescription
test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.csAdds round-trip tests for new serializers, updates stable IDs/handshake property list, and bumps supported protocol versions to include 1.4.0.
test/UnitTests/Microsoft.Testing.Platform.DotnetTestProtocolContract.UnitTests/DotnetTestProtocolContractTests.csMirrors the protocol contract stability assertions for new IDs/properties and version list.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/FakeDotnetTestSdkResult.csTracks control-pipe observations (connected + cancel sent) for acceptance assertions.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/FakeDotnetTestSdk.csAdds optional reverse control pipe server and drives CancelSession message in the fake SDK harness.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/DotnetTestPipeServerCancellationTests.csNew end-to-end acceptance tests validating graceful server-initiated cancellation behavior and the no-advertisement case.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/DotnetTestPipeProtocol.csExtends black-box protocol contract helper with new serializer IDs, handshake property ID, and server-control message encoding.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/DotnetTestPipeBaselineTests.csUpdates baseline advertised protocol versions to include 1.4.0.
src/Platform/Microsoft.Testing.Platform/ServerMode/IPushOnlyProtocol.csAdds control-channel capability flag and a start method to begin listening for server control signals.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/WaitForServerControlRequestSerializer.csNew serializer for an empty long-poll request used on the control pipe.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/ServerControlMessageSerializer.csNew serializer for a server-pushed control message (currently Kind only).
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/ObjectFieldIds.csDefines stable serializer IDs/field IDs for the new control messages.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/WaitForServerControlRequest.csNew model representing the parked long-poll request.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/ServerControlMessage.csNew model representing the server’s control reply (e.g., CancelSession).
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Constants.csAdds handshake property constant for ServerControlPipeName, defines ServerControlKinds, and bumps supported versions to include 1.4.0.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.csImplements control-pipe negotiation, background connect/listen loop, and one-time cancel dispatch + teardown behavior.
src/Platform/Microsoft.Testing.Platform/IPC/Serializers/RegisterSerializers.csRegisters the two new serializers on named-pipe endpoints.
src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeClient.csAdds exitProcessOnConnectionLoss flag to allow auxiliary channels to surface disconnects without terminating the process.
src/Platform/Microsoft.Testing.Platform/Hosts/TestHostOchestratorHost.csWires control-channel cancel to application token cancellation for orchestrator host scenario.
src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.csStarts server-control listener after a successful handshake and maps cancel to graceful-stop capability (or token cancellation fallback).

Review details

  • Files reviewed: 19/19 changed files
  • Comments generated: 1
  • Review effort level: Low

@Evangelink
Amaury Levé (Evangelink) marked this pull request as ready for review July 2, 2026 17:56
…l-safe check
- FakeDotnetTestSdk: declare the reverse control-pipe server stream with 'await
using' so its OS handle is released on every exit path (incl. exceptions),
removing the manual DisposeAsync block.
- DotnetTestConnection: use 'is true' instead of '== true' for the nullable-bool
handshake property check.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@Evangelink
Amaury Levé (Evangelink) enabled auto-merge (squash) July 2, 2026 18:21
@EvangelinkAmaury Levé (Evangelink) added the state/needs-review Awaiting review from the team. label Jul 2, 2026
@Evangelink
Amaury Levé (Evangelink) merged commit 7e8ab49 into mainJul 2, 2026
58 of 59 checks passed
@Evangelink
Amaury Levé (Evangelink) deleted the dev/amauryleve/server-session-cancellation-design branch July 2, 2026 18:57
github-actionsBot added a commit that referenced this pull request Jul 4, 2026
- Add --report-azdo-groups/--report-azdo-annotations toggles (#9542) to Platform changelog
- Add re-print errored assemblies in end-of-run recap (#9545) to Platform changelog
- Add server-initiated session cancellation (#9549) to Platform changelog
- Add fix for CloneWithUpdatedSource mutating this (#9581) to MSTest changelog
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Amaury Levé (Evangelink) added a commit that referenced this pull request Jul 5, 2026
…9613)
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

state/needs-reviewAwaiting review from the team.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[RFC] Server-initiated session cancellation in the dotnet test IPC protocol

3 participants

@Evangelink@0101
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Add server-initiated session cancellation to the dotnet test IPC protocol (#8691) - #9549

Merged
Amaury Levé (Evangelink) merged 3 commits into
mainfrom
dev/amauryleve/server-session-cancellation-design
Jul 2, 2026
Merged

Add server-initiated session cancellation to the dotnet test IPC protocol (#8691)#9549
Amaury Levé (Evangelink) merged 3 commits into
mainfrom
dev/amauryleve/server-session-cancellation-design

Conversation

@Evangelink

Copy link
Copy Markdown
Member

Closes#8691.

Implements the RFC's recommended Option B — a reverse "server control" pipe — so dotnet test-level features (global --maximum-failed-tests, --timeout, graceful Ctrl+C drain) can ask a Microsoft.Testing.Platform test app to stop cooperatively instead of only letting it run to completion or Process.Kill-ing it.

How it works

sequenceDiagram
participant SDK as dotnet test (SDK)
participant App as MTP test app
App->>SDK: Handshake (advertises 1.4.0)
SDK-->>App: Handshake reply (ServerControlPipeName=<pipe>)
App->>SDK: WaitForServerControlRequest (parks on control pipe)
Note over SDK: global budget reached
SDK-->>App: ServerControlMessage(CancelSession)
App->>App: IGracefulStopTestExecutionCapability.StopTestExecutionAsync()
App->>SDK: final results + TestSessionEnd (data pipe)
App-->>SDK: exit
Loading
  • The SDK advertises a control-pipe name in its handshake reply. Its presence is the capability signal (no separate boolean), gated per-connection — an older SDK never advertises it, so the feature stays off.
  • The test host opens a second NamedPipeClient and parks a long-poll WaitForServerControlRequest; the SDK completes it with a ServerControlMessage. This is a true server push, so it works even when the app is silent/hung — the crux for --timeout.
  • On CancelSession the host stops gracefully via IGracefulStopTestExecutionCapability (the same path --maximum-failed-tests uses), so trx/logs/artifacts for anything that completed are still emitted. It falls back to hard token cancellation only when the running framework has no graceful-stop capability.
  • The connect + long-poll run entirely on a background task, so test start is never blocked on the auxiliary channel. A dropped control pipe is treated as "host went away → cancel"; the new NamedPipeClient.exitProcessOnConnectionLoss flag keeps that from killing the host (the shared data-pipe behavior is unchanged). On exit the parked read is force-aborted (dispose-before-await), so shutdown can't hang — including on .NET Framework where cancelling an in-flight named-pipe read is unreliable.

Protocol changes (mirror in dotnet/sdk in lockstep)

  • ProtocolConstants bumped to add 1.4.0.
  • Handshake property ServerControlPipeName = 12.
  • Serializers WaitForServerControlRequest = 13, ServerControlMessage = 14 (Kind byte, CancelSession = 1). Note the RFC's "id 11 is next free" was stale — 11/12 are already AzureDevOpsLogMessage/DisplayMessage.
  • The ServerControlPipeName doc spells out the SDK-side contract: accept one control connection per connecting process, and keep the pipe open until the data session ends (an early drop is read as cancel).

Notes vs. the RFC

  • The version-negotiation "latent bug" is already effectively fixed in the current tree (the SDK returns a single negotiated version and the host tracks per-connection capability), so it's out of scope here.
  • The reaction is a graceful stop, not CancellationTokenSource.Cancel() as the RFC sketched, precisely so reporting survives.

Tests

  • Contract + round-trip unit tests for the two new serializers, plus id/property/version stability (ProtocolTests, DotnetTestProtocolContractTests).
  • End-to-end acceptance tests (DotnetTestPipeServerCancellationTests): a graceful server-initiated cancel still reports a result + TestSessionEnd and exits cleanly; an SDK that doesn't advertise the pipe is a no-op.
  • Extended the FakeDotnetTestSdk harness to stand up the control pipe and push CancelSession.

All 13 DotnetTestPipe acceptance tests, the protocol unit tests, and the contract tests pass; the strict -pack build is green.

An expert review pass was run and its findings addressed (background connect, force-abort-on-exit, protocol-contract docs) in the second commit.

⚠️ The protocol files are duplicated in dotnet/sdk — a matching PR must land there in coordination.

amauryleveand others added 2 commits July 1, 2026 16:49
…ocol (#8691)
Implements Option B from the RFC: a reverse "server control" pipe. The SDK
advertises a control pipe name in its handshake reply; the test host connects
back and parks a long-poll WaitForServerControlRequest that the SDK completes
with a ServerControlMessage (CancelSession). On cancel the host stops
gracefully via IGracefulStopTestExecutionCapability so trx/artifacts survive,
falling back to hard cancellation when no graceful capability exists. A dropped
control pipe is treated as "host gone => cancel".
- Protocol 1.4.0; handshake property ServerControlPipeName=12; serializer ids
WaitForServerControlRequest=13, ServerControlMessage=14.
- NamedPipeClient gains exitProcessOnConnectionLoss so the control channel does
not kill the host on disconnect.
- Contract + round-trip unit tests and end-to-end acceptance tests (graceful
cancel still reports; no-advertise is a no-op).
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
… the parked read on exit
- StartServerControlChannelAsync no longer blocks test start on the control-pipe
connect; connect + long-poll now run entirely on the background listener task
(fixes up-to-30s startup stall and de-risks multi-process contention).
- OnExitAsync now cancels then disposes the control pipe client before a bounded
wait, so the parked long-poll read is force-aborted even on .NET Framework where
cancelling an in-flight named-pipe read is unreliable (fixes potential exit hang).
- Documented the SDK-side contract for ServerControlPipeName (one control
connection per connecting process; SDK must keep the pipe open for the whole
data session, since an early drop is treated as cancel).
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings July 1, 2026 15:14

CopilotAI 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

Adds server-initiated session cancellation support to the dotnet test IPC protocol (MTP “server mode”) by introducing a reverse “server control” named pipe that the SDK can use to push a cooperative CancelSession signal to the test host, allowing graceful shutdown with reporting preserved.

Changes:

  • Extend the dotnet-test pipe protocol with v1.4.0, a new handshake property (ServerControlPipeName), and two new message types (WaitForServerControlRequest, ServerControlMessage).
  • Implement host-side listening/handling for server control messages (including a graceful-stop path via IGracefulStopTestExecutionCapability, with a cancellation fallback).
  • Add protocol/unit/contract coverage plus an end-to-end acceptance test and enhance the fake SDK harness to drive the control channel.
Show a summary per file
FileDescription
test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.csAdds round-trip tests for new serializers, updates stable IDs/handshake property list, and bumps supported protocol versions to include 1.4.0.
test/UnitTests/Microsoft.Testing.Platform.DotnetTestProtocolContract.UnitTests/DotnetTestProtocolContractTests.csMirrors the protocol contract stability assertions for new IDs/properties and version list.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/FakeDotnetTestSdkResult.csTracks control-pipe observations (connected + cancel sent) for acceptance assertions.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/FakeDotnetTestSdk.csAdds optional reverse control pipe server and drives CancelSession message in the fake SDK harness.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/DotnetTestPipeServerCancellationTests.csNew end-to-end acceptance tests validating graceful server-initiated cancellation behavior and the no-advertisement case.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/DotnetTestPipeProtocol.csExtends black-box protocol contract helper with new serializer IDs, handshake property ID, and server-control message encoding.
test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/DotnetTestPipeBaselineTests.csUpdates baseline advertised protocol versions to include 1.4.0.
src/Platform/Microsoft.Testing.Platform/ServerMode/IPushOnlyProtocol.csAdds control-channel capability flag and a start method to begin listening for server control signals.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/WaitForServerControlRequestSerializer.csNew serializer for an empty long-poll request used on the control pipe.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/ServerControlMessageSerializer.csNew serializer for a server-pushed control message (currently Kind only).
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/ObjectFieldIds.csDefines stable serializer IDs/field IDs for the new control messages.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/WaitForServerControlRequest.csNew model representing the parked long-poll request.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/ServerControlMessage.csNew model representing the server’s control reply (e.g., CancelSession).
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Constants.csAdds handshake property constant for ServerControlPipeName, defines ServerControlKinds, and bumps supported versions to include 1.4.0.
src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.csImplements control-pipe negotiation, background connect/listen loop, and one-time cancel dispatch + teardown behavior.
src/Platform/Microsoft.Testing.Platform/IPC/Serializers/RegisterSerializers.csRegisters the two new serializers on named-pipe endpoints.
src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeClient.csAdds exitProcessOnConnectionLoss flag to allow auxiliary channels to surface disconnects without terminating the process.
src/Platform/Microsoft.Testing.Platform/Hosts/TestHostOchestratorHost.csWires control-channel cancel to application token cancellation for orchestrator host scenario.
src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.csStarts server-control listener after a successful handshake and maps cancel to graceful-stop capability (or token cancellation fallback).

Review details

  • Files reviewed: 19/19 changed files
  • Comments generated: 1
  • Review effort level: Low

@Evangelink
Amaury Levé (Evangelink) marked this pull request as ready for review July 2, 2026 17:56
…l-safe check
- FakeDotnetTestSdk: declare the reverse control-pipe server stream with 'await
using' so its OS handle is released on every exit path (incl. exceptions),
removing the manual DisposeAsync block.
- DotnetTestConnection: use 'is true' instead of '== true' for the nullable-bool
handshake property check.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@Evangelink
Amaury Levé (Evangelink) enabled auto-merge (squash) July 2, 2026 18:21
@EvangelinkAmaury Levé (Evangelink) added the state/needs-review Awaiting review from the team. label Jul 2, 2026
@Evangelink
Amaury Levé (Evangelink) merged commit 7e8ab49 into mainJul 2, 2026
58 of 59 checks passed
@Evangelink
Amaury Levé (Evangelink) deleted the dev/amauryleve/server-session-cancellation-design branch July 2, 2026 18:57
github-actionsBot added a commit that referenced this pull request Jul 4, 2026
- Add --report-azdo-groups/--report-azdo-annotations toggles (#9542) to Platform changelog
- Add re-print errored assemblies in end-of-run recap (#9545) to Platform changelog
- Add server-initiated session cancellation (#9549) to Platform changelog
- Add fix for CloneWithUpdatedSource mutating this (#9581) to MSTest changelog
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Amaury Levé (Evangelink) added a commit that referenced this pull request Jul 5, 2026
…9613)
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

state/needs-reviewAwaiting review from the team.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[RFC] Server-initiated session cancellation in the dotnet test IPC protocol

3 participants

@Evangelink@0101