editor icon indicating copy to clipboard operation
editor copied to clipboard

fix(viewer): defer geometry disposal to avoid WebGPU dispose race (Sentry MONOREPO-EDITOR-DK/EG/EH)

Open anton-pascal opened this issue 4 months ago • 3 comments

What

Defensive fix for a Three.js WebGPU dispose race that is generating the top Sentry error in the editor: MONOREPO-EDITOR-DK (4453 events), plus EG (110) and EH (94) — all the same root cause.

The race

Inside the per-frame rebuild loops of GeometrySystem and RoofSystem, an outgoing live geometry (one currently attached to a rendered mesh) was disposed synchronously mid-useFrame:

  • geometry-system.tsx → disposeChildren() (mesh.geometry.dispose() on swapped-out children)
  • roof-system.tsx → updateRoofSegmentGeometry() (mesh.geometry.dispose() before reassign)
  • roof-system.tsx → the BoxGeometry placeholder swap
  • roof-system.tsx → updateMergedRoofGeometry() (mergedMesh.geometry.dispose() on the two reassign paths)

On the WebGPU backend the renderer still holds a RenderObject referencing that geometry for the frame in flight. BufferGeometry.dispose() synchronously dispatches the dispose event; three's WebGPU onDispose handler then calls RenderObject.getAttributes(), which reads .id / .count off attributes that have already been freed →

Cannot read properties of undefined (reading 'id')   // and 'count'
  THREE.BufferGeometry.dispose
  -> EventDispatcher.dispatchEvent -> three.webgpu.js onDispose
  -> RenderObject.getAttributes

([email protected], @react-three/[email protected])

A try/catch around .dispose() cannot help — the throw happens inside three's own async event dispatch, not in our call frame.

The fix — defensive deferral, behavior identical

New tiny helper packages/viewer/src/lib/deferred-dispose.ts:

  • queueGeometryDispose(geometry) — queue an outgoing live geometry instead of freeing it now.
  • flushGeometryDisposals() — drain the queue (wrapped in try/catch), called once at the start of each system's useFrame, before any rebuild work.

The renderer releases its RenderObject for a geometry once it's no longer drawn (i.e. after the frame in which we swapped in the replacement). So we hand the outgoing geometry to the queue and free it at the top of the next frame, after that render has completed. Every geometry is still disposed — just one frame later, after the renderer let go of it. No geometry leaks, no rendering-behavior change.

Only the live-mesh dispose sites were changed. Transient CSG intermediates (brushes, temporary merge/subtract results that never enter the scene graph) are left disposing synchronously — the renderer never held a RenderObject for them, so there's no race.

Testing

  • bunx tsc --build packages/viewer/tsconfig.json → exit 0 (clean).
  • bun test .../geometry-system.test.ts → 1 pass.
  • biome lint on all three touched files → clean.

Scope

Addresses Sentry MONOREPO-EDITOR-DK / EG / EH. Defensive-only; does not redesign the rebuild pipeline. Do not merge without review.


[!NOTE] Medium Risk Touches core viewer frame ordering and geometry lifecycle for all parametric/roof rebuilds; timing-sensitive but narrowly scoped to dispose sites on rendered meshes with documented ordering constraints.

Overview Fixes a WebGPU dispose race where synchronous BufferGeometry.dispose() on meshes still referenced by the renderer during useFrame rebuilds triggered Cannot read properties of undefined (reading 'id') (top Sentry errors DK/EG/EH).

Adds deferred-dispose.ts with queueGeometryDispose and flushGeometryDisposals, plus GeometryDisposalFlushSystem mounted in the viewer at useFrame priority -1000 so the queue drains before any rebuild system runs each frame. GeometrySystem and RoofSystem now queue outgoing live mesh geometries instead of disposing them mid-frame; transient CSG intermediates still dispose synchronously.

Geometries are freed one frame later, after the render pass that swapped them out—same cleanup behavior, no pipeline redesign.

Reviewed by Cursor Bugbot for commit cb566be4c94a0e120dc945ddecc9ef66e7116b0f. Bugbot is set up for automated code reviews on this repo. Configure here.

anton-pascal avatar Jul 07 '26 04:07 anton-pascal

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
pascal 🔴 Failed – Jul 7, 2026, 4:12 AM

💡 Tip: Enable Workflows to automatically generate PRs for you.

mintlify[bot] avatar Jul 07 '26 04:07 mintlify[bot]

Good catch by Bugbot — confirmed and fixed in cb566be4.

Root cause: RoofSystem and GeometrySystem each called flushGeometryDisposals() from their own useFrame. Since all systems run at the default priority (0) in mount order, RoofSystem's flush executed after GeometrySystem's rebuild in the same frame, so it could dispose geometries GeometrySystem had just queued this frame — before the render pass — reintroducing exactly the dispose race the deferral prevents.

Fix: Introduced a dedicated GeometryDisposalFlushSystem that flushes once per frame in useFrame at priority -1000, guaranteeing it runs ahead of every rebuild system regardless of mount order. Removed the inline flush calls from GeometrySystem and RoofSystem, and updated the deferred-dispose docs to note that this is the single authoritative caller of flushGeometryDisposals. The queue now only ever contains geometries dropped on a previous frame (already released by the renderer).

