Skip to content

[web] Fix CanvasKit fragment shader uniforms being freed or mutated after recording - #195718

Merged
auto-submit[bot] merged 9 commits into
flutter:masterfrom
harryterkelsen:flutter-flutter-193221-web-disposing-a-shader
Nov 3, 2026
Merged

auto-submit[bot] merged 9 commits into
flutter:masterfrom
harryterkelsen:flutter-flutter-193221-web-disposing-a-shader

Conversation

@harryterkelsen

@harryterkelsen harryterkelsen commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

On the CanvasKit renderer, a ui.FragmentShader disposed after a draw call (but before the recorded ui.Picture is rasterized) corrupted the picture. Picture.toImage sampled black instead of the shader's color, and a later shader could take over the earlier draw's colors.

The cause: CkFragmentShader kept its uniforms in a buffer allocated with CanvasKit.Malloc and passed that buffer straight to RuntimeEffect.makeShader. For malloc'd arrays, CanvasKit wraps the memory with SkData::MakeWithoutCopy, so every recorded SkShader aliased the shader's mutable staging buffer, and dispose() then freed it. The GC finalizer frees it the same way, so apps that never call dispose() could hit this too, depending on GC timing.

This PR stores the uniforms in a plain Dart Float32List and passes floats.toJS to makeShader / makeShaderWithChildren. CanvasKit copies a non-malloc'd typed array into its own allocation, and the resulting SkShader owns it (SkData::MakeFromMalloc). Each recorded draw therefore gets its own uniform snapshot. Native Flutter's ReusableFragmentShader behaves the same way: it copies the uniforms on every draw. dispose() no longer frees a staging buffer; it only releases the cached SkShader handle.

Fixes #193221

Behavioral Changes

These apply to the CanvasKit renderer only; Skwasm is unchanged.

  • Disposing a fragment shader after recording, before rasterizing:
    • Before: picture.toImage returned corrupted pixels, e.g. [0, 0, 0, 255] for a shader that outputs opaque red.
    • After: it returns [255, 0, 0, 255], the color the shader had when it was drawn.
  • Disposing shader A after drawing with it, then creating and drawing shader B, in the same picture:
    • Before: shader B could reuse A's freed uniform memory, so A's box rendered in B's color.
    • After: each box keeps its own color.
  • Calling setFloat / uniform setters on a shader between draw calls in the same picture:
    • Before: every earlier draw took on the latest uniform values.
    • After: each draw keeps the uniforms it was recorded with.
  • Image-sampler shaders: the texture-size uniforms recorded with a draw no longer get corrupted when the shader is disposed before rasterization.

Where to focus

  • lib/src/engine/canvaskit/fragment_shader.dart holds the core change.
    • The key point is the comment in skShader: correctness depends on passing a non-malloc'd typed array, because CanvasKit only takes ownership of a copy in that case (it checks the _ck marker in rt_shader.js).
    • This holds on dart2js, where toJS returns the same array, and on dart2wasm, where toJS produces a fresh JS array.
  • lib/src/engine/canvaskit/canvaskit_api.dart: SkRuntimeEffect.makeShader and makeShaderWithChildren now accept JSAny uniforms instead of SkFloat32List. Existing callers that pass SkFloat32List (the API tests) still compile.
  • Cost: each skShader call now does one small malloc plus a copy of N floats. This matches native behavior. Caching the SkShader across draws while uniforms are unchanged is intentionally left for a follow-up.
  • Skwasm: Skwasm already keeps disposed-shader uniforms alive through ref-counting, so the disposal tests pass there. It does still share a single uniform buffer between draws of the same shader. That's why the per-draw mutation test is skipped on Skwasm, with a comment explaining it. Fixing that is a separate change.
  • test/ui/fragment_shader_test.dart: pixel-readback regression tests, one per aliasing route:
    • dispose then rasterize, including re-rasterizing and nesting the picture
    • freed-memory reuse by a later shader
    • image-sampler dispose
    • per-draw uniform mutation
    • sampler replacement between draws
    • a shader with no uniforms

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 Oct 30, 2026
@harryterkelsen
harryterkelsen marked this pull request as ready for review October 30, 2026 22:48
@harryterkelsen harryterkelsen added the CICD Run CI/CD label Oct 30, 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 modifies the CanvasKit web backend to pass fragment shader uniforms as plain JS typed arrays instead of CanvasKit-malloc'd memory. This ensures CanvasKit copies the uniforms into a buffer owned by the new SkShader, preventing recorded pictures from aliasing the mutable staging buffer and observing subsequent mutations or disposal. Consequently, CkFragmentShader now uses standard Float32List instead of SkFloat32List, eliminating manual memory allocation and freeing. Multiple regression tests have been added to verify correct behavior under shader disposal, mutation, and sampler replacement. No review comments were provided, so there is no additional feedback.

Narrow SkRuntimeEffect.makeShader and makeShaderWithChildren to accept a
JSFloat32Array instead of JSAny so passing a CanvasKit-malloc'd
SkFloat32List (which would alias mutable WASM memory) is a compile-time
error. Update the RuntimeEffect API test to pass plain typed arrays.

@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.

LGTM!

mdebbar
mdebbar previously approved these changes Nov 2, 2026
@harryterkelsen harryterkelsen added the autosubmit Merge PR when tree becomes green via auto submit App label Nov 2, 2026
@auto-submit auto-submit Bot removed the autosubmit Merge PR when tree becomes green via auto submit App label Nov 2, 2026
@auto-submit

auto-submit Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

autosubmit label was removed for flutter/flutter/195718, because - The status or check suite Dashboard Checks has failed. Please fix the issues identified (or deflake) before re-applying this label.

@harryterkelsen harryterkelsen added the autosubmit Merge PR when tree becomes green via auto submit App label Nov 2, 2026
@auto-submit
auto-submit Bot added this pull request to the merge queue Nov 2, 2026
Merged via the queue into flutter:master with commit 1c7c4db Nov 3, 2026
22 of 23 checks passed
@flutter-dashboard flutter-dashboard Bot removed the autosubmit Merge PR when tree becomes green via auto submit App label Nov 3, 2026
gmackall pushed a commit to gmackall/flutter that referenced this pull request Nov 3, 2026
…fter recording (flutter#195718)

On the CanvasKit renderer, a `ui.FragmentShader` disposed after a draw
call (but before the recorded `ui.Picture` is rasterized) corrupted the
picture. `Picture.toImage` sampled black instead of the shader's color,
and a later shader could take over the earlier draw's colors.

The cause: `CkFragmentShader` kept its uniforms in a buffer allocated
with `CanvasKit.Malloc` and passed that buffer straight to
`RuntimeEffect.makeShader`. For malloc'd arrays, CanvasKit wraps the
memory with `SkData::MakeWithoutCopy`, so every recorded `SkShader`
aliased the shader's mutable staging buffer, and `dispose()` then freed
it. The GC finalizer frees it the same way, so apps that never call
`dispose()` could hit this too, depending on GC timing.

This PR stores the uniforms in a plain Dart `Float32List` and passes
`floats.toJS` to `makeShader` / `makeShaderWithChildren`. CanvasKit
copies a non-malloc'd typed array into its own allocation, and the
resulting `SkShader` owns it (`SkData::MakeFromMalloc`). Each recorded
draw therefore gets its own uniform snapshot. Native Flutter's
`ReusableFragmentShader` behaves the same way: it copies the uniforms on
every draw. `dispose()` no longer frees a staging buffer; it only
releases the cached `SkShader` handle.

Fixes flutter#193221

## Behavioral Changes

These apply to the CanvasKit renderer only; Skwasm is unchanged.

- Disposing a fragment shader after recording, before rasterizing:
- Before: `picture.toImage` returned corrupted pixels, e.g. `[0, 0, 0,
255]` for a shader that outputs opaque red.
- After: it returns `[255, 0, 0, 255]`, the color the shader had when it
was drawn.
- Disposing shader A after drawing with it, then creating and drawing
shader B, in the same picture:
- Before: shader B could reuse A's freed uniform memory, so A's box
rendered in B's color.
  - After: each box keeps its own color.
- Calling `setFloat` / uniform setters on a shader between draw calls in
the same picture:
  - Before: every earlier draw took on the latest uniform values.
  - After: each draw keeps the uniforms it was recorded with.
- Image-sampler shaders: the texture-size uniforms recorded with a draw
no longer get corrupted when the shader is disposed before
rasterization.

## Where to focus

- **`lib/src/engine/canvaskit/fragment_shader.dart`** holds the core
change.
- The key point is the comment in `skShader`: correctness depends on
passing a *non*-malloc'd typed array, because CanvasKit only takes
ownership of a copy in that case (it checks the `_ck` marker in
`rt_shader.js`).
- This holds on dart2js, where `toJS` returns the same array, and on
dart2wasm, where `toJS` produces a fresh JS array.
- **`lib/src/engine/canvaskit/canvaskit_api.dart`**:
`SkRuntimeEffect.makeShader` and `makeShaderWithChildren` now accept
`JSAny` uniforms instead of `SkFloat32List`. Existing callers that pass
`SkFloat32List` (the API tests) still compile.
- **Cost:** each `skShader` call now does one small malloc plus a copy
of N floats. This matches native behavior. Caching the `SkShader` across
draws while uniforms are unchanged is intentionally left for a
follow-up.
- **Skwasm:** Skwasm already keeps disposed-shader uniforms alive
through ref-counting, so the disposal tests pass there. It does still
share a single uniform buffer between draws of the same shader. That's
why the per-draw mutation test is skipped on Skwasm, with a comment
explaining it. Fixing that is a separate change.
- **`test/ui/fragment_shader_test.dart`**: pixel-readback regression
tests, one per aliasing route:
- dispose then rasterize, including re-rasterizing and nesting the
picture
  - freed-memory reuse by a later shader
  - image-sampler dispose
  - per-draw uniform mutation
  - sampler replacement between draws
  - a shader with no uniforms

## Pre-launch Checklist

- [x] I read the [Contributor Guide] and followed the process outlined
there for submitting PRs.
- [x] I read the [AI contribution guidelines] and understand my
responsibilities, or I am not using AI tools.
- [x] I read the [Tree Hygiene] wiki page, which explains my
responsibilities.
- [x] I read and followed the [Flutter Style Guide], including [Features
we expect every widget to implement].
- [x] I signed the [CLA].
- [x] I listed at least one issue that this PR fixes in the description
above.
- [x] I updated/added relevant in-code documentation (doc comments with
`///`).
- [x] If this PR introduces a new feature or capability, I created and
linked a website documentation issue or PR in [flutter/website] (or
verified none is needed).
- [x] I added new tests to check the change I am making, or this PR is
[test-exempt].
- [x] I followed the [breaking change policy] and added [Data Driven
Fixes] where supported.
- [x] All existing and new tests are passing.

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](https://developers.google.com/gemini-code-assist/docs/review-github-code).
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.

<!-- Links -->
[Contributor Guide]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview
[AI contribution guidelines]:
https://github.com/flutter/flutter/blob/main/CONTRIBUTING.ai.md
[Tree Hygiene]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md
[test-exempt]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests
[Flutter Style Guide]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md
[Features we expect every widget to implement]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement
[CLA]: https://cla.developers.google.com/
[flutter/tests]: https://github.com/flutter/tests
[flutter/website]: https://github.com/flutter/website
[breaking change policy]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes
[Discord]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md
[Data Driven Fixes]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md
auto-submit Bot pushed a commit to flutter/packages that referenced this pull request Nov 3, 2026
Roll Flutter from fcfb4f203eae to 934720261be0 (38 revisions)

flutter/flutter@fcfb4f2...9347202

2026-11-03 [email protected] Roll Skia from 5bceaa033999 to c733ad3e37cb (5 revisions) (flutter/flutter#195872)
2026-11-03 [email protected] Roll Skia from 34d2bf479385 to 5bceaa033999 (9 revisions) (flutter/flutter#195864)
2026-11-03 [email protected] fix: prefer pointer events over semantics tap for mouse clicks on web (flutter/flutter#191529)
2026-11-03 [email protected] [VPAT] Expose a semantics text field value while it is not being edited (flutter/flutter#195445)
2026-11-03 [email protected] [Impeller] Make a GL context current before constructing an AiksContext without a surface (flutter/flutter#195629)
2026-11-03 [email protected] [flutter_tools] Eliminate globals.dart from project.dart (flutter/flutter#194066)
2026-11-03 [email protected] [tool] Complete context runner elimination and migrate AppContext usages to ToolContext (flutter/flutter#190797)
2026-11-03 [email protected] [web] Unify font collections between CanvasKit and Skwasm (flutter/flutter#195539)
2026-11-03 [email protected] [Android] Replay predictive back state for retained engines (flutter/flutter#192286)
2026-11-03 [email protected] [vulkan]: Adds depth/stencil synchronization for subpasses (flutter/flutter#195689)
2026-11-03 [email protected] [web] Honor requested upscaling in instantiateImageCodecWithSize and ImageDescriptor.instantiateCodec (flutter/flutter#195836)
2026-11-03 [email protected] Roll Skia from 866b61ca92c9 to 34d2bf479385 (9 revisions) (flutter/flutter#195848)
2026-11-03 [email protected] Roll Fuchsia Test Scripts from xl1LWBuppzu-BnOzV... to B6zarykZp6PKWRueg... (flutter/flutter#195847)
2026-11-03 [email protected] Remove unused ffi (flutter/flutter#195710)
2026-11-02 [email protected] Revert: [Android] Let the raster thread use every core of a chip without little cores (flutter/flutter#195838)
2026-11-02 [email protected] Run 10 impeller iOS benchmarks as one devicelab task (flutter/flutter#195661)
2026-11-02 [email protected] Use named uniforms instead of setFloat in StretchEffect (flutter/flutter#195372)
2026-11-02 [email protected] [flutter_tools] Report when the browser disconnects during a web test run (flutter/flutter#192198)
2026-11-02 [email protected] fix: Resolve memory leak in image_list example (flutter/flutter#189526)
2026-11-02 [email protected] Only run the common local engine configurations in presubmit (flutter/flutter#195688)
2026-11-02 [email protected] Update gcloud_version to version [email protected] (flutter/flutter#195769)
2026-11-02 [email protected] [Impeller] Order the Vulkan copy-texture-to-texture layout transition after the copy (flutter/flutter#195814)
2026-11-02 [email protected] [Impeller] Order the Vulkan ResizeTexture layout transition after its blit (flutter/flutter#195721)
2026-11-02 [email protected] [web] Fix CanvasKit fragment shader uniforms being freed or mutated after recording (flutter/flutter#195718)
2026-11-02 [email protected] Roll Fuchsia Linux SDK from MqypI6RNyVZ_FLUE-... to T_-6-6X1lDMghhAvX... (flutter/flutter#195809)
2026-11-02 [email protected] [Android] Log why Impeller falls back to OpenGLES (flutter/flutter#194764)
2026-11-02 [email protected] Roll Skia from 3f35fb6e591b to 866b61ca92c9 (11 revisions) (flutter/flutter#195802)
2026-11-02 [email protected] Roll Skia from 3f35fb6e591b to 866b61ca92c9 (11 revisions) (flutter/flutter#195802)
2026-11-02 [email protected] Only run the common local engine configurations in presubmit (flutter/flutter#195688)
2026-11-02 [email protected] Balance tool_integration_tests subshards by expected duration (flutter/flutter#195628)
2026-11-02 [email protected] [web_paragraph] Map code units without a cluster to a cluster (flutter/flutter#195384)
2026-11-02 [email protected] [web] Hide synthetic autofill inputs from assistive technology (flutter/flutter#195618)
2026-11-02 [email protected] Roll Packages from 3742a4e to 3f34a6f (8 revisions) (flutter/flutter#195795)
2026-11-02 [email protected] [web] Unskip web tests that pass on CanvasKit and Skwasm: platform_view_test, route_notification_messages_test (flutter/flutter#195605)
2026-11-02 [email protected] Roll Skia from e5ad3868b8db to 3f35fb6e591b (1 revision) (flutter/flutter#195789)
2026-11-02 [email protected] Roll Skia from f5215e74aa16 to e5ad3868b8db (3 revisions) (flutter/flutter#195779)
2026-11-02 [email protected] Roll Skia from e43478a2f9f8 to f5215e74aa16 (1 revision) (flutter/flutter#195776)
2026-11-01 [email protected] Roll Fuchsia Linux SDK from kW0A0xxNkqf38ljm4... to MqypI6RNyVZ_FLUE-... (flutter/flutter#195768)

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
...
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] Disposing a shader before Picture.toImage changes sampled pixels in Chrome

2 participants