[WebGPU/WebGL2] A material recompile or `EffectWrapper.updateEffect` never releases the superseded effect, so it outlives `scene.dispose()` and keeps the scene reachable
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
- Domain
- computer-graphics, performance
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) readspreviousEffect, compiles the new effect and callssubMesh.setEffect(effect, ...).DrawWrapper.setEffectoverwritesthis.effectwithout disposing the old one. - Post-processes and other
EffectWrapperusers:updateEffectassignsthis._drawWrapper.effect = engine.createEffect(...)without disposing the previous effect.
So:
- The superseded effect stays in
engine._compiledEffectsafterscene.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
_processCodeAfterIncludesis the closure returned byMaterialPluginManager._injectCustomCode, which captures the plugin manager, and the plugin manager's_sceneis 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, inisReadyForSubMesh: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 disposedstandardMaterial.pure.js:1301has the same shape.Materials/drawWrapper.js:50-54, insetEffect:this.effect = effect;, and the old effect isn't released.Materials/effectRenderer.pure.js:348, inEffectWrapper.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:1226passesprocessCodeAfterIncludes: this._eventInfo.customCode.Materials/materialPluginManager.pure.js:193and274build that callback as a closure over the plugin manager.Materials/effect.pure.js:170stores 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
Scenestayed reachable. - Effect cache:
_compiledEffectsgrew from 203 to 432 entries. - Refcounts: of 212 effects acquired during one stage, 143 still had
_refCount > 0after that stage'sscene.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, callpreviousEffect.dispose()(a refcount decrement, notdispose(true)). This has to happen after the new effect is in place, which keeps theallowShaderHotSwappingpath that renders the old effect until the new one is ready. Doing it centrally inDrawWrapper.setEffect(dispose the old effect whenthis.effect !== effect) would cover every material at once, provided every caller hands over the reference it acquired. - In
EffectWrapper.updateEffect, dispose the previous_drawWrapper.effectonce 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
PBRCustomMaterialonly, 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.updateEffecthas the same defect.
- Fixed for
- 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 refcounteddispose().
- Dominant language
- TypeScript
- Stars
- 26.6k
- Forks
- 3.8k
- Avg merge
- 1d 9h
- Merged PRs (30d)
- 112
Getting set up
- No Dockerfile or Docker Compose file
- No pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from BabylonJS/Babylon.js
-
WebGPU: Geometry._invalidateVertexBuffers throws 'mesh.subMeshes is not iterable' for a mesh without sub-meshesPossibly taken @vladosskins178 claimed this 14 days ago. Open
Difficulty 1/5 Under an hour Newbie friendliness 88/100
BabylonJS/Babylon.js#19188 ·
Maintainers usually reply within 1 day
-
WebGPU compressed cube readback feeds encoded blocks to diffuse irradiance calculationPossibly taken @yucheng-du claimed this 1 day ago. Open
Difficulty 4/5 3-5 days Newbie friendliness 54/100
BabylonJS/Babylon.js#19278 ·
Maintainers usually reply within 1 day
-
[WebGPU] A render effect whose WGSL fails to compile never reaches onError: isReady() is true and every draw fails on an invalid pipelinePossibly taken @Popov72 claimed this today. Open
Difficulty 4/5 3-5 days Newbie friendliness 35/100
BabylonJS/Babylon.js#19224 · 2 comments · 1 assignee ·
Maintainers usually reply within 1 day
-
in progress
Difficulty 4/5 3-5 days Newbie friendliness 48/100
BabylonJS/Babylon.js#19212 · 1 comment · 1 assignee ·
Maintainers usually reply within 1 day
-
enhancement Gaussian Splatting native
Difficulty 4/5 3-5 days Newbie friendliness 43/100
BabylonJS/Babylon.js#19145 · 1 assignee ·
Maintainers usually reply within 1 day
All issues in BabylonJS/Babylon.js
Similar issues
-
Difficulty 2/5 1-3 hours Newbie friendliness 86/100
ardia-browser/ardia#6391 ·
Maintainers usually reply within 1 day
-
Feature:Actions/ConnectorTypes Team:ResponseOps
Difficulty 2/5 1-3 hours Newbie friendliness 85/100
elastic/kibana#309028 · 1 comment ·
Maintainers usually reply within 1 day
-
🔨 tool 🧰 library
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
Orange-OpenSource/Orange-Boosted-Bootstrap#4035 ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 65/100
DISIC/teleservice-conformite#230 ·
Maintainers usually reply within 1 day
-
Difficulty 1/5 Under an hour Newbie friendliness 90/100
rothgar/rabble.radio#410 ·
Maintainers usually reply within 1 day