Babylon.js icon indicating copy to clipboard operation
Babylon.js copied to clipboard

WebGPU Engine Deferred Queue Memory Leak & Premature Device Destruction

Open codeCraft-Ritik opened this issue 2 months ago • 2 comments

Issue : WebGPU Engine Deferred Queue Memory Leak & Premature Device Destruction

  • Package: @babylonjs/core
  • Subsystem: WebGPUEngine, Resource Disposal & Memory Management
  • Affected File: packages/dev/core/src/Engines/webgpuEngine.pure.ts (Lines 4085–4098)
  • Associated Files:
    • packages/dev/core/src/Engines/WebGPU/webgpuTextureManager.ts (Lines 1467–1495)
    • packages/dev/core/src/Engines/WebGPU/webgpuBufferManager.ts (Lines 235–253)
    • packages/dev/core/src/Engines/abstractEngine.pure.ts (Lines 2788–2791)
  • Status: Architectural defect on master branch

1. Problem Description

When an application disposes a WebGPUEngine via engine.dispose(), all GPU textures and vertex/index buffers attached to active scenes are permanently leaked in VRAM and JavaScript memory. Furthermore, GPUDevice.destroy() is called before the engine's scenes are torn down, causing sub-resource disposals to interact with an invalidated device.

In single-page applications (SPAs) where 3D canvases mount and unmount, or in automated unit tests, this bug causes monotonic VRAM growth leading to browser tab crashes (WebGL/WebGPU context lost / Out-Of-Memory).

2. Root Cause Analysis

Inspect WebGPUEngine.dispose() in webgpuEngine.pure.ts:

public override dispose(): void {
    this._isDisposed = true;
    this.hideLoadingUI?.();
    this._timestampQuery.dispose();
    this._mainTexture?.destroy();
    this._depthTexture?.destroy();
    this._textureHelper.destroyDeferredTextures();  // (1) Flushes existing deferred textures
    this._bufferManager.destroyDeferredBuffers();    // (2) Flushes existing deferred buffers
    this._device.destroy();                         // (3) GPUDevice is DESTROYED here!

    _CommonDispose(this, this._renderingCanvas);

    super.dispose();                                // (4) Calls AbstractEngine.dispose()
}

Now trace what happens inside super.dispose() (abstractEngine.pure.ts lines 2788–2791):

// Release scenes
while (this.scenes.length) {
    this.scenes[0].dispose();
}

When scene.dispose() executes:

  1. Every mesh is disposed, which calls bufferManager.releaseBuffer(buffer). When references reach zero, the buffer is queued into this._deferredReleaseBuffers (webgpuBufferManager.ts line 239).
  2. Every texture is disposed, which calls textureManager.releaseTexture(texture). The texture is queued into this._deferredReleaseTextures (webgpuTextureManager.ts line 1473).
  3. The fatal flaw: Because destroyDeferredTextures() and destroyDeferredBuffers() were already called in steps (1) and (2), the newly queued resources from scene.dispose() are never flushed!
  4. Additionally, this._device.destroy() was already executed in step (3). Calling cleanup code on hardware resources after the device is destroyed violates the WebGPU specification lifecycle.
sequenceDiagram
    participant App
    participant WebGPUEngine
    participant WebGPUManagers as Buffer & Texture Managers
    participant GPUDevice
    participant AbstractEngine
    participant Scene

    App->>WebGPUEngine: dispose()
    WebGPUEngine->>WebGPUManagers: destroyDeferredBuffers() & destroyDeferredTextures()
    Note over WebGPUManagers: Only clears pre-existing queue
    WebGPUEngine->>GPUDevice: destroy() [Device invalidated!]
    WebGPUEngine->>AbstractEngine: super.dispose()
    AbstractEngine->>Scene: scene.dispose()
    Scene->>WebGPUManagers: releaseBuffer() & releaseTexture()
    Note over WebGPUManagers: Enqueues scene buffers & textures into deferred lists
    Note over WebGPUManagers: QUEUES NEVER FLUSHED! VRAM LEAKED!

3. Step-by-Step Reproduction

import { WebGPUEngine } from "@babylonjs/core/Engines/webgpuEngine";
import { Scene } from "@babylonjs/core/scene";
import { MeshBuilder } from "@babylonjs/core/Meshes/meshBuilder";
import { StandardMaterial } from "@babylonjs/core/Materials/standardMaterial";
import { Texture } from "@babylonjs/core/Materials/Textures/texture";

async function verifyMemoryLeak() {
    const canvas = document.createElement("canvas");
    const engine = new WebGPUEngine(canvas);
    await engine.initAsync();
    const scene = new Scene(engine);

    // Create a mesh with buffers and textures
    const sphere = MeshBuilder.CreateSphere("sphere", { segments: 32 }, scene);
    const mat = new StandardMaterial("mat", scene);
    mat.diffuseTexture = new Texture("https://playground.babylonjs.com/textures/grass.png", scene);
    sphere.material = mat;

    // Dispose the engine
    engine.dispose();

    // Inspect internal manager queues
    const bufferManager = (engine as any)._bufferManager;
    const textureHelper = (engine as any)._textureHelper;

    console.assert(
        bufferManager._deferredReleaseBuffers.length === 0,
        `Memory leak: ${bufferManager._deferredReleaseBuffers.length} GPU buffers queued but never destroyed!`
    );
    console.assert(
        textureHelper._deferredReleaseTextures.length === 0,
        `Memory leak: ${textureHelper._deferredReleaseTextures.length} GPU textures queued but never destroyed!`
    );
}

4. Code Fix & Patch

The correct lifecycle must tear down the engine abstractions and attached scenes first, then flush and destroy all resulting deferred GPU resources, and finally destroy the GPUDevice:

--- a/packages/dev/core/src/Engines/webgpuEngine.pure.ts
+++ b/packages/dev/core/src/Engines/webgpuEngine.pure.ts
@@ -4088,13 +4088,16 @@ export class WebGPUEngine extends ThinWebGPUEngine {
         this._timestampQuery.dispose();
         this._mainTexture?.destroy();
         this._depthTexture?.destroy();
+
+        _CommonDispose(this, this._renderingCanvas);
+
+        // Tear down scenes, materials, meshes, and textures first
+        super.dispose();
+
+        // Flush all deferred buffers and textures queued during scene teardown
         this._textureHelper.destroyDeferredTextures();
         this._bufferManager.destroyDeferredBuffers();
         this._device.destroy();
-
-        _CommonDispose(this, this._renderingCanvas);
-
-        super.dispose();
     }

5. Contributor Value & Profile Impact

  • Why it matters: Memory leaks in WebGPU runtimes cannot be reclaimed by garbage collection because underlying native handles (GPUBuffer, GPUTexture) reside in GPU memory.
  • Skills demonstrated: Deep understanding of WebGPU memory lifecycles, deferred GPU resource management, and clean engine architectural design.

codeCraft-Ritik avatar Sep 18 '26 04:09 codeCraft-Ritik

Thanks for your investigation!

Can you create a PR for it? It will be easier for us to review and give you feedbacks.

Thanks!

Popov72 avatar Sep 22 '26 17:09 Popov72

Hi @codeCraft-Ritik - Would you have to create a PR by any chance?

thomlucc avatar Sep 29 '26 17:09 thomlucc