Skip to content

Fix MTP affected-test collection in headless Windows runs - #11896

Merged
Amaury Levé (Evangelink) merged 2 commits into
mainfrom
dev/amauryleve/pipeline-test-fixes
Oct 12, 2026
Merged

Amaury Levé (Evangelink) merged 2 commits into
mainfrom
dev/amauryleve/pipeline-test-fixes

Conversation

@Evangelink

Copy link
Copy Markdown
Member

Pull request

Summary

Fix the Windows Release affected-test collection failures in pipeline run 20261012.11. The failures had multiple causes, not an SDK handshake regression:

  • Emit ASCII-only discovery JSON while preserving decoded Unicode UIDs and metadata. Headless Windows legacy encoding can convert U+20DD into a raw tab after serialization, making otherwise valid JSON unreadable.
  • Keep VSTestBridge startup diagnostics and acceptance-runner process statistics on stderr instead of surrounding the JSON document on stdout.
  • Resolve desktop XML fixtures from the application base directory, independently of the collection child's working directory.
  • Load both access-control and Windows-principal assemblies before AppContainer impersonation, retaining the real connection and denial assertions.

No tests are disabled, and pipeline fallback, exit-code handling, scheduling, package versions, and public APIs are unchanged.

Design and decision record

The existing affected-test collection contract records the rationale. A separate feature record is unnecessary for these repairs.

Escaping Unicode keeps the JSON schema and decoded values unchanged without changing process-global console encoding or adding a dependency. Strict parsing and real collection exposed issues that serializer-only and ordinary test execution missed: preloading access control alone still failed when the collector reached the lazy Windows-principal dependency.

Demonstration

A text transcript is clearer than screenshots for these JSON/process failures.

Before:
  Discovery failed: The test discovery JSON response is missing or invalid.
  JsonReaderException: '0x09' is invalid within a JSON string.
  FileNotFoundException: System.Security.AccessControl / System.Security.Principal.Windows

After:
  All seven originally failing modules emit valid headless discovery JSON.
  198 focused cases passed; zero skipped.
  13 persisted test maps cover 15,658 cases.
  Final net8/net9 collection exits: 0, with no failed batches or handshake errors.

Discovery was exercised through real apphosts with CreateNoWindow=true and --list-tests json, not just in-memory serialization. The packed headless regression consumes Microsoft.Testing.Platform/2.6.0-dev on net10.0; its executed DLL matches the freshly packed payload by SHA-256.

Validation and regression proof

Baseline production: 7d50b3e8c232c49573d37da996c9a665eb2f4dac, with the new regression tests retained in the task-owned worktree. Final source: 1a29ef2b83a604e31278e9b4efa769f7c832cb92. Validation used Release, the pinned SDK 12.0.100-alpha.1.26509.101, and affected-tests/coverage packages 18.13.0-preview.26508.3.

Check Result
Serialize_NonAsciiCharacters_ProducesLosslessAsciiJson Red: executed and failed exact ASCII JSON equality, exit 2. Green: passes on net8/net9/net462.
ListTestsJson_HeadlessProcess_PreservesUnicode Red: executed against the baseline packed producer and failed strict parsing on a raw tab, exit 2. Green: passes against the repacked producer.
Serializer and NamedPipeServerSecurityTests 64 passed per net8/net9/net462, no skips.
Both DesktopTestDataSourceTests.GetDataShould* methods Two passed per net462/net48 from repository cwd.
Packed headless and existing dotnet-test pipe discovery cases Two planned, selected, executed, and passed; exit 0, no skips; execution verifier passed.
Full instrumented collection 13 validated map shards. The first pass exposed the additional principal load; final complete net8/net9 reruns collected 2,932/2,933 cases with exit 0 and no failed-child/batch messages. Other modules collected without failures.

Build/pack commands, all successful with exit 0:

.\build.cmd -pack -c Release -projects 'src\**\*.csproj' -bl
.\build.cmd -pack -c Release -projects src\Platform\Microsoft.Testing.Platform\Microsoft.Testing.Platform.csproj -bl
.\.dotnet\dotnet.exe build test\UnitTests\Microsoft.Testing.Platform.UnitTests\Microsoft.Testing.Platform.UnitTests.csproj -c Release --no-restore -v:q "-bl:$PWD\artifacts\pipe-closure-build-{}.binlog"

Focused runner commands used the repo-local SDK on PATH and DOTNET_ROOT pointing to .dotnet; modern acceptance runs also set DOTNET_ROLL_FORWARD=Major and DOTNET_ROLL_FORWARD_TO_PRERELEASE=1:

# net8.0 and net9.0: each exited 0, 64 passed.
foreach ($tfm in @('net8.0', 'net9.0')) {
    .\.dotnet\dotnet.exe "artifacts\bin\Microsoft.Testing.Platform.UnitTests\Release\$tfm\Microsoft.Testing.Platform.UnitTests.dll" --filter 'FullyQualifiedName~DiscoveredTestsJsonSerializerTests|FullyQualifiedName~NamedPipeServerSecurityTests' --report-trx --report-trx-filename "platform-final-$tfm.trx" --results-directory "$PWD\artifacts\TestResults\pipeline-fixes" --show-test-results failed
}
# net462: exit 0, 64 passed.
& artifacts\bin\Microsoft.Testing.Platform.UnitTests\Release\net462\Microsoft.Testing.Platform.UnitTests.exe --filter 'FullyQualifiedName~DiscoveredTestsJsonSerializerTests|FullyQualifiedName~NamedPipeServerSecurityTests' --report-trx --report-trx-filename platform-green-net462.trx --results-directory "$PWD\artifacts\TestResults\pipeline-fixes" --show-test-results all
# Both desktop TFMs: each exited 0, two passed.
foreach ($tfm in @('net462', 'net48')) {
    & "artifacts\bin\MSTestAdapter.PlatformServices.UnitTests\Release\$tfm\MSTestAdapter.PlatformServices.UnitTests.exe" --filter-uid MSTestAdapter.PlatformServices.UnitTests.Services.DesktopTestDataSourceTests.GetDataShouldReadDataFromGivenDataSource MSTestAdapter.PlatformServices.UnitTests.Services.DesktopTestDataSourceTests.GetDataShouldSetDataConnectionInTestContextObject --report-trx --report-trx-filename "desktop-green-$tfm.trx" --results-directory "$PWD\artifacts\TestResults\pipeline-fixes" --show-test-results all
}
# Packed acceptance: exit 0, two passed.
$project = (Resolve-Path test\IntegrationTests\Microsoft.Testing.Platform.Acceptance.IntegrationTests\Microsoft.Testing.Platform.Acceptance.IntegrationTests.csproj).Path
.\.dotnet\dotnet.exe test --project $project -c Release --no-build -p:TestingPlatformCommandLineArguments= -p:TestRunnerAdditionalArguments= --filter 'FullyQualifiedName~DotnetTestPipeListTestsJsonTests' --report-trx --report-trx-filename headless-final.trx --results-directory "$PWD\artifacts\TestResults\pipeline-fixes" --show-test-results all "-bl:$PWD\artifacts\headless-final-{}.binlog"

Real collector validation used a task-owned solution containing the four affected unit-test projects and a nested global.json selecting the supported local storage provider. Collection rejects filters by design; none were used. From that validation directory, with repo-local dotnet on PATH and DOTNET_CLI_ENABLE_AFFECTED_TESTS=1:

dotnet test --solution "$root\artifacts\affected-validation\AffectedModules.slnx" -c Release --no-build -p:UsingDotNetTest=true -p:TestingPlatformCommandLineArguments= -p:TestRunnerAdditionalArguments= --collect-test-map "-bl:$root\artifacts\collect-unit-modules-green-{}.binlog"
# After completing the dependency preload: both final reruns exited 0 without failed batches.
foreach ($tfm in @('net8.0', 'net9.0')) {
    dotnet test --project $project -c Release -f $tfm --no-build -p:UsingDotNetTest=true -p:TestingPlatformCommandLineArguments= -p:TestRunnerAdditionalArguments= --collect-test-map "-bl:$root\artifacts\collect-platform-final-$tfm-{}.binlog"
}

