Skip to content

fix(webgpu): Survive a lost device - #26088

Open
MartinZikmund wants to merge 2 commits into
masterfrom
dev/mazi/webgpu-device-lost
Open

MartinZikmund wants to merge 2 commits into
masterfrom
dev/mazi/webgpu-device-lost

Conversation

@MartinZikmund

Copy link
Copy Markdown
Member

GitHub Issue: closes #26086

PR Type:

🐞 Bugfix

What changed? 🚀

Symptom. With the WebGPU renderer on a native host, a lost GPU device kills the process. On CI, Android WebGPU shard 2 of build 243859 (artifact runtime-tests-android-skia-webgpu-results) aborted in wgpuSurfaceGetCurrentTexture, and the shard lost all its results.

Cause. wgpu-native answers an error from some calls with a panic, and a panic can't cross into managed code, so the process aborts. try/catch can't help. From the v29.0.1.1 source, those calls include wgpuSurfaceGetCurrentTexture, wgpuQueueSubmit, wgpuQueueSubmitForIndex, wgpuSurfaceConfigure, wgpuDevicePoll, wgpuBufferGetMappedRange and the discard inside wgpuTextureRelease.

The lost-device callback didn't protect anything. It only logged, and wgpu-native fires it only when a non-fatal call runs into the loss, not when the loss happens. That's why the CI log has no device lost line before the panic.

Invariant. No call that wgpu-native treats as fatal reaches a device known to be lost.

Fix (root-cause fix for that invariant).

  • The guards sit in the SilkCompat table that every WebGPU call goes through, so all native hosts and WebGpuCanvasElement code get them. The browser path is unchanged: it doesn't panic, and non-recovery there stays with WebGPU on WASM never recovers from a lost device: rendering and RenderTargetBitmap stay dead #25361.
  • Before a fatal call, a probe creates and releases a command encoder. That's a non-fatal call that reports a loss synchronously through the callback. It cost about 0.39 µs here (Vulkan on a discrete GPU), a few times per frame. The Android emulator will be slower; that wasn't measured.
  • Once lost: submits and surface configuration are skipped, acquire returns a failed status, Present stops without asking for a retry, and a readback returns a blank image. The loss is logged once and later errors are silenced.
  • An acquired texture that was never presented is deliberately leaked once the device is lost, because releasing it panics.

Trigger mitigation (defensive hardening, not validated). The crash also shows the UI thread in wgpuQueueSubmit, which looks like a readback racing the render thread. gfx-rs/wgpu#9029 makes the Vulkan acquire report a fence wait over one second as a lost device. On software Vulkan, submissions now wait while the render thread polls and acquires, so another thread's work can't queue up in front of the acquire.

What this does not cover. Please read this part.

  • A loss first discovered inside a fatal call still aborts, and that may well be what happened in this CI crash. The first panic comes from the acquire itself, and the wait in fix: Solve PaddingMask.Top with StatusBarTranslucent #9029 is inside that call, so no check beforehand can see it. I inferred that from the source and the log; I didn't reproduce it. The mitigation above makes that stall less likely but can't rule it out. Removing it needs a change in wgpu or wgpu-native (fix: Solve PaddingMask.Top with StatusBarTranslucent #9029 is still open and unfixed on wgpu trunk).
  • There is still a window between the probe and the native call. A loss from another thread in that gap still aborts. Submissions are serialized with each other, but non-fatal calls on other threads can still lose the device there.
  • A pending map still polls natively so its waiter can finish, and that poll can panic on a real GPU loss.
  • wgpuBufferGetConstMappedRange and render bundle encoders aren't guarded. Uno doesn't call them, but app code could.
  • No recovery: rendering stays stopped until the app restarts. Recovery stays with WebGPU on WASM never recovers from a lost device: rendering and RenderTargetBitmap stay dead #25361.
  • Why the device was lost on the emulator remains unproven.

