Skip to content

[web] Release CanvasKit WebGL contexts and surfaces when a view is removed - #196816

Merged
auto-submit[bot] merged 25 commits into
flutter:masterfrom
harryterkelsen:flutter-flutter-195025-web-canvaskit-view-goes
Nov 20, 2026
Merged

auto-submit[bot] merged 25 commits into
flutter:masterfrom
harryterkelsen:flutter-flutter-195025-web-canvaskit-view-goes

Conversation

@harryterkelsen

Copy link
Copy Markdown
Contributor

When a view is removed from a multi-view CanvasKit app, its MultiSurfaceViewRasterizer and the onscreen surfaces it created were never fully torn down. CkSurface.dispose() only disposed the SkSurface. It left the WebGL context, the Emscripten GL.contexts entry and the webglcontextlost listener in place, and the rasterizer stayed registered in MultiSurfaceRasterizer. When the browser later evicted one of those stale contexts, the removed view's surface handled webglcontextlost by acquiring a new canvas and creating a new context. After a few removeView/addView cycles 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:

  • The abstract Surface now owns disposal: dispose() is a non-virtual, idempotent template that calls a protected disposeResources() hook once, then onDispose.
  • CkSurface.disposeResources() releases the canvas through _releaseCanvas(). That abandons and deletes the GrContext, 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.
  • The abstract ViewRasterizer tracks whether it is disposed, and draw() stops if the view is disposed before or partway through a frame (after prepareToDraw()), so a removed view never submits a stale frame or allocates new canvases. Queued renders still complete.
  • MultiSurfaceViewRasterizer.dispose() removes itself from MultiSurfaceRasterizer and disposes its DisplayCanvasFactory, which now also removes canvases from the DOM. MultiSurfaceRasterizer.dispose() iterates over a copy of its map.
  • DisplayCanvasFactory.baseCanvas is created lazily, so a view that is disposed before its first frame never allocates a surface or WebGL context.
  • SurfaceProvider stops tracking surfaces once they are disposed (via Surface.onDispose).
  • SkwasmSurface now extends OffscreenSurface and implements disposeResources(), so it gets the same idempotent dispose(). This prevents a double surfaceDestroy on the native handle.

Fixes #195025

