[WebGPU/WebGL2] A material recompile or `EffectWrapper.updateEffect` never releases the superseded effect, so it outlives `scene.dispose()` and keeps the scene reachable

Open
#19,130 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
30/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Active
Tech stack
typescript

Research direction

Start with setEffect in Materials/drawWrapper.js and updateEffect in Materials/effectRenderer.pure.js, then the previousEffect handling in isReadyForSubMesh in Materials/PBR/pbrBaseMaterial.pure.js. Reproduce with the NullEngine script from the report and check whether the superseded effect's refCount in engine._compiledEffects falls to zero after scene.dispose(). Done means the replaced effect is released without breaking allowShaderHotSwapping, and the WebGL2 same-key concern in the linked issue is addressed.

Written by the indexing model from the issue text.

Description

Summary

When an effect is replaced because its defines change, nothing decrements the replaced effect's refcount.

  • Materials: PBRBaseMaterial.isReadyForSubMesh (and the other materials' equivalents) reads previousEffect, compiles the new effect and calls subMesh.setEffect(effect, ...). DrawWrapper.setEffect overwrites this.effect without disposing the old one.
  • Post-processes and other EffectWrapper users: updateEffect assigns this._drawWrapper.effect = engine.createEffect(...) without disposing the previous effect.

So:

  • The superseded effect stays in engine._compiledEffects after scene.dispose(). Every later scene that compiles the same key adds a reference that is again never released, so the refcount only climbs.
  • A superseded material effect also keeps its disposed scene reachable. Its _processCodeAfterIncludes is the closure returned by MaterialPluginManager._injectCustomCode, which captures the plugin manager, and the plugin manager's _scene is the scene. PBR materials always have a plugin manager (built-in configurations such as clear coat are plugins).
  • An app that rebuilds its scene on one engine keeps one old scene alive per define set that only that scene used.

Where

  • Materials/PBR/pbrBaseMaterial.pure.js:948-970, in isReadyForSubMesh:
    const previousEffect = subMesh.effect;
    const effect = this._prepareEffect(mesh, subMesh.getRenderingMesh(), defines, this.onCompiled, this.onError, useInstances, null);
    ...
    scene.resetCachedMaterial();
    subMesh.setEffect(effect, defines, this._materialContext);   // previousEffect is never disposed
    
    standardMaterial.pure.js:1301 has the same shape.
  • Materials/drawWrapper.js:50-54, in setEffect: this.effect = effect;, and the old effect isn't released.
  • Materials/effectRenderer.pure.js:348, in EffectWrapper.updateEffect: this._drawWrapper.effect = this.options.engine.createEffect(...). The previous effect isn't released here either.
  • Retention, which only matters for material effects:
    • Materials/PBR/pbrBaseMaterial.pure.js:1226 passes processCodeAfterIncludes: this._eventInfo.customCode.
    • Materials/materialPluginManager.pure.js:193 and 274 build that callback as a closure over the plugin manager.
    • Materials/effect.pure.js:170 stores it on the effect as _processCodeAfterIncludes.

Repro (Playground, WebGPU: https://playground.babylonjs.com/?webgpu#JQJF9H, WebGL2: https://playground.babylonjs.com/#SLDU2K)

// Each "scene" is created on the Playground's engine, rendered, changed, and disposed.
const s = new BABYLON.Scene(engine);
new BABYLON.FreeCamera("camera", new BABYLON.Vector3(0, 0, -5), s);
new BABYLON.HemisphericLight("sky", new BABYLON.Vector3(0, 1, 0), s);
const box = BABYLON.MeshBuilder.CreateBox("box", {}, s);
box.material = new BABYLON.PBRMaterial("paint", s);
await s.whenReadyAsync(); s.render();
new BABYLON.PointLight("lamp", new BABYLON.Vector3(1, 2, 0), s);   // defines change
box.material.markAsDirty(BABYLON.Material.LightDirtyFlag);
await s.whenReadyAsync(); s.render();
s.dispose();
// expected: the scene's effects leave engine._compiledEffects; actual: the 1-light effect stays (refCount 1, 2, 3, ... per repeat)
// PostProcess variant: pp.updateEffect("#define VARIANT_A"); pp.updateEffect("#define VARIANT_B"); then dispose
// leaves the original and VARIANT_A effects cached.

The same scene without the define change ends with an empty cache. With NullEngine in Node and a forced GC:

  • the first define-change scene stays reachable, refCounts [1], [2], [3];
  • the control and post-process scenes are collected.

Measured in my game

WebGPU, 2560x1440, solo start line, headless Edge. Each stage is a new Scene on one engine, and materials recompile during load as weather, lights and plugins settle.

  • Heap: the JS heap grew 300 to 450 MB per stage, from 1.1 GB to 3.2 GB after 9 stages, and every disposed Scene stayed reachable.
  • Effect cache: _compiledEffects grew from 203 to 432 entries.
  • Refcounts: of 212 effects acquired during one stage, 143 still had _refCount > 0 after that stage's scene.dispose(). Acquisition sites included material compiles, shadow generators, SSAO2 and other post-processes.
  • Frame pacing: from about the sixth stage, render CPU p50 rose from 3 to 4 ms to 6 to 9 ms, and rAF p99 reached 38 to 51 ms (GC).
  • Heap-snapshot retainer path: WebGPUEngine._compiledEffects["pbr+pbr@…MATERIALPLUGIN_26…"] → Effect._processCodeAfterIncludes → closure context → MaterialPluginManager._scene → Scene.

With the workaround below, at most the current and the just-left scene are alive. Over 12 stages the heap stays at 0.95 to 1.7 GB with 160 to 200 cached effects, and stage-11 frame times match stage 0.

Suggested fix

  • When a sub-mesh's or material's effect is replaced by a different one in isReadyForSubMesh, call previousEffect.dispose() (a refcount decrement, not dispose(true)). This has to happen after the new effect is in place, which keeps the allowShaderHotSwapping path that renders the old effect until the new one is ready. Doing it centrally in DrawWrapper.setEffect (dispose the old effect when this.effect !== effect) would cover every material at once, provided every caller hands over the reference it acquired.
  • In EffectWrapper.updateEffect, dispose the previous _drawWrapper.effect once the new one is assigned.
  • Optional hardening: once an effect has compiled, avoid keeping scene-bound closures (_processCodeAfterIncludes, _processFinalCode, onCompiled, onError, fallbacks) reachable from the engine-level cache longer than their owner lives. Context-loss rebuilds need the code callbacks, so this needs care.

Workaround we use

Between scenes (after the old scene is disposed, before the next one exists), call effect.dispose(true) on every entry in engine._compiledEffects except those that existed before the first scene was created (the WebGPU clear quad). The next scene recompiles its shaders as a fresh page load does. We only do this while no scene exists, because force-disposing a same-key effect that is still in use is unsafe on WebGL2 (see #18783 below).

Related

  • Forum "PBRCustomMaterial: compiledEffects memory leak", https://forum.babylonjs.com/t/63468 (May 2026). The same orphaning, reported for PBRCustomMaterial. The reporter noted that it "also occurs with PBRMaterial, but is bounded at most one orphaned entry per define combination".
    • Fixed for PBRCustomMaterial only, by PR #18471 "Fix PBRCustomMaterial compiled effect cleanup" (merged 2026-05-19, in 9.9.0), https://github.com/BabylonJS/Babylon.js/pull/18471, which states it keeps "the global compiled effect cache behavior intact for other materials". A follow-up, PR #18493 "[Materials] Fix PBRCustomMaterial cached effect cleanup" (merged 2026-05-21, in 9.9.1), https://github.com/BabylonJS/Babylon.js/pull/18493, force-releases the custom material's tracked effects on dispose.
    • What this report adds:
      • The plain-material orphan is not harmless. Its refcount keeps climbing, so it never leaves the cache.
      • It keeps a disposed scene reachable.
      • EffectWrapper.updateEffect has the same defect.
  • PR #14406 "Fix a memory leak bug in ShadowDepthWrapper" (2023, closed without merging), https://github.com/BabylonJS/Babylon.js/pull/14406. Same pattern: a depth effect is recreated without releasing the previous one from _compiledEffects.
  • PR #15910 "Fix disposing of effects for submeshes" (merged 2024-11-29) and PR #15964 "Fix an issue with effect reference counting" (merged 2024-12-07, forum https://forum.babylonjs.com/t/55237). These introduced and corrected effect refcounting on dispose paths. They don't cover replacement after a define change.
  • Forum https://forum.babylonjs.com/t/63914 and issue #18783 (closed 2026-08-07), https://github.com/BabylonJS/Babylon.js/issues/18783. On WebGL2, disposing an effect that shares a cached pipeline with a live same-key effect can break the live one. A maintainer there notes that dispose(true) bypasses the refcount. This is why our workaround force-releases only while no scene exists, and why the suggested fix uses the refcounted dispose().
Dominant language
TypeScript
Stars
26.6k
Forks
3.8k
Avg merge
1d 9h
Merged PRs (30d)
112

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from BabylonJS/Babylon.js

All issues in BabylonJS/Babylon.js

Similar issues

More TypeScript issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.