Validation.

  • Runtime, negative control: When_Device_Is_Lost_Then_Process_Survives destroys the device in a child process with wgpuDeviceDestroy, then renders, takes a screenshot and resizes the window. Without the fix the child died with exit code 0xC0000409 and Error in wgpuQueueSubmit: Validation Error ... Parent device is lost, the same panic as CI, and the test failed.
  • Runtime, with the fix: Windows desktop, UNO_WEBGPU=1, Vulkan on a discrete GPU. Given_WebGpuCanvasElement passed 3/3, child exit code 0, no panics, and one device lost line. A subset of Given_DrawingBackend_Conformance and Given_RenderTargetBitmap gave 14 passed and 1 inconclusive of 15. That run was on the final fix commit; only the test's child-launch code changed after it.
  • Compile: Uno.UI.Composition.WebGpu.Init and Uno.UI.Composition.WebGpu build with analyzers on; the desktop SamplesApp builds with UnoFastDevBuild.
  • Code review: the wgpu-native v29.0.1.1 and wgpu-core 29.0.1 sources for the fatal paths and when the callback fires.
  • Not validated locally: Android, including the mitigation (no local run; Uno.UI.Runtime.Android didn't build here because of a missing workload, and no Android files changed). Also macOS, Linux and iOS. D3D12: with UNO_WEBGPU_BACKENDS=dx12 the app fails in startup on this machine, with or without the fix, so that backend wasn't exercised. The new test only runs on desktop, since Android can't spawn the child process. One clean CI run won't prove the mitigation either, because the crash is intermittent.

PR Checklist ✅

🤖 Generated with Claude Code

https://claude.ai/code/session_01TXMNtyBVZWdemP5ouF7UUA

MartinZikmund and others added 2 commits November 5, 2026 10:41
wgpu-native panics on an error from a few of its calls, which aborts the
process, and its lost callback only fires when a non-fatal call hits the
loss. Probe for the loss before those calls and skip them once it is known.

Keep submissions out of the software-Vulkan poll and acquire, since queued
work can push the acquire past the one second wgpu reports as a loss.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TXMNtyBVZWdemP5ouF7UUA
Copilot AI balanced review requested due to automatic review settings November 5, 2026 09:45
@github-actions github-actions Bot added the area/skia ✏️ Categorizes an issue or PR as relevant to Skia label Nov 5, 2026
@github-actions

github-actions Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @MartinZikmund's task in 38s —— View job


Review summary

Verdict: ship after small fixes. The root-cause approach (probe, then guard fatal calls in the SilkCompat table) fits the stated invariant. The PR description is candid about what it leaves uncovered.

Issues: 0 blocking, 2 medium, 2 minor. All are posted inline.

Cross-cutting notes

  • Static residual risk. A loss first discovered inside a fatal call can still abort, as can a loss in the window between the probe and the native call. The PR already says so, and I agree with that framing. The fix is a mitigation, not a full resolution, so keep WebGPU on WASM never recovers from a lost device: rendering and RenderTargetBitmap stay dead #25361 and the wgpu upstream tracking open.
  • Runtime validation. Windows desktop only, as the PR states. Android, which is the CI crash platform, was not validated, and the new test skips it.
  • Review method. This was a static review. I did not build or run anything.

{
if (RuntimeTestsBackendHelper.CurrentBackend != RuntimeTestBackends.WebGpu)
{
Assert.Inconclusive("Requires the WebGPU backend.");

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.

Inconclusive in the child scenario. Assert.Inconclusive hides a regression instead of surfacing it. The parent already checks the backend at line 65, and the child inherits the environment, so this check can't fire legitimately. If the child somehow isn't on WebGPU, the scenario exercises nothing and the parent can still see passed="1". Check the backend in the parent only and use Assert.Fail here, or drop this check.

Separately, passed="1" (line 71 here) is a brittle match on the results XML format.

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 panel: this doesn't hold for the child. The results XML counts passes and inconclusive results separately (passed comes from Succeeded only, in UnitTestsControl.cs), so an inconclusive child writes passed="0" and the parent's passed="1" check fails visibly. The match is fragile only in the fail-loud direction.

The parent's own Assert.Inconclusive gate is a different matter. Nothing in CI watches inconclusive results, and [BackendCondition(ConditionMode.Include, RuntimeTestBackends.WebGpu)] gates the test explicitly.


private sealed unsafe class DeviceDestroyingWebGpuCanvasElement : WebGpuCanvasElement
{
public bool DeviceDestroyed { get; private set; }

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.

DeviceDestroyed is written on the render thread and polled from the UI thread via WaitFor, with no memory barrier. Use a volatile backing field. It works in practice, but it is a data race by the book.

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 panel: this one doesn't hold. RenderOverride is called from WebGpuCanvasElement.Paint, which runs while the frame is recorded on the UI thread, and the test class is [RunsOnUIThread]. So WaitFor polls from the same thread that sets the flag.

// device (gfx-rs/wgpu#9029), from inside a call that then panics. On a CPU rasterizer the work ahead of the
// acquire can take longer than that (the Android emulator's SwiftShader, which compiles each shader on first
// use), so let it finish first, and keep other threads' renders from queueing in front of the acquire.
lock (Xlate.SubmissionGate)

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.

SubmissionGate is held across a blocking DevicePoll(wait: true). On software Vulkan, any other thread that submits (for example the UI thread doing a screenshot readback) blocks in GuardedQueueSubmit for as long as the render thread's outstanding work takes. On the emulator that includes SwiftShader shader compiles, so it can be seconds. This is defensive hardening, and it trades a possible panic for a possible UI-thread stall that has no timeout. Please note this in the PR, or say why it is acceptable. Also consider whether _pendingMaps / SubmissionGate ordering can deadlock when the UI thread holds a pending map and waits on a poll while this thread holds the gate. I found no cycle, but it deserves 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 panel: the stall is real but not new. wgpu-core's blocking poll already holds the device's fence lock while it waits (Device::maintain), the acquire takes the same lock, and a submit needs it for writing. So other threads' submits already waited out the poll; the gate adds the acquire to that wait. We found no lock cycle.

What's unproven is that the gate prevents the loss. It would be easier to judge as its own commit, with the poll and acquire timed on the emulator.

// whose implementation reports errors instead of panicking.
private static nint _device;
private static int _deviceLost;
private static int _pendingMaps;

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.

_device is a plain nint static written from the native request-device callback and read from the render and UI threads. It is only a single word, but make it Volatile-accessed like _deviceLost. Also, the file is #nullable disable and all the guards depend on _device having been set by OnDevice only for the first device. If a second device is ever requested, the "one device per process" assumption silently breaks the probe. An assertion or a comment at the assignment would help.

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 panel: the missing volatile isn't a problem in itself. It's one word, and Uno's device sets it once, synchronously, inside GetShared's lock. The second half is the real issue: nothing enforces one device per process. Details on the OnDevice thread.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Two critical issues remain: polling can reach a fatal native call before detecting device loss, and unrelated device requests can corrupt the shared renderer’s loss tracking or leave a stale pointer.

2 open issues
What changed in this PR

Adds native WebGPU device-loss protection for #26086 so detected losses stop rendering rather than aborting the process. Recovery and losses first discovered inside fatal native calls remain outside this fix.

Changes:

  • Adds shared API guards, loss tracking, and one-time loss reporting.
  • Adjusts presentation, texture cleanup, and readback behavior after loss, and serializes software-Vulkan acquisition with submissions.
  • Adds a desktop child-process regression test for device destruction.
File Description
src/​Uno.UI.RuntimeTests/​Microsoft/​UI/​Xaml/​Controls/​Given_WebGpuCanvasElement.skia.cs Tests process survival after device destruction.
src/​Uno.UI.Composition.WebGpu/​WebGpuDevice.cs Returns a blank readback when no mapped range is available.
src/​Uno.UI.Composition.WebGpu.Init/​WebGpuSwapChainContext.cs Stops presentation after loss and protects acquisition and cleanup.
src/​Uno.UI.Composition.WebGpu.Init/​WebGpuInit.Core.cs Clarifies that device loss stops rendering without recovery.
src/​Uno.UI.Composition.WebGpu.Init/​SilkCompat/​SilkCompatContext.cs Registers device-loss guards in the API table.
src/​Uno.UI.Composition.WebGpu.Init/​SilkCompat/​SilkCompat.Hand.cs Tracks loss and pending maps; guards acquisition and polling.
src/​Uno.UI.Composition.WebGpu.Init/​SilkCompat/​SilkCompat.DeviceLoss.cs Adds loss probing and guarded native API calls.

Review effort: Balanced

[UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])]
private static void OnDevice(WGPURequestDeviceStatus status, IntPtr device, WGPUStringView message, IntPtr callback, IntPtr userdata)
{
_device = device;

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 panel: confirmed, and it's worse than probing the wrong device. Once the app releases its own device, _device points at freed memory (wgpuDeviceRelease is Arc::decrement_strong_count in wgpu-native v29.0.1.1), and the next probe's wgpuDeviceCreateCommandEncoder reads it. A failed request sets it to null, which turns the probe off. And a loss of the app's device stops Uno's rendering and mutes its errors.

Registering Uno's device once from WebGpuInitDevice, and keying the lost flag by the device the callback receives, would cover all three.

private static uint wgpuDevicePoll(nint device, uint wait, nint wrappedSubmissionIndex)
{
// Pending maps still have to settle, or whoever spins on one never returns.
if (Volatile.Read(ref _deviceLost) != 0 && Volatile.Read(ref _pendingMaps) == 0)

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 panel: partly. After wgpuDeviceDestroy this poll is harmless, since wgpu-core's device_poll doesn't check the device first, but a real loss can still fail inside the poll. Uno's own polls all come right after a guarded submit or the lost check, so in practice it's app code calling DevicePoll directly that's exposed.


if (_device != 0)
{
WGPU.wgpuCommandEncoderRelease(WGPU.wgpuDeviceCreateCommandEncoder(_device, null));

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.

Not applicable here: this file exists to call wgpu-native, so the native call is the point.


if (_device != 0)
{
WGPU.wgpuCommandEncoderRelease(WGPU.wgpuDeviceCreateCommandEncoder(_device, null));

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.

Not applicable here: this file exists to call wgpu-native, so the native call is the point.

{
if (!IsDeviceLost)
{
WGPU.wgpuQueueSubmit(queue, commandCount, commands);

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.

Not applicable here: this file exists to call wgpu-native, so the native call is the point.

private static nint GuardedBufferGetMappedRange(nint buffer, nuint offset, nuint size)
=> Volatile.Read(ref _deviceLost) != 0 && (!_mapStates.TryGetValue(buffer, out var state) || state != SW.BufferMapState.Mapped)
? 0
: WGPU.wgpuBufferGetMappedRange(buffer, offset, size);

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.

Not applicable here: this file exists to call wgpu-native, so the native call is the point.

return;
}

var resultsPath = Path.Combine(Path.GetTempPath(), $"webgpu-device-loss-{Guid.NewGuid():N}.xml");

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.

False positive: the second argument is webgpu-device-loss-{guid}.xml, which can't be rooted, so nothing is dropped.

@unodevops

Copy link
Copy Markdown
Contributor

🤖 Your WebAssembly Sample App stage site is ready! Visit it here:

@nventive-devops

Copy link
Copy Markdown
Contributor

The build 243915 found UI Test snapshots differences: skia-linux-screenshots: 2458, skia-windows-screenshots: 2458

Details
  • skia-linux-screenshots: 2458 changed over 2494

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • AnimatedIconPage.png-dark
    • AnimatedVisualsTestbedPage.png
    • ApplicationViewMode.png
    • AppWindowClosing.png-dark
    • AppWindowFeatures.png-dark
    • AppWindowPresenters.png
    • Arrange_Performance01.png
    • Attributed_text_Supserscript.png-dark
    • AutoBorderStretchwithleftmargin.png-dark
    • AutoBorderStretchwithleftmargin.png
    • AutomationProperties_Relations.png-dark
    • AutomationProperties_Relations.png
    • AutoSuggestBox_Description.png-dark
    • AutoSuggestBox_Description.png
    • BadgeNotificationTests.png-dark
    • BadgeNotificationTests.png
    • Basics.png-dark
    • Basics.png
    • BenchmarkDotNet.png-dark
    • BenchmarkDotNet.png
  • skia-windows-screenshots: 2458 changed over 2494

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • Accessibility_ScreenReader.png-dark
    • ApplicationViewMode.png-dark
    • Application_DispatcherShutdownMode.png-dark
    • AppWindowPresenters.png-dark
    • ArcSegment.png
    • Attributed_text_Supserscript.png
    • AutoBorderStretchwithleftmargin.png
    • AutomationPropertiesExtensions_Role.png-dark
    • AutoSizedPathCentered.png-dark
    • AutoSizedPathCentered.png
    • AutoSuggestBoxChosenSuggestion.png-dark
    • AutoSuggestBoxChosenSuggestion.png
    • AutoSuggestBox_SoftKeboard.png-dark
    • AutoSuggestBox_SoftKeboard.png
    • BasicEnability.png-dark
    • BasicEnability.png
    • Battery.png-dark
    • Battery.png
    • BezierSegment.png-dark
    • BezierSegment.png

@mergify

mergify Bot commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue). If it does not match the queue conditions yet, it enters the queue once it does.

  • Queue this pull request

@Jen-Uno

Jen-Uno commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

TL;DR — This crash is now the most common way Android WebGPU fails on master. It happens during the same two tests, so they make a good check for this fix. This PR's only CI run is from 5 Nov, and its red Android jobs are the TextBox scroll-lock tests that were fixed on master the next day, not this change. Could it get a rerun on current master and a review?


How often it happens. I went through every failed Android WebGPU job in Uno.UI - CI from 6 to 12 Nov: 50 jobs. 12 of them are this abort: Error in wgpuSurfaceGetCurrentTexture: Validation Error … Parent device is lost, from WebGpuSwapChainContext.Present() in UnoWebGpuView.RenderLoop, on the SwiftShader adapter. The app dies before it writes results, so these jobs show no failed test at all.

Shard Aborts Test running when it aborted
0 9 Given_TextBox.When_Rearranged_Without_Remeasuring ([RequiresFullWindow])
2 3 Given_RichEditBox.When_Seeded_Randomized_Rich_Visual_Stress_Remains_Consistent

From the device logs of builds 245387 and 245853 (artifact runtime-tests-android-skia-webgpu-results):

  • No [webgpu] device lost line before the panic, which matches what WebGPU: a lost device aborts the process on native hosts #26086 describes.
  • In both, the render thread that aborted had logged a new surface 1280x800 earlier in the run. The full-window switch, or a stall in the stress test, looks like the trigger, but that part is inferred.

The rest of the 50, for context:

  • 18 jobs had real test failures. The most common is Given_ScrollViewer.When_Wheel_Notches_Then_Settles_Shortly_After_The_Last (9), which fails only in the WebGPU lane.
  • 9 lost the emulator (adb exits with 255, 3–5 minutes in).
  • 10 failed at checkout, on two PRs.
  • 1 was a different native crash (SIGSEGV in GetFloatArrayRegion).

This PR's CI. Build 243915 (5 Nov) failed Android Skia shards 0 and 4 and Android WebGPU shards 0, 3 and 4. All five failed on tests that were failing across the Android lanes on 4–5 Nov and have passed on master since 6 Nov: When_Touch_Tap_Does_Not_Lock_ScrollViewer_Android, When_Touch_Selection_Flick_Does_Not_Lock_ScrollViewer_Android, When_Keyboard_Selection_Backwards_ScrollViewer_Offset, and one Given_InputPane test. A rerun on current master should show whether shards 0 and 2 stop aborting.

Related: #25989 makes the Android WebGPU lane non-blocking until it is reliable. This PR addresses the main reason it isn't.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/skia ✏️ Categorizes an issue or PR as relevant to Skia

Projects

None yet

Development

Successfully merging this pull request may close these issues.

WebGPU: a lost device aborts the process on native hosts

5 participants