Here $root is the worktree root and $project in the collection block is the absolute Microsoft.Testing.Platform.UnitTests.csproj path. Collection intentionally suppresses ordinary SDK reporting, so the parent's zero-test summary is not execution proof: map contents, discovered UIDs, source associations, and absence of failed-batch output were checked explicitly.

Package SHA-256: 0FE351E345A589D75246BC8FEA366288566AA4D54B887322A41BC1EF0A973888. Executed consumer/platform DLL SHA-256: 3AF928F7CE13E5C8472052E01EF5270F28EC38E711D28634AC8425D8666AD833; obj/project.assets.json confirms the isolated cache and resolved package.

TRX, binlogs, map summaries, and red/green logs are retained locally, not uploaded: artifacts\TestResults\pipeline-fixes, artifacts\collection-final-summary.json, and artifacts\packed-consumer-provenance.json. Azure DevOps artifact upload and the full acceptance collection matrix were not rerun locally; CI on this PR remains the verification for those paths.

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

Copilot-Session: 60094118-e0a2-49e7-8ae9-b97c0d7efa54
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 60094118-e0a2-49e7-8ae9-b97c0d7efa54
Copilot AI balanced review requested due to automatic review settings October 12, 2026 13:11
@github-actions github-actions Bot added the state/needs-review Awaiting review from the team. label Oct 12, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟢 Approval recommended

The changes consistently address the documented failure modes with focused unit and packed acceptance coverage.

0 open findings

What changed in this PR

Stabilizes MTP affected-test collection for headless Windows processes by preserving clean, valid JSON output and fixing environment-dependent tests.

Changes:

  • Emits ASCII-safe JSON while preserving decoded Unicode values.
  • Redirects diagnostics to stderr and fixes Windows fixture/dependency loading.
  • Adds unit, packed acceptance, and contract documentation coverage.

Confidence at a glance

🟢 Serialization, Windows behavior, tests, and documentationNo actionable defects identified.
File Description
src/​Platform/​Microsoft.Testing.Platform/​OutputDevice/​JsonStringWriter.cs Escapes non-ASCII JSON characters.
docs/​affected-test-selection.md Documents headless collection requirements.
test/​UnitTests/​MSTestAdapter.PlatformServices.UnitTests/​Services/​DesktopTestDataSourceTests.cs Resolves copied XML fixtures reliably.
test/​UnitTests/​Microsoft.Testing.Platform.UnitTests/​OutputDevice/​DiscoveredTestsJsonSerializerTests.cs Verifies ASCII output and Unicode round-tripping.
test/​UnitTests/​Microsoft.Testing.Platform.UnitTests/​IPC/​NamedPipeServerSecurityTests.cs Preloads security assemblies before impersonation.
test/​UnitTests/​Microsoft.Testing.Extensions.VSTestBridge.UnitTests/​Program.cs Moves startup diagnostics to stderr.
test/​IntegrationTests/​MSTest.Acceptance.IntegrationTests/​Program.cs Moves process statistics to stderr.
test/​IntegrationTests/​Microsoft.Testing.Platform.Acceptance.IntegrationTests/​Program.cs Moves process statistics to stderr.
test/​IntegrationTests/​Microsoft.Testing.Platform.Acceptance.IntegrationTests/​DotnetTestPipe/​DotnetTestPipeListTestsJsonTests.cs Adds packed headless Unicode discovery coverage.

🧠 Review effort: Balanced


💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧪 Test quality review — PR #11896

🧵 Parallel safety

STATUS: CLEAN (delegated to the parallel-safety-reviewer specialist).

