Repository navigation
fix(webgpu): Survive a lost device - #26088
MartinZikmund wants to merge 2 commits into
Conversation
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
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01TXMNtyBVZWdemP5ouF7UUA
|
Claude finished @MartinZikmund's task in 38s —— View job Review summaryVerdict: 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
|
| { | ||
| if (RuntimeTestsBackendHelper.CurrentBackend != RuntimeTestBackends.WebGpu) | ||
| { | ||
| Assert.Inconclusive("Requires the WebGPU backend."); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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; } |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
_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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
🟡 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; |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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)); |
There was a problem hiding this comment.
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)); |
There was a problem hiding this comment.
Not applicable here: this file exists to call wgpu-native, so the native call is the point.
| { | ||
| if (!IsDeviceLost) | ||
| { | ||
| WGPU.wgpuQueueSubmit(queue, commandCount, commands); |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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"); |
There was a problem hiding this comment.
False positive: the second argument is webgpu-device-loss-{guid}.xml, which can't be rooted, so nothing is dropped.
|
🤖 Your WebAssembly Sample App stage site is ready! Visit it here: |
|
The build 243915 found UI Test snapshots differences: Details
|
|
Tick the box to add this pull request to the merge queue (same as
|
|
TL;DR — This crash is now the most common way Android WebGPU fails on How often it happens. I went through every failed Android WebGPU job in
From the device logs of builds 245387 and 245853 (artifact
The rest of the 50, for context:
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 Related: #25989 makes the Android WebGPU lane non-blocking until it is reliable. This PR addresses the main reason it isn't. |

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 inwgpuSurfaceGetCurrentTexture, 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/catchcan't help. From the v29.0.1.1 source, those calls includewgpuSurfaceGetCurrentTexture,wgpuQueueSubmit,wgpuQueueSubmitForIndex,wgpuSurfaceConfigure,wgpuDevicePoll,wgpuBufferGetMappedRangeand the discard insidewgpuTextureRelease.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 lostline before the panic.Invariant. No call that wgpu-native treats as fatal reaches a device known to be lost.
Fix (
root-cause fixfor that invariant).WebGpuCanvasElementcode 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.Presentstops without asking for a retry, and a readback returns a blank image. The loss is logged once and later errors are silenced.Trigger mitigation (
defensive hardening, not validated). The crash also shows the UI thread inwgpuQueueSubmit, 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.
wgpuBufferGetConstMappedRangeand render bundle encoders aren't guarded. Uno doesn't call them, but app code could.Validation.
When_Device_Is_Lost_Then_Process_Survivesdestroys the device in a child process withwgpuDeviceDestroy, then renders, takes a screenshot and resizes the window. Without the fix the child died with exit code0xC0000409andError in wgpuQueueSubmit: Validation Error ... Parent device is lost, the same panic as CI, and the test failed.UNO_WEBGPU=1, Vulkan on a discrete GPU.Given_WebGpuCanvasElementpassed 3/3, child exit code 0, no panics, and onedevice lostline. A subset ofGiven_DrawingBackend_ConformanceandGiven_RenderTargetBitmapgave 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.Uno.UI.Composition.WebGpu.InitandUno.UI.Composition.WebGpubuild with analyzers on; the desktop SamplesApp builds withUnoFastDevBuild.Uno.UI.Runtime.Androiddidn't build here because of a missing workload, and no Android files changed). Also macOS, Linux and iOS. D3D12: withUNO_WEBGPU_BACKENDS=dx12the 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 ✅
Screenshots Compare Test Runresults.🤖 Generated with Claude Code
https://claude.ai/code/session_01TXMNtyBVZWdemP5ouF7UUA