Behavioral Changes

  • Before: removing a CanvasKit view left its WebGL contexts alive. If the browser later lost one of them, the removed view recreated a canvas and context. After a few removeView/addView cycles 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.
  • Before: every MultiSurfaceViewRasterizer allocated a base canvas (and WebGL context) when first accessed, and the rasterizer stayed in MultiSurfaceRasterizer'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.
  • Before: calling dispose() twice on a SkwasmSurface destroyed the native surface twice.
    After: dispose() is idempotent on both CkSurface and SkwasmSurface.
  • Before: if a view was removed while a frame was being prepared, the frame was still submitted, which allocated display canvases for the removed view and could throw in 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): SkSurface dispose → abandon/delete GrContext → release the canvas (unregisters the webglcontextlost listener 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.
  • Disposal lives in the base classes (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, SurfaceProvider stops tracking it, and ViewRasterizer.draw() doesn't submit frames for disposed views.
  • Lazy baseCanvas (compositing/display_canvas_factory.dart): forEachCanvas, isLive, releaseCanvas, _canvasCount and dispose read the nullable field directly so they never allocate a canvas as a side effect.
  • Primary review files: lib/src/engine/compositing/surface.dart, lib/src/engine/compositing/rasterizer.dart, lib/src/engine/canvaskit/surface.dart.
  • Tests: test/canvaskit/multi_surface_view_disposal_test.dart reproduces 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-assist bot 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.

…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.
@github-actions github-actions Bot added engine flutter/engine related. See also e: labels. platform-web Web applications specifically team-web Owned by Web platform team labels Nov 17, 2026
@kevmoo

kevmoo commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

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 debugResetRasterizer() will now call rasterizer.dispose(), so Skwasm suites start running surface_destroy on every reset and the gaps may become more visible.

What the Skwasm side does today:

  1. _skwasm_destroyContext calls GL.deleteContext without WEBGL_lose_context (library_skwasm_support.js#L383-L392). Emscripten also keeps its current-context reference, so the last context survives GC.
  2. Surface::Dispose destroys render_context_ after the handle is gone, without binding it (surface.cc#L106-L111). With two surfaces, A's GL deletes go to B's context.
  3. ReceiveCanvasOnWorker overwrites gl_context_ without destroying the old handle (surface.cc#L136-L145).

What I measured (AI-assisted, prebuilt skwasm_heavy driven directly, single runs, software GL on Linux):

  • Destroying 12 surfaces at 2048×2048 freed almost no process memory before GC on Chrome 157, Firefox 157 and Playwright's Linux WebKit.
  • Patching loseContext() into the JS glue freed most of it on Chrome and Firefox, and almost none on Linux WebKit unless the canvas was resized to 0×0 first. Not checked on Safari.
  • On Chrome, (2) reproduced: deletes for surface A's objects ran against surface B's context.

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 Dispose and ReceiveCanvasOnWorker), but it hasn't been built or tested yet. I'm happy to send it as a follow-up once this lands, or pass it along if you'd rather fold it in here. Whichever is easier for you.

@harryterkelsen
harryterkelsen marked this pull request as ready for review November 18, 2026 17:53
@harryterkelsen harryterkelsen added the CICD Run CI/CD label Nov 18, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@harryterkelsen

Copy link
Copy Markdown
Contributor Author

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 debugResetRasterizer() will now call rasterizer.dispose(), so Skwasm suites start running surface_destroy on every reset and the gaps may become more visible.

What the Skwasm side does today:

  1. _skwasm_destroyContext calls GL.deleteContext without WEBGL_lose_context (library_skwasm_support.js#L383-L392). Emscripten also keeps its current-context reference, so the last context survives GC.
  2. Surface::Dispose destroys render_context_ after the handle is gone, without binding it (surface.cc#L106-L111). With two surfaces, A's GL deletes go to B's context.
  3. ReceiveCanvasOnWorker overwrites gl_context_ without destroying the old handle (surface.cc#L136-L145).

What I measured (AI-assisted, prebuilt skwasm_heavy driven directly, single runs, software GL on Linux):

  • Destroying 12 surfaces at 2048×2048 freed almost no process memory before GC on Chrome 157, Firefox 157 and Playwright's Linux WebKit.
  • Patching loseContext() into the JS glue freed most of it on Chrome and Firefox, and almost none on Linux WebKit unless the canvas was resized to 0×0 first. Not checked on Safari.
  • On Chrome, (2) reproduced: deletes for surface A's objects ran against surface B's context.

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 Dispose and ReceiveCanvasOnWorker), but it hasn't been built or tested yet. I'm happy to send it as a follow-up once this lands, or pass it along if you'd rather fold it in here. Whichever is easier for you.

@kevmoo this sounds like it's definitely worth fixing. Please send the follow-up PR after this one lands

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 mdebbar left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@harryterkelsen harryterkelsen added the autosubmit Merge PR when tree becomes green via auto submit App label Nov 20, 2026
@auto-submit
auto-submit Bot added this pull request to the merge queue Nov 20, 2026
Merged via the queue into flutter:master with commit 98ed019 Nov 20, 2026
21 checks passed
@flutter-dashboard flutter-dashboard Bot removed the autosubmit Merge PR when tree becomes green via auto submit App label Nov 20, 2026
auto-submit Bot pushed a commit to flutter/packages that referenced this pull request Nov 21, 2026
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CICD Run CI/CD engine flutter/engine related. See also e: labels. platform-web Web applications specifically team-web Owned by Web platform team

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[web] CanvasKit view goes blank after a few removeView/addView cycles in Safari: too many active WebGL contexts

3 participants