Skip to content

Enable MSTest/MTP test execution on wasi-wasm (#2196) - #9781

Merged
Amaury Levé (Evangelink) merged 7 commits into
mainfrom
dev/amauryleve/wasm-test-execution
Jul 9, 2026
Merged

Amaury Levé (Evangelink) merged 7 commits into
mainfrom
dev/amauryleve/wasm-test-execution

Conversation

@Evangelink

Copy link
Copy Markdown
Member

Summary

Enables running MSTest tests end-to-end in WebAssembly from a console host, using wasi-wasm as a headless proxy for browser-wasm (both share the same single-threaded execution model). Fixes the core platform work tracked by #2196.

The wasm expert's guidance was the key insight: async Main is fine; threads are not. A user-authored async Task Main completes cleanly on single-threaded wasm as long as the pipeline never hops to a background thread — the compiler's synthetic entry point only blocks (GetAwaiter().GetResult()) when the awaited task hasn't already completed. The real blockers were a handful of thread-dependent spots on the run path, since single-threaded wasm has no thread pool (Task.Run continuations never execute and blocking waits throw PlatformNotSupportedException).

Approach

Add a single-threaded-wasm detection and fall back to inline/synchronous execution when threading is unavailable:

  • RuntimeFeatureHelper.IsMultiThreaded (platform) and RuntimeContext.IsMultiThreaded (adapter) — derived from OperatingSystem.IsWasi()/IsBrowser() (available since .NET 8). Both document that .NET 11's RuntimeFeature.IsMultithreadingSupported (dotnet/runtime#77541) is the future canonical API.

Fixes (all gated on single-threaded wasm — multi-threaded behavior is unchanged)

Component Change
AsynchronousMessageBus Use the inline BlockingConsumerDataProcessor for all consumers (the Task.Run background consumer loop never ran).
CountDownEventExtensions.WaitAsync Use the cooperative poll path (previously browser-only) instead of ThreadPool.RegisterWaitForSingleObject, whose callback never fires on wasi.
AppInsightsProvider Skip the background ingest Task.Run so Dispose's blocking .Wait() is a no-op.
ShutdownProgressReporter Skip the Task.Run watchdog.
TestExecutionManager.DefaultFactoryAsync Run inline instead of Task.Run (parallelism is irrelevant on a single thread).

Tests

New WasmExecutionTests acceptance coverage:

  • WasmBuild_GeneratesTestingPlatformEntryPoint — always-on; asserts a wasi-wasm MSTest project builds and the MTP entry point is generated (only needs the wasi-experimental workload the bootstrap installs).
  • WasmExecution_RunsTestsUnderWasmtime — publishes a real MSTest wasi-wasm project and runs it end-to-end under wasmtime, asserting the passing tests report success, the failing test is reported failed, and there's no PlatformNotSupportedException. Skipped (inconclusive) when the wasm-tools workload or wasmtime is unavailable, so it only runs where the wasm runtime exists.

Validation

  • Acceptance tests pass under wasmtime (2 succeeded, 1 failed, non-zero exit) and skip cleanly without it.
  • Manual end-to-end run: Test run summary: Passed!, exit code 0.
  • Platform unit tests: 1287/1287 pass. Adapter unit tests: 898/898 pass.
  • Full build+pack: 0 warnings, 0 errors. No public API or localization changes (all additions are internal).

Follow-up (not in this PR)

The gated execution test skips everywhere without the toolchain. To exercise it in CI, a Linux leg would need to install the wasm-tools workload + wasmtime. Happy to wire that pipeline change in a follow-up.

Single-threaded WebAssembly runtimes (wasi-wasm / browser-wasm) have no thread
pool: Task.Run continuations never execute and blocking waits throw
PlatformNotSupportedException. A user-authored async Main is fine as long as the
pipeline completes without hopping to a background thread; the blockers were a
handful of thread-dependent spots on the run path.

Add a single-threaded-wasm detection (RuntimeFeatureHelper.IsMultiThreaded in the
platform, RuntimeContext.IsMultiThreaded in the adapter; derived from
OperatingSystem.IsWasi()/IsBrowser(), noting net11 RuntimeFeature.IsMultithreadingSupported)
and fall back to inline/synchronous execution when threading is unavailable:

- AsynchronousMessageBus: inline BlockingConsumerDataProcessor for all consumers.
- CountDownEventExtensions.WaitAsync: cooperative poll path (previously browser-only)
  instead of ThreadPool.RegisterWaitForSingleObject.
- AppInsightsProvider: skip the background ingest Task.Run so Dispose does not block.
- ShutdownProgressReporter: skip the Task.Run watchdog.
- TestExecutionManager.DefaultFactoryAsync: run inline instead of Task.Run.

Multi-threaded behavior is unchanged (the fallbacks only trigger on single-threaded
wasm). Add WasmExecutionTests acceptance coverage: an always-on build assertion plus
a gated end-to-end run under wasmtime (skipped when the wasm-tools workload/wasmtime
are absent). Update the WasiPlayground sample README to reflect that execution now
works.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI review requested due to automatic review settings July 9, 2026 12:43

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR enables MSTest/MTP tests to run end-to-end on single-threaded WebAssembly, using wasi-wasm as a headless stand-in for browser-wasm (both share a no-thread-pool execution model), addressing issue #2196. The insight is that a user-authored async Task Main is fine on single-threaded wasm as long as the pipeline never hops to a background thread; the fix adds a runtime capability probe and falls back to inline/synchronous execution at the handful of thread-dependent spots on the run path. All behavioral changes are gated so multi-threaded runtimes are unaffected.

Changes:

  • Adds two IsMultiThreaded capability probes — RuntimeFeatureHelper (platform) and RuntimeContext (adapter) — derived from OperatingSystem.IsBrowser()/IsWasi().
  • Gates five thread-dependent code paths on the probe: message-bus consumers (force inline), shutdown watchdog (skip), telemetry ingest loop (skip, keep Dispose non-blocking), countdown-event wait (cooperative poll), and the adapter's per-test task factory (run inline).
  • Adds WasmExecutionTests acceptance coverage (always-on build assertion + gated wasmtime end-to-end run) and updates the WasiPlayground README.
Show a summary per file
File Description
src/Platform/Microsoft.Testing.Platform/Helpers/RuntimeFeatureHelper.cs New internal platform-side single-threaded-wasm capability probe.
src/Adapter/MSTestAdapter.PlatformServices/Helpers/RuntimeContext.cs Adds the adapter-side IsMultiThreaded counterpart.
src/Platform/Microsoft.Testing.Platform/Messages/AsynchronousMessageBus.cs Forces inline (BlockingConsumerDataProcessor) consumption on single-threaded wasm.
src/Platform/Microsoft.Testing.Platform/Services/ShutdownProgressReporter.cs Skips the fire-and-forget Task.Run watchdog when threading is unavailable.
src/Platform/Microsoft.Testing.Extensions.Telemetry/AppInsightsProvider.cs Uses Task.CompletedTask instead of the background ingest loop so Dispose's blocking wait is a no-op.
src/Platform/Microsoft.Testing.Platform/Helpers/CountDownEventExtensions.cs Renames browser/non-browser wait paths to single/multi-threaded and routes via the probe (with a scoped CA1416 suppression).
src/Adapter/MSTestAdapter.PlatformServices/Execution/TestExecutionManager.cs Runs the per-test task inline instead of Task.Run on single-threaded wasm.
test/IntegrationTests/.../WasmExecutionTests.cs New acceptance tests: always-on build/entry-point check and a gated wasmtime end-to-end run.
samples/WasiPlayground/README.md Updates status to reflect working end-to-end execution and explains the threading fixes.

Review details

  • Files reviewed: 9/9 changed files
  • Comments generated: 0
  • Review effort level: Medium

@github-actions

This comment has been minimized.

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

Review Summary

Solid PR. The single-threaded-wasm detection is clean, the fallbacks are correctly guarded, and the logic inversions from IsBrowser() → IsMultiThreaded are all correct. No blocking or major issues found.

Dimension Verdicts

# Dimension Verdict
1 Algorithmic Correctness ✅ LGTM
2 Threading & Concurrency ✅ LGTM
3 Security & IPC Contract Safety ⊘ N/A
4 Public API & Binary Compatibility ✅ LGTM
5 Performance & Allocations ✅ LGTM
6 Cross-TFM Compatibility ✅ LGTM
7 Resource & IDisposable Management ✅ LGTM
8 Defensive Coding at Boundaries ✅ LGTM
9 Localization & Resources ⊘ N/A
10 Test Isolation ✅ LGTM
11 Assertion Quality ✅ LGTM
12 Flakiness Patterns ✅ LGTM
13 Test Completeness & Coverage ✅ LGTM
14 Data-Driven Test Coverage ⊘ N/A
15 Code Structure & Simplification ✅ LGTM
16 Naming & Conventions ✅ LGTM
17 Documentation Accuracy ✅ LGTM
18 Analyzer & Code Fix Quality ⊘ N/A
19 IPC Wire Compatibility ⊘ N/A
20 Build Infrastructure & Dependencies ⊘ N/A
21 Scope & PR Discipline ✅ LGTM
22 PowerShell Scripting Hygiene ⊘ N/A

Notes

  • CA1416 suppression (CountDownEventExtensions.cs): Justified and narrowly scoped. RuntimeFeatureHelper.IsMultiThreaded is false for both browser and wasi, so WaitMultiThreadedAsync (annotated [UnsupportedOSPlatform("browser")]) is unreachable on browser. The analyzer can't infer this through the helper, so the pragma is the correct solution.
  • [UnsupportedOSPlatform("browser")] on WaitMultiThreadedAsync: Could additionally be annotated with [UnsupportedOSPlatform("wasi")] for documentary completeness (the method uses ThreadPool.RegisterWaitForSingleObject which would also fail on wasi). Low priority since the method is private and the runtime guard already prevents calls on both platforms.
  • Test asset Assert.IsTrue(true): This is the wasm test asset, not the acceptance test itself — it intentionally exercises minimal passing assertions to validate the wasm pipeline, not production logic. Acceptable as-is.
  • GenerateWasmAssetAsync parallel safety: Both test methods use the same asset name "WasmTestProject", but TempDirectory.CreateUniqueDirectory generates a random path via RandomId.Next(), so parallel execution is safe.

No action required — clean to merge.

Copilot AI review requested due to automatic review settings July 9, 2026 16:36
@github-actions

This comment has been minimized.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review details

  • Files reviewed: 9/9 changed files
  • Comments generated: 3
  • Review effort level: Medium

Comment thread samples/WasiPlayground/README.md Resolved
@github-actions

github-actions Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

🔍 Build Failure Analysis

Summary — New internal API members (RuntimeFeatureHelper and RuntimeContext.IsMultiThreaded) were not declared in InternalAPI.Unshipped.txt, causing RS0051 errors across 2 projects (cascading to 2 more).

Root cause: Missing InternalAPI.Unshipped.txt entries (RS0051)

The PR introduces a new internal static class RuntimeFeatureHelper in Microsoft.Testing.Platform and adds a public static bool IsMultiThreaded property to the existing internal static class RuntimeContext in MSTestAdapter.PlatformServices. Both classes are internal, but the repo tracks internal API surface via RS0051. The new symbols must be listed in the appropriate InternalAPI.Unshipped.txt files.

Affected files / errors

# File Error
1 RuntimeFeatureHelper.cs:9 RS0051: Symbol 'Microsoft.Testing.Platform.Helpers.RuntimeFeatureHelper' is not part of the declared API
2 RuntimeFeatureHelper.cs:29 RS0051: Symbol 'static ...RuntimeFeatureHelper.IsMultiThreaded.get -> bool' is not part of the declared API
3 RuntimeContext.cs:27 RS0051: Symbol 'static ...RuntimeContext.IsMultiThreaded.get -> bool' is not part of the declared API (×2, once per TFM)

Proposed fix

Add the missing entries to three InternalAPI.Unshipped.txt files:

1. src/Platform/Microsoft.Testing.Platform/InternalAPI/InternalAPI.Unshipped.txt

 #nullable enable
+Microsoft.Testing.Platform.Helpers.RuntimeFeatureHelper
 static Microsoft.Testing.Platform.IPC.Serializers.BaseSerializer.ReadFields(System.IO.Stream! stream, System.Func<ushort, int, bool>! tryReadField) -> void
 static Microsoft.Testing.Platform.IPC.Serializers.BaseSerializer.WriteListPayload<T>(System.IO.Stream! stream, ushort fieldId, T[]? list, System.Action<System.IO.Stream!, T>! writeItem) -> void
+static Microsoft.Testing.Platform.Helpers.RuntimeFeatureHelper.IsMultiThreaded.get -> bool

2. src/Platform/Microsoft.Testing.Platform/InternalAPI/net/InternalAPI.Unshipped.txt — same additions as above.

3. src/Adapter/MSTestAdapter.PlatformServices/InternalAPI/InternalAPI.Unshipped.txt

 #nullable enable
+static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers.RuntimeContext.IsMultiThreaded.get -> bool

Cascading failures

Microsoft.Testing.Extensions.AzureFoundry.csproj also failed because it depends on Microsoft.Testing.Platform which did not produce a valid output. No additional fix needed — resolving the RS0051 errors fixes it.


Build overview
Metric Value
Status ❌ FAILED
Duration 195.2 s
Projects 49
Errors 5 (4 distinct RS0051 + 1 "Build failed")
Warnings 0

Failed projects:

  • Microsoft.Testing.Platform.csproj — 2 RS0051 errors (new RuntimeFeatureHelper class + property)
  • MSTestAdapter.PlatformServices.csproj — 2 RS0051 errors (new RuntimeContext.IsMultiThreaded, one per TFM)
  • Microsoft.Testing.Extensions.AzureFoundry.csproj — cascading (depends on MTP)
  • Build.proj / NonWindowsTests.slnf — top-level orchestration failure
All MSBuild errors (5)
Code Project File:Line Message
RS0051 Microsoft.Testing.Platform RuntimeFeatureHelper.cs:9 Symbol RuntimeFeatureHelper is not part of the declared API
RS0051 Microsoft.Testing.Platform RuntimeFeatureHelper.cs:29 Symbol RuntimeFeatureHelper.IsMultiThreaded.get -> bool is not part of the declared API
RS0051 MSTestAdapter.PlatformServices RuntimeContext.cs:27 Symbol RuntimeContext.IsMultiThreaded.get -> bool is not part of the declared API
RS0051 MSTestAdapter.PlatformServices RuntimeContext.cs:27 Symbol RuntimeContext.IsMultiThreaded.get -> bool is not part of the declared API (2nd TFM)
— Build.proj — Build failed.

🤖 Generated by the Build Failure Analysis workflow using binlog-mcp · commit 99deca0

🤖 Automated content by GitHub Copilot. Generated by the Build Failure Analysis workflow. · 164.8 AIC · ⌖ 7.99 AIC · ⊞ 7.3K · [◷]( · ◷)

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🤖 Automated content by GitHub Copilot. Generated by the Build Failure Analysis workflow. · 164.8 AIC · ⌖ 7.99 AIC · ⊞ 7.3K · ◷

- Declare RuntimeFeatureHelper and RuntimeContext.IsMultiThreaded in the
  InternalAPI.Unshipped.txt files (fixes the RS0016/RS0051 build failure).
- WasiPlayground: drop AddAzureDevOpsProvider (its HttpClient sets
  AutomaticDecompression, unsupported by the wasi HttpClientHandler), mirroring
  the existing hang-dump exclusion, so the sample runs green on wasi.
- README: show the actual WasiPlayground sample output (DummyFramework, 1 passing
  test) instead of the acceptance-test asset output, and note the extension-level
  wasi limitations.
- Annotate CountDownEventExtensions.WaitMultiThreadedAsync with
  [UnsupportedOSPlatform("wasi")] for documentary completeness.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI review requested due to automatic review settings July 9, 2026 17:03

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review details

  • Files reviewed: 12/12 changed files
  • Comments generated: 2
  • Review effort level: Medium

@github-actions

This comment has been minimized.

@Evangelink
Amaury Levé (Evangelink) enabled auto-merge (squash) July 9, 2026 17:20
@Evangelink Amaury Levé (Evangelink) added the state/needs-review Awaiting review from the team. label Jul 9, 2026
.editorconfig enforces charset = utf-8-bom for *.cs; the two newly added files
(RuntimeFeatureHelper.cs, WasmExecutionTests.cs) were missing it.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI review requested due to automatic review settings July 9, 2026 17:20

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review details

  • Files reviewed: 12/12 changed files
  • Comments generated: 0 new
  • Review effort level: Medium

@github-actions

This comment has been minimized.

# Conflicts:
#	src/Platform/Microsoft.Testing.Platform/InternalAPI/InternalAPI.Unshipped.txt
Copilot AI review requested due to automatic review settings July 9, 2026 19:04

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review details

  • Files reviewed: 12/12 changed files
  • Comments generated: 0 new
  • Review effort level: Medium

Copilot AI review requested due to automatic review settings July 9, 2026 19:10
@github-actions

This comment has been minimized.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review details

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

Short-circuit LogEventAsync when !RuntimeFeatureHelper.IsMultiThreaded so events are not queued into the unbounded channel with no consumer draining it.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI review requested due to automatic review settings July 9, 2026 19:56

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review details

  • Files reviewed: 12/12 changed files
  • Comments generated: 1
  • Review effort level: Medium

@github-actions

github-actions Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

🧪 Test quality grade — PR #9781

GradeTestNotes
A (90–100) new WasmExecutionTests.
WasmBuild_
GeneratesTestingPlatformEntryPoint
Asserts exit-code success and MTP entry-point file presence; clean AAA for an always-on build guard.
A (90–100) new WasmExecutionTests.
WasmExecution_
RunsTestsUnderWasmtime
Four complementary assertions (no crash, pass/fail counts, exit code); environment skip guards via Assert.Inconclusive are clean.

This advisory comment was generated automatically. Grades are heuristic
and informational — they do not block merging. Re-run with
/grade-tests.

🤖 Automated content by GitHub Copilot. Generated by the Grade Tests on PR (on open / sync) workflow. · 97.4 AIC · ⌖ 11.7 AIC · ⊞ 9.5K · [◷]( · ◷)

@Evangelink
Amaury Levé (Evangelink) merged commit 3a9976a into main Jul 9, 2026
49 checks passed
@Evangelink
Amaury Levé (Evangelink) deleted the dev/amauryleve/wasm-test-execution branch July 9, 2026 21:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

state/needs-review Awaiting review from the team.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants