Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion samples/WasiPlayground/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@
testApplicationBuilder.AddCrashDumpProvider();
// AddHangDumpProvider is intentionally not registered: hang dumps rely on
// System.Diagnostics.Process which is unsupported on wasi (see #8557).
testApplicationBuilder.AddAzureDevOpsProvider();
// AddAzureDevOpsProvider is intentionally not registered: its HttpClient sets
// AutomaticDecompression, which the wasi HttpClientHandler
// (System.Net.Http.WasiHttpHandler) does not support and throws
// PlatformNotSupportedException from its static initializer.
using ITestApplication testApplication = await testApplicationBuilder.BuildAsync();
return await testApplication.RunAsync();

Expand Down
57 changes: 43 additions & 14 deletions samples/WasiPlayground/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,25 +54,54 @@ Then:

## Status

After publishing, Microsoft.Testing.Platform now boots on `wasi-wasm` (the
banner reads `[wasi-wasm - net10.0]`) thanks to [#7137](https://github.com/microsoft/testfx/pull/7137).
Test execution itself currently fails with:
After publishing, Microsoft.Testing.Platform boots on `wasi-wasm` (the banner
reads `[wasi-wasm - net10.0]`) thanks to [#7137](https://github.com/microsoft/testfx/pull/7137),
and tests now **run to completion** end-to-end (issue
[#2196](https://github.com/microsoft/testfx/issues/2196)). Running this sample —
which hosts a `DummyFramework` with a single passing test — produces:

```console
Microsoft.Testing.Platform v2.3.0-dev (UTC ...) [wasi-wasm - net10.0]
Microsoft.Testing.Platform v2.4.0-dev (UTC ...) [wasi-wasm - net10.0]
...
Unhandled Exception:
System.PlatformNotSupportedException: Arg_PlatformNotSupported
at System.Threading.Tasks.Task.InternalWaitCore(...)
at System.Threading.Tasks.Task.InternalWait(...)
at Program.<Main>(String[] args)
/managed/WasiPlayground.dll (net10.0|wasi-wasm)
Test run summary: Passed!
total: 1
failed: 0
succeeded: 1
skipped: 0
```

The exception comes from the C# compiler's synthetic `Main` wrapper for
`async Task Main`, which calls `Task.GetAwaiter().GetResult()` &rarr;
`Task.Wait()`. On single-threaded `wasi-wasm` (no thread pool) this throws
`PlatformNotSupportedException`. Tracked in [#5366](https://github.com/microsoft/testfx/issues/5366)
so this sample can act as the canonical repro.
MSTest itself (not just the raw platform) also runs end-to-end on `wasi-wasm`;
that is covered by the gated `WasmExecutionTests.WasmExecution_RunsTestsUnderWasmtime`
acceptance test (see [`test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/WasmExecutionTests.cs`](../../test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/WasmExecutionTests.cs)),
which publishes a real MSTest project and runs it under `wasmtime`, plus an
always-on `WasmBuild_GeneratesTestingPlatformEntryPoint` test that guards the
build/entry-point plumbing on every CI leg.

### Why it works now

A user-authored `async Task Main` is fine on single-threaded `wasi-wasm`: the
compiler-synthesized entry point only blocks (`GetAwaiter().GetResult()`) if the
awaited task has not already completed, so as long as the pipeline never hops to
a background thread it completes synchronously and the wait is a no-op.

The real constraint is **threads**, not `async`/`await`. `wasi-wasm` links
wasi-emulated / synthetic pthreads, so there is no thread pool: `Task.Run`
continuations never execute and blocking waits throw
`PlatformNotSupportedException`. The platform and the MSTest adapter detect this
(`RuntimeFeatureHelper.IsMultiThreaded` / `RuntimeContext.IsMultiThreaded`,
derived from `OperatingSystem.IsWasi()`; .NET 11 will expose
`RuntimeFeature.IsMultithreadingSupported`, see
[dotnet/runtime#77541](https://github.com/dotnet/runtime/issues/77541)) and fall
back to inline/synchronous execution for the handful of thread-dependent spots on
the run path — the message-bus consumers, the shutdown watchdog, the telemetry
ingest loop, the countdown-event wait, and the adapter's per-test task factory.

Some **extensions** still have their own wasi limitations unrelated to threading:
this sample intentionally skips the hang-dump provider (relies on
`System.Diagnostics.Process`, see [#8557](https://github.com/microsoft/testfx/issues/8557))
and the Azure DevOps provider (its `HttpClient` sets `AutomaticDecompression`,
which the wasi `HttpClientHandler` does not support) — see `Program.cs`.

## Build configuration notes

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers;
using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Deployment;
using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Helpers;
Expand Down Expand Up @@ -63,6 +64,14 @@ private static Task DefaultFactoryAsync(Func<Task> taskGetter)
}
else
{
// On single-threaded wasm runtimes (browser-wasm / wasi-wasm) there is no thread pool, so
// Task.Run would offload to a queue that never runs and the awaiting caller would hang.
// Run inline instead; parallelism is irrelevant there since there is only one thread.
if (!RuntimeContext.IsMultiThreaded)
{
return taskGetter();
}

// NOTE: If you replace this with `return taskGetter()`, you will break parallel tests.
return Task.Run(taskGetter);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,24 @@ internal static class RuntimeContext
|| Environment.GetEnvironmentVariable("TESTINGPLATFORM_HOTRELOAD_ENABLED") == "1");

public static bool IsHotReloadEnabled => IsHotReloadEnabledLazy.Value;

/// <summary>
/// Gets a value indicating whether the current runtime supports multiple threads.
/// </summary>
/// <remarks>
/// Single-threaded WebAssembly runtimes (<c>browser-wasm</c> / <c>wasi-wasm</c>) have no thread
/// pool: <c>Task.Run</c> continuations never execute and blocking waits throw
/// <see cref="PlatformNotSupportedException"/>. Adapter code that would otherwise offload work to
/// a background thread (for parallelism) must run inline when this is <see langword="false"/>.
/// .NET 11 exposes <c>RuntimeFeature.IsMultithreadingSupported</c>
/// (see <see href="https://github.com/dotnet/runtime/issues/77541"/>); we derive the same signal
/// from the <see cref="OperatingSystem"/> probes available since .NET 8.
/// </remarks>
public static bool IsMultiThreaded { get; } =
Comment thread
Evangelink marked this conversation as resolved.
Resolved
#if NETCOREAPP
!OperatingSystem.IsBrowser() && !OperatingSystem.IsWasi();
#else
// .NET Framework / UWP / WinUI builds never run on a single-threaded wasm runtime.
true;
#endif
}
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
#nullable enable
static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers.RuntimeContext.IsMultiThreaded.get -> bool
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,14 @@ public AppInsightsProvider(
_payloads = new SingleConsumerUnboundedChannel<(string EventName, IDictionary<string, object> ParamsMap)>();
#endif

_telemetryTask = task.Run(IngestLoopAsync, _testApplicationCancellationTokenSource.CancellationToken);
// On single-threaded wasm runtimes (browser-wasm / wasi-wasm) there is no thread pool, so the
// background ingest loop (started via Task.Run) would never run and Dispose's blocking
// _telemetryTask.Wait(...) would throw PlatformNotSupportedException. Telemetry requires a
// background sender, so skip the loop entirely there and keep Dispose non-blocking by leaving
// the task completed. Events written via LogEventAsync are simply never shipped.
_telemetryTask = RuntimeFeatureHelper.IsMultiThreaded
? task.Run(IngestLoopAsync, _testApplicationCancellationTokenSource.CancellationToken)
: Task.CompletedTask;
Comment thread
Evangelink marked this conversation as resolved.
Resolved
_logger = loggerFactory.CreateLogger<AppInsightsProvider>();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,19 @@ public static async Task<bool> WaitAsync(this CountdownEvent countdownEvent, Tim
=> await countdownEvent.WaitAsync((uint)timeout.TotalMilliseconds, cancellationToken).ConfigureAwait(false);

internal static async Task<bool> WaitAsync(this CountdownEvent countdownEvent, uint millisecondsTimeOutInterval, CancellationToken cancellationToken)
=> OperatingSystem.IsBrowser()
? await countdownEvent.WaitBrowserAsync(millisecondsTimeOutInterval, cancellationToken).ConfigureAwait(false)
: await countdownEvent.WaitNonBrowserAsync(millisecondsTimeOutInterval, cancellationToken).ConfigureAwait(false);
// RuntimeFeatureHelper.IsMultiThreaded is false for both browser-wasm and wasi-wasm, so the
// multithreaded (thread-pool) path is never reached on browser. The analyzer can't see through
// the helper, so suppress the browser-unsupported warning here.
Comment thread
Evangelink marked this conversation as resolved.
Resolved
#pragma warning disable CA1416 // Validate platform compatibility
=> RuntimeFeatureHelper.IsMultiThreaded
? await countdownEvent.WaitMultiThreadedAsync(millisecondsTimeOutInterval, cancellationToken).ConfigureAwait(false)
: await countdownEvent.WaitSingleThreadedAsync(millisecondsTimeOutInterval, cancellationToken).ConfigureAwait(false);
#pragma warning restore CA1416 // Validate platform compatibility

private static async Task<bool> WaitBrowserAsync(this CountdownEvent countdownEvent, uint millisecondsTimeOutInterval, CancellationToken cancellationToken)
// Single-threaded runtimes (browser-wasm / wasi-wasm) have no thread pool, so
// ThreadPool.RegisterWaitForSingleObject (used by the multithreaded path) would register a
// callback that never fires. Poll the countdown cooperatively instead.
private static async Task<bool> WaitSingleThreadedAsync(this CountdownEvent countdownEvent, uint millisecondsTimeOutInterval, CancellationToken cancellationToken)
{
const int pollIntervalMs = 10;
uint elapsedMs = 0;
Expand All @@ -39,7 +47,8 @@ private static async Task<bool> WaitBrowserAsync(this CountdownEvent countdownEv
}

[UnsupportedOSPlatform("browser")]
private static async Task<bool> WaitNonBrowserAsync(this CountdownEvent countdownEvent, uint millisecondsTimeOutInterval, CancellationToken cancellationToken)
[UnsupportedOSPlatform("wasi")]
private static async Task<bool> WaitMultiThreadedAsync(this CountdownEvent countdownEvent, uint millisecondsTimeOutInterval, CancellationToken cancellationToken)
{
RegisteredWaitHandle? registeredHandle = null;
CancellationTokenRegistration tokenRegistration = default;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Microsoft.Testing.Platform.Helpers;

/// <summary>
/// Runtime feature detection that the platform uses to adapt its behavior to the host.
/// </summary>
internal static class RuntimeFeatureHelper
{
/// <summary>
/// Gets a value indicating whether the current runtime supports multiple threads.
/// </summary>
/// <remarks>
/// Single-threaded WebAssembly runtimes (<c>browser-wasm</c> and <c>wasi-wasm</c>) do not have a
/// thread pool: <see cref="System.Threading.Tasks.Task.Run(System.Action)"/> continuations never
/// execute while the single thread is busy, and blocking waits
/// (<c>Task.Wait</c> / <c>GetAwaiter().GetResult()</c> on an incomplete task) throw
/// <see cref="PlatformNotSupportedException"/>. Code that would otherwise offload work to a
/// background thread MUST fall back to inline/synchronous execution when this returns
/// <see langword="false"/>, otherwise the operation deadlocks or throws.
/// <para>
/// .NET 11 exposes <c>System.Runtime.CompilerServices.RuntimeFeature.IsMultithreadingSupported</c>
/// for exactly this purpose (see <see href="https://github.com/dotnet/runtime/issues/77541"/>),
/// but the platform still targets earlier frameworks, so we derive the same information from the
/// <see cref="OperatingSystem"/> single-threaded-wasm probes, which are available since .NET 8.
/// </para>
/// </remarks>
public static bool IsMultiThreaded { get; } =
#if NETCOREAPP
!OperatingSystem.IsBrowser() && !OperatingSystem.IsWasi();
Comment thread
Evangelink marked this conversation as resolved.
Resolved
#else
// netstandard2.0 / .NET Framework builds never run on a single-threaded wasm runtime.
true;
#endif
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
#nullable enable
Microsoft.Testing.Platform.Helpers.RuntimeFeatureHelper
static Microsoft.Testing.Platform.Helpers.RuntimeFeatureHelper.IsMultiThreaded.get -> bool
const Microsoft.Testing.Platform.ServerMode.JsonRpcStrings.IsStateful = "isStateful" -> string!
Microsoft.Testing.Platform.ServerMode.ClientCapabilities.ClientCapabilities(bool DebuggerProvider, bool IsStateful) -> void
Microsoft.Testing.Platform.ServerMode.ClientCapabilities.Deconstruct(out bool DebuggerProvider, out bool IsStateful) -> void
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,11 @@ public override async Task InitAsync()
// A consumer that implements the IBlockingDataConsumer marker interface must consume the data
// inline (the publisher blocks until consumption completes) instead of going through the
// asynchronous background processing loop.
asyncMultiProducerMultiConsumerDataProcessor = consumer is IBlockingDataConsumer
//
// On single-threaded wasm runtimes (browser-wasm / wasi-wasm) there is no thread pool, so the
// AsyncConsumerDataProcessor background loop (started via Task.Run) would never run and the
// drain would hang. Force inline consumption for every consumer in that case.
asyncMultiProducerMultiConsumerDataProcessor = consumer is IBlockingDataConsumer || !RuntimeFeatureHelper.IsMultiThreaded
? new BlockingConsumerDataProcessor(consumer, _testApplicationCancellationTokenSource.CancellationToken)
: new AsyncConsumerDataProcessor(consumer, _task, _testApplicationCancellationTokenSource.CancellationToken);
_consumerProcessor.Add(consumer, asyncMultiProducerMultiConsumerDataProcessor);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,14 @@ private void OnCancellationRequested()
// _watchdogStopSource) cannot turn the Task.Run lambda into an ObjectDisposedException.
CancellationToken stopToken = _watchdogStopSource.Token;

// The watchdog is a best-effort diagnostic that reports slow shutdown from a background
// thread. Single-threaded wasm runtimes have no thread pool, so Task.Run would never run the
// watchdog loop (and awaiting it later would hang); skip it entirely there.
if (!RuntimeFeatureHelper.IsMultiThreaded)
{
return;
}

// Fire-and-forget watchdog. The process is shutting down, so we accept the unobserved task.
_ = Task.Run(() => RunWatchdogAsync(stopToken));
}
Expand Down
Loading
Loading