Viewer package typechecks clean and Biome passes on the touched files.

anton-pascal avatar Jul 07 '26 04:07 anton-pascal

Triage result: this remains a valuable fix direction, but it is not merge-ready on current main.

The first frame-ordering finding was addressed by the dedicated negative-priority flush. The remaining Bugbot finding is still valid: the module-global queue can retain GPU resources if the Canvas/flush system unmounts before the next frame. The branch also now conflicts with current viewer work.

Please rebase and add an explicit unmount/drain ownership path plus focused tests for: geometry queued in frame N is not disposed until after that frame's render, multiple producers cannot flush one another's same-frame entries, and Canvas teardown drains the remaining queue exactly once. I’m leaving this open as the canonical disposal-race PR rather than accepting a timing-sensitive partial port.

Aymericr avatar Jul 19 '26 15:07 Aymericr

Thanks for chasing this one down — the Sentry triage (DK/EG/EH being one root cause), the frame-ordering catch you self-reported and fixed in cb566be4, and pinning the exact three/R3F versions all made this fast to verify. I dug into three's source and reproduced the crash, and I think the conclusion is that this PR is no longer needed. Closing, with the evidence:

1. The crash isn't a timing race — it's an unguarded property read in three 0.184.0.

[email protected]/src/renderers/common/RenderObject.js:513-518:

attribute = geometry.getAttribute( nodeAttribute.name );
attributesId[ nodeAttribute.name ] = attribute.id;   // ← line 514, unguarded
...
if ( attribute === undefined ) continue;             // ← line 518, guard comes AFTER

Any geometry missing an attribute the node material requests (uv on a merged/CSG roof result, or the degenerate placeholder) throws Cannot read properties of undefined (reading 'id') here — no dispose involved. three 0.185.1 wraps that write in if ( attribute !== undefined ) (RenderObject.js:539-552, with the continue guard now at :555).

main already pins three: 0.185.1 (root package.json:45, bumped in a5907477 / #496). This branch still pins 0.184.0 (package.json:41). I ran both the synchronous (main-today) and deferred (this PR) dispose orders against real three Geometries/Attributes: 0.184 throws on the sync path; 0.185 throws on neither. The deferral isn't the mechanism doing the work.

2. The deferral introduces a use-after-free on the incoming geometry.

RenderObject.onGeometryDispose (RenderObject.js:337-341) only nulls the attribute cache, and the listener is never unregistered on geometry swap — removal happens only in RenderObject.dispose() (line 961). Meanwhile Geometries.initGeometry's onDispose closure resolves attributes through renderObject.getAttributes() (Geometries.js:190), which reads renderObject.geometry — already advanced to the replacement by RenderObjects.get() → setGeometry() (RenderObjects.js:120). So freeing outgoing A one frame late runs Attributes.delete() → destroyAttribute → data.buffer.destroy() (Attributes.js:45-58, WebGPUAttributeUtils.js:361-370) against B's live buffers. My harness against those real classes prints destroyed = ["B.position"].

3. -1000 does the opposite of what the docstring says.

geometry-disposal-flush.tsx:22 targets "after the render pass has completed", but rendering happens inside useFrame at priority 1 (post-processing.tsx:646; the DebugRenderer fallback at index.tsx:578 is priority 0). R3F sorts subscribers ascending and iterates in that order, so a -1000 callback runs before that frame's render. Tracing the real subscriber list: geometry queued in frame 1 at priority 2 is disposed in frame 2 at priority -1000 — still before the frame-2 render that would re-point the RenderObject. That's exactly the misdirected-free window in (2). Anything genuinely post-render wants addAfterEffect/addTail, or a priority above 1.

4. Consistency check. If the synchronous-dispose race were the cause, this fix would be incomplete — main still disposes live mesh geometries synchronously at wall-system.tsx:769,784, window-system.tsx:3362, stair-system.tsx:231,543, ceiling-system.tsx:96, door-system.tsx:2294, fence-system.tsx:561.

Mechanics, for the record (none of these are why I'm closing): merged onto main the only conflict is geometry-system.tsx:19, where main added type Object3D to the same three import — a stale merge base, not a defect. After resolving it, tsgo --build packages/viewer is clean, biome check is clean across all five changed files, and packages/viewer tests are 87 pass / 0 fail. One correction to the write-up: BufferGeometry.dispose() is a plain synchronous dispatchEvent (BufferGeometry.js:1472, EventDispatcher.js:101-126), so a try/catch would have caught the throw — the reason not to use one is that swallowing it hides the missing attribute, not that the dispatch is async. Bugbot's remaining unmount-drain point was also correct (deferred-dispose.ts:30 has no teardown path), just moot now.

Suggested next step: please confirm in Sentry that DK/EG/EH stopped after the 0.185 bump. If events still arrive on 0.185, the remaining cause is a geometry reaching the renderer without a requested attribute — the right fix is routing the offending builder through ensureRenderableGeometryAttributes (packages/viewer/src/lib/csg-utils.ts:45), which already backfills normal/uv/uv2, and I'd happily review that. Same-shaped guard as your #467 KTX2 fix, and it lands in the shared package where npm consumers and the hosted app both get it.

Aymericr avatar Aug 04 '26 18:08 Aymericr