Test assembly Scope Workers
MSTest.Acceptance.IntegrationTests MethodLevel 0 (CPU count)
Microsoft.Testing.Platform.Acceptance.IntegrationTests MethodLevel 0 (CPU count)
MSTestAdapter.PlatformServices.UnitTests off (TestContainer/bespoke engine, no scheduler) n/a
Microsoft.Testing.Extensions.VSTestBridge.UnitTests MethodLevel 0 (CPU count)
Microsoft.Testing.Platform.UnitTests MethodLevel 0 (CPU count)

No Critical/High/Warning/Info findings. Notes from the specialist:

  • DesktopTestDataSourceTests's Path.Combine(AppContext.BaseDirectory, "DataTestSourceFile.xml") change reads a CopyToOutputDirectory=Always content file that both methods in the class only read; no writer collides, and the class runs under the parallelism-free TestContainer engine anyway.
  • NamedPipeServerSecurityTests.TryConnectManagedClientAs's new eager assembly-load (typeof(...).Assembly) is a helper, not a test method, and introduces no shared mutable state.
  • The new DotnetTestPipeListTestsJsonTests.ListTestsJson_HeadlessProcess_PreservesUnicode test and its fixture follow the repo's standard build-once, read-only TestAssetFixtureBase pattern already used by its sibling test in the same class.
  • The three Console.WriteLine → Console.Error.WriteLine changes only touch unreferenced diagnostic lines; no test asserts on their presence/absence in stdout.

Per-test assessment

ResultQualityTestNotesHow to improve
Pass B (80–89) mod DesktopTestDataSourceTests.
GetDataShould
SetDataConnectionInTest
ContextObject
One clear mock-verify assertion (`SetDataConnection` called once) protects the claimed behavior; only the fixture path changed. None
Pass A (90–100) mod DesktopTestDataSourceTests.
GetDataShouldRead
DataFromGivenDataSource
New `dataRows.Should().HaveCount(4)` now pins the row count (matches the 4 `` entries in the fixture) in addition to the per-row value check. None
Pass A (90–100) new DiscoveredTestsJsonSerializerTests.
Serialize_
NonAsciiCharacters_
ProducesLosslessAsciiJson
Exact-equality raw-string JSON assertion plus independent round-trip decode checks for both `uid` and `displayName`. None
Pass A (90–100) new DotnetTestPipeListTestsJsonTests.
ListTestsJson_
HeadlessProcess_
PreservesUnicode
Checks exit code, empty stderr, schema version, array length, and the exact unicode `uid`/`displayName` pair end-to-end through a real headless process. None

NamedPipeServerSecurityTests.TryConnectManagedClientAs (lines 939–944) is a static test helper invoked by existing tests, not a test method itself, so it is out of grading scope per Step 1 filtering; its only change is the assembly-preload fix described in the parallel-safety section above.

No inline suggestions were prepared: every graded test is Pass with no actionable improvement, and the parallel-safety result is CLEAN.

This advisory review is heuristic and non-blocking.

Re-run the combined review with /review-tests, or only the parallel-safety
specialist with /parallel-audit.

Warning

Firewall blocked 1 domain

The following domain was blocked by the firewall during workflow execution:

  • github.com

To allow these domains, add them to the network.allowed list in your workflow frontmatter:

network:
  allowed:
    - defaults
    - "github.com"

See Network Configuration for more information.

🤖 Automated content by GitHub Copilot. Generated by the Test Quality Review on PR (on open / sync) workflow. · copilot · auto · 226.6 AIC · ⌖ 10.1 AIC · ⊞ 20.8K · ◷

@microsoft-github-policy-service microsoft-github-policy-service Bot added state/needs-review Awaiting review from the team. and removed state/needs-review Awaiting review from the team. labels Oct 12, 2026
@github-actions github-actions Bot added state/needs-review Awaiting review from the team. and removed state/needs-review Awaiting review from the team. labels Oct 12, 2026
@microsoft-github-policy-service microsoft-github-policy-service Bot added state/needs-review Awaiting review from the team. and removed state/needs-review Awaiting review from the team. labels Oct 12, 2026
@github-actions github-actions Bot added state/approved Proposal approved; ready for implementation. and removed state/needs-review Awaiting review from the team. labels Oct 12, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Note

