Repository navigation
[web] Release CanvasKit WebGL contexts and surfaces when a view is removed - #196816
Conversation
…text deletion Wrap CanvasKit deleteContext in a try/catch so a failure cannot abort view disposal partway, deduplicate the bitmap cleanup in CkOffscreenSurface.rasterizeToImageBitmaps, guard triggerContextLoss after disposal, and document the post-dispose behavior of the Surface interfaces and the MultiSurfaceViewRasterizer draw/dispose overrides.
…e classes Move disposal state into the abstract Surface and ViewRasterizer classes instead of guarding every subclass method: - Surface.dispose() is now a non-virtual, idempotent template that calls disposeResources() and onDispose once. CkSurface and SkwasmSurface implement disposeResources(). - ViewRasterizer.draw() stops if the view is disposed, including after prepareToDraw(), so MultiSurfaceViewRasterizer no longer copies draw(). - Drop guards on paths a disposed surface can no longer reach (its context-lost listener is removed and the provider stops tracking it), the try/catch around CanvasKit deleteContext (it only throws for an already-deleted handle), and the tests that called those paths directly.
…posed A disposed DisplayCanvasFactory now asserts instead of lazily creating a new base canvas or overlay, so a disposed view can never acquire a new WebGL context through it. dispose() is idempotent.
debugResetRasterizer now disposes the previous rasterizer (and the CanvasKit picture-to-image surface), then recreates the view rasterizers of registered views with the new rasterizer. Tests no longer need to dispose them by hand before resetting.
|
I've been looking at Skwasm's surface teardown and found a few gaps that predate this PR. Nothing here is caused by your change. I'm mentioning it on this PR because What the Skwasm side does today:
What I measured (AI-assisted, prebuilt
I don't think this needs to hold up your PR. I have a sketch of a fix (bind and reset the render context, then lose and delete the context, from both |
There was a problem hiding this comment.
Code Review
This pull request improves resource management and prevents memory leaks during view disposal in the Web UI engine by establishing structured disposal lifecycles for Surface and DisplayCanvasFactory. It ensures WebGL contexts are deleted via CanvasKit, canvases are removed from the DOM, and rendering is prevented on disposed views. Feedback suggests wrapping the disposeResources() call in a try-finally block within Surface.dispose to guarantee that the onDispose callback is always executed and cleared.
@kevmoo this sounds like it's definitely worth fixing. Please send the follow-up PR after this one lands |
…skit-view-goes' into flutter-flutter-195025-web-canvaskit-view-goes
…95025-web-canvaskit-view-goes
Wrap disposeResources() in try/finally so the SurfaceProvider callback is invoked and cleared even when releasing resources fails, preventing the provider from tracking a surface that is already marked disposed.
mdebbar
left a comment
There was a problem hiding this comment.
This fix is confirmed on an iOS simulator:
file.1.mp4
PlatformViewEmbedder allocates every display canvas via rasterizer.getOverlay(), leaving DisplayCanvasFactory.baseCanvas detached and never painted into. Remove baseCanvas and make MultiSurfaceViewRasterizer.prepareToDraw a no-op so each rendered multi-surface view allocates one WebGL context instead of two.
flutter/flutter@b34b017...5423f94 2026-11-21 [email protected] Make an Impeller render target from a Vulkan backing store (flutter/flutter#193003) 2026-11-21 [email protected] Persist the vulkan shader cache on teardown (flutter/flutter#197017) 2026-11-21 [email protected] [flutter_tools] Preserve rolling log buffer for Chromium crash diagnostics (flutter/flutter#196037) 2026-11-21 [email protected] Roll Skia from 8845aecd8c53 to 39e0ad394168 (2 revisions) (flutter/flutter#197094) 2026-11-21 [email protected] Adds redirect for listen package in api.flutter.dev (flutter/flutter#197068) 2026-11-21 [email protected] Roll Dart SDK from c6857d58f0ec to fc86f5a42779 (1 revision) (flutter/flutter#197086) 2026-11-20 [email protected] iOS: Discard pending platform view disposals on reset (flutter/flutter#197026) 2026-11-20 [email protected] Tolerate a missing flutter/service_worker handler in the web first-frame notification (flutter/flutter#196329) 2026-11-20 [email protected] Roll Skia from 9aafbb357743 to 8845aecd8c53 (2 revisions) (flutter/flutter#197080) 2026-11-20 [email protected] Prevent crash in tessellator with extreme radii (flutter/flutter#196648) 2026-11-20 [email protected] Windows: in the flutter tool, always close the file handle in _download even when an HTTP request fails so that it is not left open and becomes undeletable (flutter/flutter#197061) 2026-11-20 [email protected] Roll Skia from b61640825c5b to 9aafbb357743 (7 revisions) (flutter/flutter#197066) 2026-11-20 [email protected] Swap dependabot reviewers (flutter/flutter#196995) 2026-11-20 [email protected] [iOS] Hide UIScrollEdgeEffect on FlutterSemanticsScrollView and scroll-to-top UIScrollView on iOS 26+ (flutter/flutter#195356) 2026-11-20 [email protected] [devicelab] Enable Vulkan GPU tracing by default on Android Impeller PerfTests (flutter/flutter#196822) 2026-11-20 [email protected] Roll Dart SDK from 3b5f45d812f8 to c6857d58f0ec (1 revision) (flutter/flutter#197063) 2026-11-20 [email protected] [flutter_tools] Delete flutter.version.json when switching channels (flutter/flutter#196943) 2026-11-20 [email protected] Update desktop TESTOWNERS (flutter/flutter#196930) 2026-11-20 [email protected] [web] Release CanvasKit WebGL contexts and surfaces when a view is removed (flutter/flutter#196816) 2026-11-20 [email protected] [Linux] Hide libunwind symbols in libflutter_linux_gtk.so (flutter/flutter#196451) 2026-11-20 [email protected] Roll Skia from a1edf5c2ea5c to b61640825c5b (1 revision) (flutter/flutter#197058) 2026-11-20 [email protected] [flutter_tools] Update --web-content-hash serving tip to cover assets and canvaskit (flutter/flutter#196908) 2026-11-20 [email protected] Send a semantics update when only the identifier changes (flutter/flutter#196460) 2026-11-20 [email protected] Roll Packages from 81b7c44 to 898818d (11 revisions) (flutter/flutter#197056) If this roll has caused a breakage, revert this CL and set the roller to dry run mode using the controls here: https://autoroll.skia.org/r/flutter-packages Please CC [email protected],[email protected] on the revert to ensure that a human is aware of the problem. To file a bug in Packages: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md
When a view is removed from a multi-view CanvasKit app, its
MultiSurfaceViewRasterizerand the onscreen surfaces it created were never fully torn down.CkSurface.dispose()only disposed theSkSurface. It left the WebGL context, the EmscriptenGL.contextsentry and thewebglcontextlostlistener in place, and the rasterizer stayed registered inMultiSurfaceRasterizer. When the browser later evicted one of those stale contexts, the removed view's surface handledwebglcontextlostby acquiring a new canvas and creating a new context. After a fewremoveView/addViewcycles this went over Safari's active WebGL context limit (16), and the browser evicted the live view's context, so the view went blank.This PR releases everything a view owns when it is disposed:
Surfacenow owns disposal:dispose()is a non-virtual, idempotent template that calls a protecteddisposeResources()hook once, thenonDispose.CkSurface.disposeResources()releases the canvas through_releaseCanvas(). That abandons and deletes theGrContext, unregisters the context-lost listener (so a disposed surface can never run context-loss recovery), explicitly loses the WebGL context (WEBGL_lose_context) and deletes the handle from CanvasKit's context table (canvasKit.deleteContext, newly bound). The WebGL steps only run when CanvasKit actually created a context (_glContext > 0), so software surfaces are untouched.ViewRasterizertracks whether it is disposed, anddraw()stops if the view is disposed before or partway through a frame (afterprepareToDraw()), so a removed view never submits a stale frame or allocates new canvases. Queued renders still complete.MultiSurfaceViewRasterizer.dispose()removes itself fromMultiSurfaceRasterizerand disposes itsDisplayCanvasFactory, which now also removes canvases from the DOM.MultiSurfaceRasterizer.dispose()iterates over a copy of its map.DisplayCanvasFactory.baseCanvasis created lazily, so a view that is disposed before its first frame never allocates a surface or WebGL context.SurfaceProviderstops tracking surfaces once they are disposed (viaSurface.onDispose).SkwasmSurfacenow extendsOffscreenSurfaceand implementsdisposeResources(), so it gets the same idempotentdispose(). This prevents a doublesurfaceDestroyon the native handle.Fixes #195025
Behavioral Changes
removeView/addViewcycles in Safari, the live view's context was evicted and the view rendered blank.After: removing a view loses and deletes its WebGL contexts right away and removes its canvases from the DOM. A removed view never recreates a context, so only the live views' contexts stay active.
MultiSurfaceViewRasterizerallocated a base canvas (and WebGL context) when first accessed, and the rasterizer stayed inMultiSurfaceRasterizer's registry after the view was disposed.After: the base canvas is created on first draw, and disposed view rasterizers are removed from the registry.
dispose()twice on aSkwasmSurfacedestroyed the native surface twice.After:
dispose()is idempotent on bothCkSurfaceandSkwasmSurface.PlatformViewEmbedder.submitFrame.After:
ViewRasterizer.draw()skips submitting the frame for a disposed view, and the render future completes normally.Where to focus
CkSurface._releaseCanvas()ordering (canvaskit/surface.dart):SkSurfacedispose → abandon/deleteGrContext→ release the canvas (unregisters thewebglcontextlostlistener before losing the context, so explicit loss doesn't trigger recovery) →WEBGL_lose_context→GL.deleteContext. Every CanvasKit GL entry point re-binds its own context, so deleting the current one doesn't affect other live surfaces.compositing/surface.dart,compositing/rasterizer.dart): subclasses don't check disposal per method. A disposed surface is unreachable instead: its context-lost listener is removed,SurfaceProviderstops tracking it, andViewRasterizer.draw()doesn't submit frames for disposed views.baseCanvas(compositing/display_canvas_factory.dart):forEachCanvas,isLive,releaseCanvas,_canvasCountanddisposeread the nullable field directly so they never allocate a canvas as a side effect.lib/src/engine/compositing/surface.dart,lib/src/engine/compositing/rasterizer.dart,lib/src/engine/canvaskit/surface.dart.test/canvaskit/multi_surface_view_disposal_test.dartreproduces the issue in Chrome. It counts WebGL contexts created and still active across 10 add/remove cycles, and covers context loss on a disposed view, software mode, disposal mid-render, and idempotent disposal.Pre-launch Checklist
///).If you need help, consider asking for advice on the #hackers-new channel on Discord.
If this change needs to override an active code freeze, provide a comment explaining why. The code freeze workflow can be overridden by code reviewers. See pinned issues for any active code freezes with guidance.
Note: The Flutter team is currently trialing the use of Gemini Code Assist for GitHub. Comments from the
gemini-code-assistbot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed.