Skip to content

[web] Recover CanvasKit surfaces from WebGL failures without per-frame null crashes - #196257

Merged
auto-submit[bot] merged 10 commits into
flutter:masterfrom
harryterkelsen:flutter-flutter-162868-occasional-bursts-of-null
Nov 17, 2026
Merged

auto-submit[bot] merged 10 commits into
flutter:masterfrom
harryterkelsen:flutter-flutter-162868-occasional-bursts-of-null

Conversation

@harryterkelsen

Copy link
Copy Markdown
Contributor

When WebGL fails, CanvasKit surfaces fall back to software rendering, but they did it on the same canvas that already owned the WebGL context. Per the HTML canvas spec, getContext('2d') returns null on a canvas bound to WebGL. CanvasKit's CPU surface calls that on every flush(), so each frame threw TypeError: Cannot read properties of null (reading 'putImageData'), which dart2js reports as Null check operator used on a null value. This happens with MakeOnScreenGLSurface returning null on resize, MakeGrContext failing, or a lost context. Separately, if recreateContextForCanvas received a canvas whose context was already lost, MakeGrContext threw (null.rangeMin inside CanvasKit). That error escaped context recreation and left the surface with no SkSurface.

This PR makes CkSurface (onscreen and offscreen) recover cleanly:

  • A software fallback on a canvas that already requested a WebGL context first releases that canvas, frees its WebGL context and GrContext, and switches to a fresh canvas. This happens once; later resizes reuse the fresh canvas.
  • Exceptions from MakeGrContext, and a failed WebGL context request, now trigger the software fallback instead of escaping.
  • When the canvas is replaced (context loss or offscreen buffer-clamp recovery), the old canvas is released and removed from the DOM, so the onscreen host element always holds exactly one canvas.
  • The overlay position: absolute style is stored on the surface and reapplied to replacement canvases.
  • initialized always completes. handledContextLossEvent completes after recovery, including when recovery fails, and onContextLost asserts that the surface is not already in software mode.
  • Offscreen buffer-clamp recovery skips the WebGL drawing-buffer check when the replacement canvas has fallen back to software rendering, avoiding binding a WebGL context to the software canvas.

Fixes #162868

Behavioral Changes

  • Software fallback after a WebGL failure. Before: falling back (e.g. MakeOnScreenGLSurface returning null on resize) kept rendering into the canvas that owned the WebGL context, and every later rasterizeToCanvas threw Null check operator used on a null value / null.putImageData. After: the surface switches to a new canvas once and renders on the CPU without errors. CkSurface.canvas returns the new canvas, and glContext becomes -1.
  • Recreating on a lost-context canvas. Before: recreateContextForCanvas with a canvas whose WebGL context was already lost completed with an error, and skSurface stayed null; through onContextLost this was an unhandled async error. After: it completes normally and the surface renders in software mode.
  • The replaced canvas is released. Before: replacing the canvas left the old <canvas> in CkOnscreenSurface.hostElement (two children after a context loss), and the offscreen path's old GrContext / WebGL context were never freed. After: the old canvas is removed from the DOM, its webglcontextlost listener is removed, and its GrContext and still-live WebGL context are freed.
  • Overlay style. Before: setIsOverlay(true) styled only the current canvas, so a replacement canvas lost position: absolute. After: the style is reapplied whenever a canvas is attached.
  • Initialization and context-loss invariants. Before: if surface creation threw during construction, initialized never completed, and handledContextLossEvent completed before recovery started. After: initialized always completes (logging a warning on failure), handledContextLossEvent completes once recovery has finished or failed, and onContextLost asserts !isSoftware in debug mode.
  • Offscreen buffer-clamp recovery. Before: if the replacement canvas fell back to software, the clamp check still asked it for a WebGL context, breaking 2D software rendering on that canvas. After: the clamp check is skipped in software mode.

Where to focus

  • Primary file: engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/surface.dart, mainly _recreateSoftwareSkSurface, _swapCanvasForSoftwareRendering, _releaseCanvas and _replaceCanvas. Tests are in engine/src/flutter/lib/web_ui/test/canvaskit/surface_gl_failure_test.dart.
  • Tracking which canvases have used WebGL: _canvasHasWebGlContext is set before requesting a WebGL context on the current canvas. A software fallback swaps the canvas only when that flag is set, so the swap happens at most once per WebGL-to-software transition. _failedToCreateGrContext stays set, so the surface never switches back to WebGL on the new canvas. Checking getContext('2d') on every frame was rejected because it adds DOM interop to the hot path.
  • Teardown order in _releaseCanvas: CanvasProvider.releaseCanvas runs before the old WebGL context is lost on purpose. Releasing the canvas removes its webglcontextlost listener, so losing the context explicitly does not trigger onContextLost (which now asserts !isSoftware). The context is lost only if one was actually created (_glContext > 0): calling getContext on a canvas whose initial request failed could allocate a new WebGL context just to lose it.
  • No runtime canvas type checks: subclasses supply _webGlContextOf, so CkSurface never runs isA<DomOffscreenCanvas>(). That check evaluates instanceof OffscreenCanvas and throws in browsers that do not define OffscreenCanvas, and Safari is where this crash is reported most.
  • Direct _replaceCanvas helper: offscreen clamp recovery and onContextLost read supportsWebGl and canvas immediately after replacing the canvas, so they call _replaceCanvas directly rather than going through the async recreateContextForCanvas wrapper.
  • Known limitation: a context loss that happens between frames and shows up as MakeOnScreenGLSurface returning null now leaves that surface in software mode permanently, instead of throwing on every frame.

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.

@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 9, 2026
@harryterkelsen
harryterkelsen marked this pull request as ready for review November 10, 2026 00:40

@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 refactors the CanvasKit surface implementation to improve WebGL context loss recovery and software fallback handling, ensuring resources are properly released and the canvas is replaced when switching to software rendering. It also adds a comprehensive suite of regression tests. The review feedback identifies a redundant canvas release in _replaceCanvasWithSize and suggests throwing an error if MakeOnScreenGLSurface returns null to guarantee that the software fallback is correctly triggered.

@harryterkelsen harryterkelsen added the CICD Run CI/CD label Nov 10, 2026
_replaceCanvasWithSize called _releaseCanvasAndContext() and then
_replaceCanvas(), which calls _releaseCanvas() again on the same,
already-released canvas. Release it once via _releaseCanvas() and then
acquire and initialize the new canvas directly.
mdebbar
mdebbar previously approved these changes Nov 12, 2026
@harryterkelsen harryterkelsen added the autosubmit Merge PR when tree becomes green via auto submit App label Nov 17, 2026
@auto-submit
auto-submit Bot added this pull request to the merge queue Nov 17, 2026
Merged via the queue into flutter:master with commit c60d44a Nov 17, 2026
22 checks passed
@flutter-dashboard flutter-dashboard Bot removed the autosubmit Merge PR when tree becomes green via auto submit App label Nov 17, 2026
LouiseHsu pushed a commit to flutter/packages that referenced this pull request Nov 18, 2026
flutter/flutter@2f09f96...06f32f8

2026-11-18 [email protected] Move macOS
desktop builds to ThinLTO (flutter/flutter#196804)
2026-11-18 [email protected] Roll Dart SDK from
5ed55b4b2ebc to 753488ede427 (2 revisions) (flutter/flutter#196893)
2026-11-18 [email protected] Roll Packages from
9af69be to dca2e58 (7 revisions) (flutter/flutter#196892)
2026-11-18 [email protected] Roll Skia from 503a380ebecc
to 81ee7327e81c (29 revisions) (flutter/flutter#196889)
2026-11-18 [email protected] Roll Dart SDK from
26e38955d9d4 to 5ed55b4b2ebc (4 revisions) (flutter/flutter#196843)
2026-11-18 [email protected] Fix permissions for action updates
(flutter/flutter#196791)
2026-11-18 [email protected] iOS: Apply platform view mutators from
FlutterPlatformViewLayer (flutter/flutter#196753)
2026-11-18 [email protected] [flutter_tools] Remove ambient Doctor,
FeatureFlags, and device getters (flutter/flutter#196572)
2026-11-18 [email protected] Fix
RelativeRect.lerp crash when b is null (flutter/flutter#196655)
2026-11-18 [email protected] [web] Harden
WebP and GIF header readers against truncated and malformed buffers
(flutter/flutter#196075)
2026-11-17 [email protected] Enable apps to
control focus behavior during app lifecycle changes via
`FocusLifecyclePolicy` (flutter/flutter#190570)
2026-11-17 [email protected] Don't re-run the code freeze check
on label changes (flutter/flutter#196745)
2026-11-17 [email protected] Android: Report
FlutterView as a text editor while a text input client is attached
(flutter/flutter#193074)
2026-11-17 [email protected] Roll Packages from
4c6a7d3 to 9af69be (5 revisions) (flutter/flutter#196812)
2026-11-17 [email protected] [flutter_tools] Handle target VM filesystem
errors in DevFS.create (flutter/flutter#196234)
2026-11-17 [email protected] [flutter_tools] Clarify analytics reporting
status when on a feature branch (flutter/flutter#194496)
2026-11-17 [email protected] [web] Recover
CanvasKit surfaces from WebGL failures without per-frame null crashes
(flutter/flutter#196257)
2026-11-17 [email protected] [devicelab] Trigger navigation tap via
Flutter Driver in service_extensions_test (flutter/flutter#194456)

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.

Occasional bursts of "Null check operator used on a null value" on the web

2 participants