🤖 Automated review by GitHub Copilot. Generated by the Expert Code Review workflow. To request a follow-up action, reply by tagging @copilot directly.

Summary

Reviewed the full diff against the 22 dimensions (Algorithmic Correctness, Security/IPC, Public API, Performance, Cross-TFM, Resource Management, Defensive Coding, Localization, Test Isolation, Assertion Quality, Flakiness, Test Completeness, Code Structure, Documentation Accuracy, IPC Wire Compatibility, Scope Discipline, and others). This is a focused, well-scoped bugfix PR addressing three related headless/process-isolation defects uncovered by the affected-test collection workflow:

  1. JsonStringWriter non-ASCII escaping (src/Platform/Microsoft.Testing.Platform/OutputDevice/JsonStringWriter.cs) — now \u-escapes every character >= 0x7F (not just surrogate pairs and \u2028/\u2029), guarding against a legacy-console-encoding best-fit fallback corrupting Unicode (or worse, emitting raw control characters) when discovery runs in a headless Windows child process. Verified the schema/decoded values are unaffected — JsonDocument.Parse round-trips correctly in the new Serialize_NonAsciiCharacters_ProducesLosslessAsciiJson test, and the ASCII-only existing test (Serialize_DisplayNameWithSpecialCharacters_EscapesProperly) is unaffected since all its characters are < 0x7F.
  2. Console.WriteLine → Console.Error.WriteLine in three test-host Program.cs entry points — keeps stdout clean for the collection/affected-tests pipeline, which depends on an uncluttered stdout for --list-tests json. Confirmed via grep that no other test asserts on this stdout text, so this is safe.
  3. AppContainer pipe test preloading WindowsIdentity/GenericSecurityDescriptor assemblies before impersonation (NamedPipeServerSecurityTests.cs) — correctly addresses lazy assembly loading under a restricted token that can't read the desktop runtime install directory; preloading before ImpersonateLoggedOnUser is the right fix shape.
  4. DesktopTestDataSourceTests resolving the fixture via AppContext.BaseDirectory — fixes a working-directory-dependent test; verified DataTestSourceFile.xml has exactly 4 <settings> entries, matching the new HaveCount(4) assertion, and the project's .csproj already copies the file to output, so the fixture is actually present at that path.

All four fixes are independently verifiable, narrowly targeted, and backed by regression tests (Serialize_NonAsciiCharacters_ProducesLosslessAsciiJson unit test + ListTestsJson_HeadlessProcess_PreservesUnicode packed acceptance test) that exercise the actual failure mode rather than just the implementation detail. The doc update in docs/affected-test-selection.md accurately describes the headless-compatibility rationale and correctly cross-references the two key regression tests.

