From 7bdb6ac366afb9f1bc2f14557647cc6d8146badd Mon Sep 17 00:00:00 2001 From: Andrei Alecu Date: Tue, 24 Nov 2026 20:21:12 +0200 Subject: [PATCH 1/3] =?UTF-8?q?fix(=F0=9F=A7=A0):=20free=20Dawn's=20unused?= =?UTF-8?q?=20memory=20on=20memory=20pressure=20and=20in=20the=20backgroun?= =?UTF-8?q?d?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Call dawn::native::ReduceMemoryUsage on every live device when iOS sends a memory warning or the app enters the background, and when Android trims memory with its UI hidden or memory low. Repeat after a short delay while Dawn reports memory waiting on GPU work in flight, as Chrome does. On Metal this frees Dawn's last staging ring buffer (4 MiB) plus scratch, temporary uniform and cache memory. On Vulkan it also frees recycled device memory and the framebuffer cache. --- packages/webgpu/android/cpp/cpp-adapter.cpp | 10 +++ .../main/java/com/webgpu/WebGPUModule.java | 65 +++++++++++++++++ packages/webgpu/apple/WebGPUModule.mm | 51 +++++++++++++ packages/webgpu/cpp/rnwgpu/api/GPUDevice.cpp | 72 +++++++++++-------- packages/webgpu/cpp/rnwgpu/api/GPUDevice.h | 26 +++++++ 5 files changed, 196 insertions(+), 28 deletions(-) diff --git a/packages/webgpu/android/cpp/cpp-adapter.cpp b/packages/webgpu/android/cpp/cpp-adapter.cpp index 93a93042b6..35eed74d29 100644 --- a/packages/webgpu/android/cpp/cpp-adapter.cpp +++ b/packages/webgpu/android/cpp/cpp-adapter.cpp @@ -70,6 +70,16 @@ Java_com_webgpu_WebGPUModule_flushPipelineCaches(JNIEnv * /* env */, rnwgpu::GPUDevice::flushPipelineCaches(); } +// WebGPUModule.reduceMemoryUsage (UI thread): the system asked the app to +// give back memory, its UI hidden or memory low (see +// GPUDevice::reduceMemoryUsage). True when a call after a short delay would +// free more. +extern "C" JNIEXPORT jboolean JNICALL +Java_com_webgpu_WebGPUModule_reduceMemoryUsageNative(JNIEnv * /* env */, + jclass /* clazz */) { + return rnwgpu::GPUDevice::reduceMemoryUsage() ? JNI_TRUE : JNI_FALSE; +} + // WebGPUModule.onHostResume and onHostPause (UI thread): animation frames // follow the host activity, resumed or not. extern "C" JNIEXPORT void JNICALL diff --git a/packages/webgpu/android/src/main/java/com/webgpu/WebGPUModule.java b/packages/webgpu/android/src/main/java/com/webgpu/WebGPUModule.java index a4a8557c7f..2f7a68c294 100644 --- a/packages/webgpu/android/src/main/java/com/webgpu/WebGPUModule.java +++ b/packages/webgpu/android/src/main/java/com/webgpu/WebGPUModule.java @@ -1,8 +1,12 @@ package com.webgpu; +import android.content.ComponentCallbacks2; +import android.content.res.Configuration; import android.graphics.Bitmap; import android.hardware.HardwareBuffer; import android.os.Build; +import android.os.Handler; +import android.os.Looper; import android.util.Log; import android.view.View; @@ -41,11 +45,15 @@ public WebGPUModule(ReactApplicationContext reactContext) { // Animation frames follow the host activity: resumed, or not. setForegroundNative(reactContext.getLifecycleState() == LifecycleState.RESUMED); reactContext.addLifecycleEventListener(this); + reactContext.getApplicationContext().registerComponentCallbacks(memoryCallbacks); } @Override public void invalidate() { getReactApplicationContext().removeLifecycleEventListener(this); + getReactApplicationContext().getApplicationContext().unregisterComponentCallbacks(memoryCallbacks); + mainHandler.removeCallbacksAndMessages(null); + reducingMemoryUsage = false; super.invalidate(); } @@ -72,6 +80,63 @@ public void onHostDestroy() {} @DoNotStrip private native void flushPipelineCaches(); + private static final int MEMORY_PASSES = 8; + private static final long MEMORY_PASS_DELAY_MS = 250; + + private final Handler mainHandler = new Handler(Looper.getMainLooper()); + // Main thread only. + private boolean reducingMemoryUsage = false; + + /** + * The system asks the app to give back memory (see + * GPUDevice::reduceMemoryUsage): once its UI is hidden, which is the app + * going to the background (not a pause that a dialog or a focus change in + * multi-window also brings, after which the app is straight back), and + * when memory runs low. The levels below UI_HIDDEN come while the app is + * in the foreground, rendering: what a trim gave back would only be + * allocated again. + */ + private final ComponentCallbacks2 memoryCallbacks = new ComponentCallbacks2() { + @Override + public void onTrimMemory(int level) { + if (level >= ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) { + reduceMemoryUsage(); + } + } + + @Override + public void onLowMemory() { + reduceMemoryUsage(); + } + + @Override + public void onConfigurationChanged(Configuration configuration) {} + }; + + /** + * Has Dawn free the memory it keeps but does not need, then again while + * some of it waits on GPU work in flight, as Chrome does, a few times at + * most (see GPUDevice::reduceMemoryUsage). Main thread. + */ + private void reduceMemoryUsage() { + if (reducingMemoryUsage) { + return; + } + reducingMemoryUsage = true; + reduceMemoryUsagePass(MEMORY_PASSES); + } + + private void reduceMemoryUsagePass(int passesLeft) { + if (reduceMemoryUsageNative() && passesLeft > 1) { + mainHandler.postDelayed(() -> reduceMemoryUsagePass(passesLeft - 1), MEMORY_PASS_DELAY_MS); + return; + } + reducingMemoryUsage = false; + } + + @DoNotStrip + private static native boolean reduceMemoryUsageNative(); + /** * Whether the app is in the foreground: the host activity is resumed (see * AnimationFrameDispatcher::setForeground). An AChoreographer sends its diff --git a/packages/webgpu/apple/WebGPUModule.mm b/packages/webgpu/apple/WebGPUModule.mm index 4f75772294..44ec42f7d2 100644 --- a/packages/webgpu/apple/WebGPUModule.mm +++ b/packages/webgpu/apple/WebGPUModule.mm @@ -2,6 +2,7 @@ #include "ApplePlatformContext.h" #include "DawnBlobCache.h" #import "GPUCanvasContext.h" +#include "GPUDevice.h" #import "RNWGUIKit.h" #import @@ -22,6 +23,53 @@ @interface RCTBridge (JSIRuntime) - (void *)runtime; @end +#if !TARGET_OS_OSX +// Has Dawn free the memory it keeps but does not need (see +// GPUDevice::reduceMemoryUsage), then again while some of it waits on GPU work +// in flight, as Chrome does, a few times at most. Main thread. +static bool reducingDawnMemoryUsage = false; + +static void reduceDawnMemoryUsagePass(int passesLeft) { + if (rnwgpu::GPUDevice::reduceMemoryUsage() && passesLeft > 1) { + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 250 * NSEC_PER_MSEC), + dispatch_get_main_queue(), ^{ + reduceDawnMemoryUsagePass(passesLeft - 1); + }); + return; + } + reducingDawnMemoryUsage = false; +} + +static void reduceDawnMemoryUsage() { + if (reducingDawnMemoryUsage) { + return; + } + reducingDawnMemoryUsage = true; + reduceDawnMemoryUsagePass(8); +} + +// A memory warning, and the move to the background, where iOS kills the apps +// that hold the most memory first: the moments Flutter and Chrome give back +// the GPU memory they can. +static void observeMemoryPressure() { + static dispatch_once_t once; + dispatch_once(&once, ^{ + NSNotificationCenter *center = NSNotificationCenter.defaultCenter; + for (NSNotificationName name in @[ + UIApplicationDidReceiveMemoryWarningNotification, + UIApplicationDidEnterBackgroundNotification + ]) { + [center addObserverForName:name + object:nil + queue:NSOperationQueue.mainQueue + usingBlock:^(NSNotification *) { + reduceDawnMemoryUsage(); + }]; + } + }); +} +#endif + @implementation WebGPUModule RCT_EXPORT_MODULE(WebGPUModule) @@ -151,6 +199,9 @@ - (void)invalidate { } webgpuManager = std::make_shared(runtime, jsInvoker, platformContext); +#if !TARGET_OS_OSX + observeMemoryPressure(); +#endif return @true; } diff --git a/packages/webgpu/cpp/rnwgpu/api/GPUDevice.cpp b/packages/webgpu/cpp/rnwgpu/api/GPUDevice.cpp index f4464b1182..1c1218fe4f 100644 --- a/packages/webgpu/cpp/rnwgpu/api/GPUDevice.cpp +++ b/packages/webgpu/cpp/rnwgpu/api/GPUDevice.cpp @@ -118,42 +118,58 @@ void GPUDevice::flushPipelineCacheIfDue() { flushPipelineCache(); } -void GPUDevice::flushPipelineCaches() { - // What flushing a device takes, copied out of its wrapper under the - // registry's mutex, rather than the wrapper itself: a strong reference to - // the wrapper released on this thread (the platform's UI thread) could be - // its last, and a wrapper, with its JSI members, must only go on its - // runtime's thread. - struct Flush { - wgpu::Device device; - std::shared_ptr> outgrown; - std::shared_ptr async; - std::weak_ptr wrapper; - }; - std::vector flushes; - { - std::lock_guard lock(getRegistryMutex()); - for (const auto &entry : getRegistry()) { - GPUDevice *device = entry.second; - // A wrapper on its way out (its last reference gone, its destructor - // about to unregister it) has nothing left to flush; nor has an - // imported device, whose owner keeps its cache. - if (device->_origin == Origin::Imported || - device->weak_from_this().expired()) { - continue; - } - flushes.push_back({device->_instance, device->_pipelineCacheOutgrown, - device->_async, device->weak_from_this()}); +std::vector GPUDevice::liveDevices() { + std::vector devices; + std::lock_guard lock(getRegistryMutex()); + for (const auto &entry : getRegistry()) { + GPUDevice *device = entry.second; + // A wrapper on its way out (its last reference gone, its destructor about + // to unregister it) has nothing left to do; an imported device is its + // owner's to look after. + if (device->_origin == Origin::Imported || + device->weak_from_this().expired()) { + continue; + } + devices.push_back({device->_instance, device->_pipelineCacheOutgrown, + device->_async, device->weak_from_this()}); + } + return devices; +} + +bool GPUDevice::reduceMemoryUsage() { + bool pending = false; + for (const auto &live : liveDevices()) { + // As in flushPipelineCaches: Dawn's wrapper takes the lock of a device + // that synchronizes itself, so this thread trims it at once. + if (live.device.HasFeature( + wgpu::FeatureName::ImplicitDeviceSynchronization)) { + pending |= dawn::native::ReduceMemoryUsage(live.device.Get()); + continue; + } + if (!live.async) { + continue; } + // Held weakly, as in flushPipelineCaches: a runtime that polls its + // mailbox may hold the job a long time, and the job must not keep the + // device alive meanwhile. + live.async->post([weak = live.wrapper](jsi::Runtime &) { + if (auto device = weak.lock()) { + dawn::native::ReduceMemoryUsage(device->_instance.Get()); + } + }); } - for (const auto &flush : flushes) { + return pending; +} + +void GPUDevice::flushPipelineCaches() { + for (const auto &flush : liveDevices()) { // Dawn locks a device that synchronizes itself around the flush, so this // thread can do it, and does: the runtime's thread may be busy, and a // runtime that polls its mailbox would hold the job until its next // operation, which may never come before the process is killed. if (flush.device.HasFeature( wgpu::FeatureName::ImplicitDeviceSynchronization)) { - flushDawnPipelineCache(flush.device, *flush.outgrown); + flushDawnPipelineCache(flush.device, *flush.pipelineCacheOutgrown); continue; } if (!flush.async) { diff --git a/packages/webgpu/cpp/rnwgpu/api/GPUDevice.h b/packages/webgpu/cpp/rnwgpu/api/GPUDevice.h index 734f15adbf..6c5f62c014 100644 --- a/packages/webgpu/cpp/rnwgpu/api/GPUDevice.h +++ b/packages/webgpu/cpp/rnwgpu/api/GPUDevice.h @@ -323,9 +323,35 @@ class GPUDevice : public NativeObject { // the last moment to write before the process may be killed. static void flushPipelineCaches(); + // Has Dawn free, on every live device, the memory it keeps but does not need + // (dawn::native::ReduceMemoryUsage): its staging ring buffers, scratch and + // temporary uniform buffers and trimmed caches, and on Vulkan the device + // memory it recycles and its framebuffer cache. Like flushPipelineCaches(), + // here when the device synchronizes itself, else on the thread of its + // runtime. Any thread: the platform modules call it when the system warns of + // low memory and when the app goes to the background. Returns true when a + // device trimmed here still has memory that waits on GPU work in flight, + // which a call after a short delay frees; a device trimmed on its runtime's + // thread is not counted. + static bool reduceMemoryUsage(); + private: friend class GPUAdapter; + // What a pass over the live devices takes from each wrapper, copied out + // under the registry's mutex rather than the wrapper itself: a strong + // reference to the wrapper released on the calling thread (the platform's + // UI thread) could be its last, and a wrapper, with its JSI members, must + // only go on its runtime's thread. Imported devices, whose owner looks + // after them, are left out, as are wrappers on their way out. + struct LiveDevice { + wgpu::Device device; + std::shared_ptr> pipelineCacheOutgrown; + std::shared_ptr async; + std::weak_ptr wrapper; + }; + static std::vector liveDevices(); + // Runs the uncapturederror listeners on the creation runtime's JS thread. // Invoked from notifyUncapturedError through the runtime's context. void deliverUncapturedError(wgpu::ErrorType type, std::string message); From b31f67abff7c6bc315f7b8efe9f82473f2eb6383 Mon Sep 17 00:00:00 2001 From: Andrei Alecu Date: Tue, 24 Nov 2026 20:25:27 +0200 Subject: [PATCH 2/3] =?UTF-8?q?fix(=F0=9F=A7=A0):=20cap=20the=20memory=20t?= =?UTF-8?q?rim=20at=20four=20passes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On Vulkan, Dawn's ReduceMemoryUsage keeps reporting pending work: it submits to free what waits, and that submit leaves work of its own. Measured on an Android 15 emulator (Cube example, app sent to the background): the first pass freed Dawn's 4 MiB staging ring buffer; the next seven freed nothing and still reported pending. --- .../webgpu/android/src/main/java/com/webgpu/WebGPUModule.java | 2 +- packages/webgpu/apple/WebGPUModule.mm | 2 +- packages/webgpu/cpp/rnwgpu/api/GPUDevice.h | 4 +++- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/webgpu/android/src/main/java/com/webgpu/WebGPUModule.java b/packages/webgpu/android/src/main/java/com/webgpu/WebGPUModule.java index 2f7a68c294..d484ebd99b 100644 --- a/packages/webgpu/android/src/main/java/com/webgpu/WebGPUModule.java +++ b/packages/webgpu/android/src/main/java/com/webgpu/WebGPUModule.java @@ -80,7 +80,7 @@ public void onHostDestroy() {} @DoNotStrip private native void flushPipelineCaches(); - private static final int MEMORY_PASSES = 8; + private static final int MEMORY_PASSES = 4; private static final long MEMORY_PASS_DELAY_MS = 250; private final Handler mainHandler = new Handler(Looper.getMainLooper()); diff --git a/packages/webgpu/apple/WebGPUModule.mm b/packages/webgpu/apple/WebGPUModule.mm index 44ec42f7d2..1a4c5a9fab 100644 --- a/packages/webgpu/apple/WebGPUModule.mm +++ b/packages/webgpu/apple/WebGPUModule.mm @@ -45,7 +45,7 @@ static void reduceDawnMemoryUsage() { return; } reducingDawnMemoryUsage = true; - reduceDawnMemoryUsagePass(8); + reduceDawnMemoryUsagePass(4); } // A memory warning, and the move to the background, where iOS kills the apps diff --git a/packages/webgpu/cpp/rnwgpu/api/GPUDevice.h b/packages/webgpu/cpp/rnwgpu/api/GPUDevice.h index 6c5f62c014..cce2232b78 100644 --- a/packages/webgpu/cpp/rnwgpu/api/GPUDevice.h +++ b/packages/webgpu/cpp/rnwgpu/api/GPUDevice.h @@ -332,7 +332,9 @@ class GPUDevice : public NativeObject { // low memory and when the app goes to the background. Returns true when a // device trimmed here still has memory that waits on GPU work in flight, // which a call after a short delay frees; a device trimmed on its runtime's - // thread is not counted. + // thread is not counted. On Vulkan the answer stays true: to free what + // waits, Dawn submits, and that submit leaves something of its own to wait + // on. Callers repeat a few times at most. static bool reduceMemoryUsage(); private: From 271765579420370d35ca051306a8c4a9d904fe88 Mon Sep 17 00:00:00 2001 From: Andrei Alecu Date: Tue, 24 Nov 2026 20:32:23 +0200 Subject: [PATCH 3/3] =?UTF-8?q?test(=F0=9F=A7=A0):=20keep=20a=20device=20w?= =?UTF-8?q?orking=20while=20Android=20trims=20its=20memory?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Sends the example app to the background (TRIM_MEMORY_UI_HIDDEN) and back while it uploads through writeBuffer and reads back, then checks every round read back what it wrote and the device still works afterwards. Android only: iOS has no command-line memory warning. am send-trim-memory cannot be used, as Android refuses a background level for a foreground process. Checked on an Android 15 emulator: the trim runs during the uploads, and the spec fails (MapAsyncStatus::Aborted) when the trim destroys the device. --- .../webgpu/src/__tests__/MemoryTrim.spec.ts | 99 +++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 packages/webgpu/src/__tests__/MemoryTrim.spec.ts diff --git a/packages/webgpu/src/__tests__/MemoryTrim.spec.ts b/packages/webgpu/src/__tests__/MemoryTrim.spec.ts new file mode 100644 index 0000000000..4dec13ccfe --- /dev/null +++ b/packages/webgpu/src/__tests__/MemoryTrim.spec.ts @@ -0,0 +1,99 @@ +import { execFile } from "child_process"; + +import { client } from "./setup"; + +// The example app's package and activity (apps/example/app.json). +const ANDROID_ACTIVITY = + "com.reactnativewebgpu.example/com.microsoft.reacttestapp.MainActivity"; + +const adb = (...args: string[]) => + new Promise((resolve, reject) => { + execFile("adb", args, (error) => (error ? reject(error) : resolve())); + }); + +const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +// Sends the example app to the background and brings it back. Hiding its UI +// has Android ask it to give back memory (TRIM_MEMORY_UI_HIDDEN), and +// WebGPUModule then has Dawn trim every live device (see +// GPUDevice::reduceMemoryUsage) on the UI thread, in passes 250ms apart. +// `am send-trim-memory` would be more direct, but Android refuses a +// background level for a process in the foreground, which the app under test +// is. +const hideAndShowApp = async () => { + await adb("shell", "input", "keyevent", "KEYCODE_HOME"); + await wait(1500); + await adb("shell", "am", "start", "-n", ANDROID_ACTIVITY); +}; + +// Uploads through Dawn's staging ring buffers (writeBuffer) and reads the last +// upload back, for durationMs. Run while the UI thread trims the same device, +// it has the trim free those ring buffers under uploads still in flight. +const uploadAndReadBack = (durationMs: number) => + client.eval< + { durationMs: number }, + { rounds: number; mismatches: number; last: number[] } + >( + ({ device, durationMs: duration }) => { + const size = 1024 * 1024; + const target = device.createBuffer({ + size, + usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC, + }); + const readback = device.createBuffer({ + size: 16, + usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ, + }); + const data = new Uint32Array(size / 4); + const end = Date.now() + duration; + let rounds = 0; + let mismatches = 0; + let last: number[] = []; + const round = (): Promise => { + rounds++; + data.fill(rounds); + device.queue.writeBuffer(target, 0, data); + const encoder = device.createCommandEncoder(); + encoder.copyBufferToBuffer(target, size - 16, readback, 0, 16); + device.queue.submit([encoder.finish()]); + return readback.mapAsync(GPUMapMode.READ).then(() => { + last = Array.from(new Uint32Array(readback.getMappedRange())); + readback.unmap(); + if (last.some((value) => value !== rounds)) { + mismatches++; + } + return Date.now() < end ? round() : undefined; + }); + }; + return round().then(() => { + target.destroy(); + readback.destroy(); + return { rounds, mismatches, last }; + }); + }, + { durationMs }, + ); + +describe("Memory trim", () => { + it("keeps a device in use working while Android trims memory", async () => { + if (client.OS !== "android") { + return; + } + // Uploads before, during and after the trim's passes (about one second). + const uploads = uploadAndReadBack(3000); + await hideAndShowApp(); + const during = await uploads; + expect(during.rounds).toBeGreaterThan(1); + expect(during.mismatches).toBe(0); + expect(during.last).toEqual([ + during.rounds, + during.rounds, + during.rounds, + during.rounds, + ]); + + // Once the trim is over, the device still uploads and reads back. + const after = await uploadAndReadBack(0); + expect(after).toEqual({ rounds: 1, mismatches: 0, last: [1, 1, 1, 1] }); + }); +});