Dimension-by-dimension notes

  • Public API & Binary Compatibility: No public API surface touched; JsonStringWriter and DiscoveredTestsJsonSerializer are both internal. Clean.
  • IPC Wire Compatibility: The JSON schema (schemaVersion, field names, structure) is unchanged — only the character-escaping policy within string values changed, and \u-escaped non-ASCII is valid JSON that decodes identically. No consumer-visible breaking change.
  • Security: The NamedPipeServerSecurityTests.cs change strengthens (doesn't weaken) the AppContainer restricted-token test by ensuring assembly loads happen on the caller's (non-impersonated) identity rather than accidentally failing/short-circuiting the restricted-token validation. No regression in coverage — the actual connect/impersonate/deny logic is untouched.
  • Test Isolation / Flakiness: The AppContext.BaseDirectory-based path fix removes a cwd-dependent flakiness source; no new static mutable state or unguarded shared paths introduced.
  • Performance: JsonStringWriter's hot loop still does a single pass over the string with no added allocations beyond the pre-existing AppendUnicodeEscape calls (just invoked more often now).
  • Scope Discipline: All four changes are tightly related (headless/isolated-process correctness for the affected-tests collection path) and appropriately bundled as a single PR rather than scattered; no unrelated drive-by changes detected.

Minor suggestion (non-blocking)

Since JsonStringWriter is shipped product code in Microsoft.Testing.Platform and this change alters the --list-tests json output encoding for non-ASCII display names/UIDs (a user-observable behavior change, even though it's strictly loss-preventing), consider adding a docs/Changelog.md entry under the next unreleased ### Fixed section, consistent with how other behavior-affecting bugfixes in this repo are tracked. Not blocking since the fix is purely corrective (previously-corrupting data is now preserved) and well-documented in affected-test-selection.md.

No blocking issues found across the applicable review dimensions. Submitting as COMMENT (not APPROVE, per this workflow's restrictions).

@microsoft-github-policy-service microsoft-github-policy-service Bot added the state/needs-review Awaiting review from the team. label Oct 12, 2026
@github-actions github-actions Bot added state/approved Proposal approved; ready for implementation. and removed state/needs-review Awaiting review from the team. state/approved Proposal approved; ready for implementation. labels Oct 12, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Final test-triage resolution — Azure Pipelines build 1632088

Build 1632088 (PR #11896, head 1a29ef2b83a604e31278e9b4efa769f7c832cb92, merge b772e0cffa52ead6d70d9f1384152baf0a615bdb) completed with overall result succeeded. No build legs reported timeline failure/warning/retry signals, and there are no crash/hang diagnostics or slow-test regressions (0 slow regressions out of 55 slow-test candidates).

The only non-passed records in the normalized results are three intentional retry-validation test probes on the Windows App Model Diagnostics leg, each of which failed on attempt 1 and passed on a subsequent retry attempt within the same build:

  • WinUIMtpPackagedApp.UnitTest1.RetryFailsFirstAttempt — message: "This probe deliberately fails the first retry attempt and passes the next one." Failed attempt 1, passed attempts 2 and 3.
  • NativeTests.Outcome (NativeSidecar, multiple generated test-case instances) — message: "expected host failure" — a parameterized probe that fails on its first attempt in several instances and passes on retry.
  • PackagedWinUI.PackagedWinUITestCases.RetryTestMethod_PassesOnSecondAppContainerHost — message: "The first AppContainer host fails so Retry must activate a second host." Failed attempt 1, passed attempt 2.

These are self-tests of the MTP retry/AppContainer-host-recovery mechanism itself (test names and messages make the by-design fail-then-pass contract explicit), not product regressions. Cross-checking history.json (8 prior builds, flagged incomplete due to artifact-download/budget limits) shows the same tests following the identical fail-then-pass pattern on retry across multiple prior builds, with a consistent ~1:2 failed:passed ratio matching "attempt 1 fails, attempts 2+ pass" — reinforcing that this is expected, stable behavior rather than new flakiness.

Conclusion: No actionable test failure, flake, crash, or performance regression attributable to this PR's changes. No issue created.

🤖 Automated content by GitHub Copilot. Generated by the Pipeline Test Triage workflow. · copilot · auto · 51.2 AIC · ⌖ 7.34 AIC · ⊞ 9.9K

@Evangelink
Amaury Levé (Evangelink) merged commit f355efc into main Oct 12, 2026
37 checks passed
@Evangelink
Amaury Levé (Evangelink) deleted the dev/amauryleve/pipeline-test-fixes branch October 12, 2026 17:21
@github-actions github-actions Bot removed the state/approved Proposal approved; ready for implementation. label Oct 12, 2026
Amaury Levé (Evangelink) added a commit that referenced this pull request Oct 12, 2026
…11904)

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 230c0442-5e09-47eb-a28e-46dd66f7297f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants