Repository navigation
[web] Release ImageSource on GC and fix Picture finalizer cycles - #197245
Conversation
Tie EngineImage's ImageSource reference count to its shared CountedRef box and wrap _StaticEngineCodec's ImageSource in a UniqueRef so ImageBitmap.close() and HTMLImageElement.src cleanup run when undisposed images, clones, ImageShaders, or static codecs are finalized by GC. Build UniqueRef onDispose callbacks via static helpers in EngineImage, _StaticEngineCodec, CkPicture, and SkwasmPicture so DomFinalizationRegistry's strongly held UniqueRef never captures `this` and retains its registered CountedRef target. Also make EngineCodec, CkImageDelegate, and SkwasmImage disposal idempotent and clarify the MakeLazyImageFromImageBitmap premultiplied-alpha comment.
There was a problem hiding this comment.
Code Review
This pull request refactors resource disposal and finalization logic across CanvasKit, Skwasm, and primitive image/codec implementations to prevent memory leaks and retainment cycles. Specifically, it introduces static disposer helpers to avoid capturing this in UniqueRef disposal callbacks, ensures dispose methods are idempotent, and adds comprehensive unit tests for garbage collection and finalization behavior. The reviewer recommends wrapping native disposal calls in try-finally blocks within these static disposers to guarantee that resource releases (such as source.release() and tracker.releaseAll()) are executed even if an exception occurs during native object disposal.
|
@harryterkelsen holding off a tiny bit until I do some more digging RE internal chat w/ @mdebbar (and you) |
|
Golden file changes have been found for this pull request. Click here to view and triage (e.g. because this is an intentional change). If you are still iterating on this change and are not ready to resolve the images on the Flutter Gold dashboard, consider marking this PR as a draft pull request above. You will still be able to view image results on the dashboard, commenting will be silenced, and the check will not try to resolve itself until marked ready for review. For more guidance, visit Writing a golden file test for Reviewers: Read the Tree Hygiene page and make sure this patch meets those guidelines before LGTMing. |
…r samplers - Retain `PictureImageTracker` sources on `EngineImage` instances created by `SkwasmPicture.toImageSync` and propagate them through `EngineImage.clone` and `PictureImageTracker.recordImage`. - Clone sampler images in `EngineFragmentShader.setImageSampler` and dispose the retained clones on slot replacement, creation error, and shader disposal. - Add unit tests covering deferred `SkwasmPicture.toImageSync` snapshots, `FragmentShader.setImageSampler` pre-recording source disposal, and `EngineImage` tracker release on `BackendImage.dispose` errors.
|
25d02e4 retains
Historical
|
- Invoke `_backendShader.setImageSampler` inside the `try` block before detaching/disposing previous bindings or mutating sampler maps, disposing both `sampler` and `clonedImage` on failure. - Document why `_samplerImages` and `_retainedSamplerImages` are maintained side by side on `EngineFragmentShader`. - Update `CkPicture._createDisposer` doc comment references to match symbols in scope in `canvaskit/picture.dart`. - Add a unit test verifying out-of-bounds `setImageSampler` indices preserve existing bindings and release the cloned image handle.
mdebbar
left a comment
There was a problem hiding this comment.
I checked this locally: with the old this-capturing closures restored in both picture.dart files, every test in this PR still passes. A test that awaits gc({type: 'major', execution: 'async'}) fails with the old closures and passes with the new ones, on both dart2js and dart2wasm.
…n tests
- Record `foreground` and `background` paints in `EngineParagraphBuilder.pushStyle` (with `EngineParagraphBuilder.finalizer` for abandoned builders), retain the `PictureImageTracker` on `EngineParagraph`, and propagate it in `EngineCanvas.drawParagraph`.
- Pass `--js-flags=--expose-gc` in `dev/chrome.dart` and add `gc({type: 'major', execution: 'async'})` tests exercising `DomFinalizationRegistry` collection for undisposed `Picture`, `Paragraph`, and abandoned `ParagraphBuilder` instances plus paragraph `ImageShader` rendering after GC.
- Document `SkwasmRenderer.dumpDebugInfo` array offsets on `_liveImageCount` and `_livePictureCount` in `test/skwasm/native_memory_test.dart`.
|
Added |
Roll Flutter from b75c5b30406a to 06f1c24345a2 (37 revisions) flutter/flutter@b75c5b3...06f1c24 2026-11-25 [email protected] Roll Skia from a60d883b3fe3 to e84ecd98d9f2 (2 revisions) (flutter/flutter#197375) 2026-11-25 [email protected] Roll Skia from ca229e319550 to a60d883b3fe3 (4 revisions) (flutter/flutter#197371) 2026-11-25 [email protected] Roll Skia from 6f75212e5a23 to ca229e319550 (2 revisions) (flutter/flutter#197369) 2026-11-25 [email protected] Roll Skia from 75d95595f14e to 6f75212e5a23 (1 revision) (flutter/flutter#197364) 2026-11-25 [email protected] [Windows] Fix Korean 3-beolsik IME dropping space, digits and punctuation (flutter/flutter#194270) 2026-11-25 [email protected] [flutter_tools] Strip embedded credentials from repository URLs (flutter/flutter#197219) 2026-11-25 [email protected] [flutter_tools] Add structured extension.log notifications for tool extensions (flutter/flutter#196714) 2026-11-25 [email protected] [flutter_tools] Share Depfile in flutter_tools_core and make BuildTarget.targetPlatform optional (flutter/flutter#194965) 2026-11-25 [email protected] Reply null asynchronously to ignored web platform messages and unskip missing-asset tests (flutter/flutter#197267) 2026-11-25 [email protected] Roll Dart SDK from 87f515c52de9 to 5202130a51b8 (1 revision) (flutter/flutter#197363) 2026-11-25 [email protected] [web] Retain queued scene pictures via ContainerLayer render pinning (flutter/flutter#196748) 2026-11-25 [email protected] [flutter_tools] Include dependency manifests in copyAssets depfile (flutter/flutter#196596) 2026-11-25 [email protected] Print the Intel Mac deprecation warning on every command (flutter/flutter#194071) 2026-11-25 [email protected] Roll Skia from 243c0dc9f662 to 75d95595f14e (2 revisions) (flutter/flutter#197351) 2026-11-25 [email protected] iOS: Ignore platform messages after the engine is destroyed (flutter/flutter#197310) 2026-11-24 [email protected] Bump customer tests to pick up material_ui cache extent test updates (flutter/flutter#197266) 2026-11-24 [email protected] [flutter_tools] Use refreshed FlutterVersion for flutter doctor feature flags (flutter/flutter#196944) 2026-11-24 [email protected] [flutter_tools] Do not crash if buildXcodeProject temporary directory is deleted before cleanup (flutter/flutter#195918) 2026-11-24 [email protected] Fix some `parameter_assignments` warnings (flutter/flutter#196815) 2026-11-24 [email protected] [flutter_tools] Extract PlatformDebuggingOptions and move WebDebugConfig (flutter/flutter#197229) 2026-11-24 [email protected] Fix desktop apps installing to the system prefix after a failed build (flutter/flutter#196482) 2026-11-24 [email protected] [flutter_tools] Write flutter test native_assets.json outside targetDir (flutter/flutter#196300) 2026-11-24 [email protected] iOS: Check the presented composition order in platform view tests (flutter/flutter#197302) 2026-11-24 [email protected] Run the shared Vulkan embedder tests under Impeller as well as Skia (flutter/flutter#193004) 2026-11-24 [email protected] Roll Fuchsia Linux SDK from BOgXtIYxLYcCkRou2... to HtAKfFLbfAQ6g96RY... (flutter/flutter#197334) 2026-11-24 [email protected] Roll Skia from b3dec9325fe1 to 243c0dc9f662 (6 revisions) (flutter/flutter#197333) 2026-11-24 [email protected] [flutter_tools] Delete globals.dart and context_runner.dart (flutter/flutter#196095) 2026-11-24 [email protected] Update viewInsets docs for translucent and rounded system UI (flutter/flutter#196355) 2026-11-24 [email protected] [flutter_tools] Check that dartaotruntime can run before starting the frontend server (flutter/flutter#194206) 2026-11-24 [email protected] [framework] Fix DraggableScrollableSheet '_hold == null' assertion when touch lifts during snap (flutter/flutter#195771) 2026-11-24 [email protected] [web] Release ImageSource on GC and fix Picture finalizer cycles (flutter/flutter#197245) 2026-11-24 [email protected] [flutter_tools] Fix web compiler output tracking in web builds (flutter/flutter#196563) 2026-11-24 [email protected] Upgrade CI to Xcode 27.2 (flutter/flutter#196807) 2026-11-24 [email protected] Roll Packages from 5b93485 to f455dfa (6 revisions) (flutter/flutter#197316) 2026-11-24 [email protected] [Linux] Fix deadlock presenting to a Wayland subsurface (flutter/flutter#196945) 2026-11-24 [email protected] Roll Skia from 2140958ee284 to b3dec9325fe1 (1 revision) (flutter/flutter#197309) 2026-11-24 [email protected] Roll Fuchsia Test Scripts from oEU515sDqSTvD8Spx... to GPtykFNizlaauBqzs... (flutter/flutter#197313) 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 ...
The branch was rebased onto master (ba17b71, 90 commits after the last base, ac8f87e), with which the pull request no longer merged: nine files conflicted, the first of them since 689d7b9 ("Upgrade CI to Xcode 27.2", flutter#196807). The replay gave each conflict to the replayed commit, so in those files the commits below this one hold the branch's old text, and they keep the lock file and the generated files of the old base. Of the 656 commits replayed (the 634 of the last push and 22 new ones) 646 keep their patch ids, nine changed (they touch files master changed too), and one is gone: "[flutter_tools] A test added upstream passes featureFlags", whose one line is upstream's own since flutter#197269. This commit's tree is the tree of a merge of the same master into the branch (those 656 commits), with the nine conflicts resolved by hand and six files more that master's 90 commits need: fifteen files differ from the merge as git writes it, and no other. The nine conflicts: - ci/builders/mac_clang_tidy.json: the branch's three builds, with upstream's Xcode (sdk_version 27b52, flutter#196807). - lib/web_ui/dev/chrome.dart: the branch's --remote-debugging-port=0 and upstream's --js-flags=--expose-gc (flutter#197245). - Seven test files of flutter_tools. Upstream removed testWithoutContext in favour of test (flutter#197259) and moved tests off testUsingContext (flutter#197246, flutter#197254, flutter#197257). build_system/targets/android_test.dart and ios_test.dart are master's with the branch's one line (the include is HostArtifact.shaderLib). localizations_test.dart is master's: the branch's one-line fix of it is upstream's flutter#197269 now. runner/local_engine_test.dart, android/ android_gradle_builder_test.dart, ios/xcodeproj_test.dart and tester/flutter_tester_test.dart are master's with the branch's tests as plain test() calls. Not conflicts in the text, and needed all the same (the six files): - artifacts_test.dart merged cleanly and called the removed testWithoutContext seven times: test() now. - The Scenario app's simulator runtime is iOS 27.2, as upstream's run_ios_tests.dart and goldens have it since flutter#196807: the converter's manifest.dart and the generated testing/ios_scenario_app/BUILD.bazel. - deps.lock.bzl for master's DEPS: the rolls of Skia, Dart and Dart's BoringSSL, the Fuchsia SDK and Fuchsia's test scripts. pub.lock.bzl does not change (upstream changed no pubspec). - The converter's output for two BUILD.gn files upstream changed: shell/platform/darwin/ios/BUILD.bazel (the new test source FlutterPlatformViewsControllerObjCTest.m, flutter#197429) and shell/platform/embedder/BUILD.bazel (the dependency on //flutter/impeller/renderer/backend/vulkan and two fixtures, flutter#193004). - dart format on two of the merged tests (artifacts_test.dart, xcodeproj_test.dart): test( is shorter than the name it replaces. Checked on this tree, all of it on Linux, with the Dart SDK DEPS pins (3.15.0-185.0.dev, the engine's prebuilt one): - gen_deps.dart and gen_pub_lock.dart, and both with --check; the converter regenerated and with --check (112 generated files current): the three files named above changed and no other. - dart format over the 98 Dart files that differ from master. - The analyzer over flutter_tools, dev/bots, flutter_goldens, the converter, bazel_tools and lib/web_ui/dev: no issues. - Tests: the ten tool test files the branch touches, localizations_test.dart and the test command's (399 tests); the converter's suite (319); dev/bots' bazel_test.dart, run_command_test.dart and test_test.dart (59). One of the 59 fails where no SHARD is set: upstream's "--dry-run prints every test that would run" inherits the environment, and without a shard a dry run on Linux ends at the first one, which throws off a Mac (master's code reads the same; not run there). With SHARD=framework_tests and SUBSHARD=misc, as its bot has them, it passes. - check_build_configs.sh, check_generated_bazel_files.sh, bazel_ci_test.py (36), engine_build_configs (84), bazel_tools (62), GN's own check (tools/gn) for a host debug build, tools/gn_test.py (7), ci/pylint.sh, ci/format.sh (its Python step through yapf directly, 14 files). - buildifier over the 364 Starlark files that differ from master. One warning, and an old one: build/bazel/toolchains/emscripten/spike/ BUILD.bazel calls sh_test without loading it from rules_shell. The file is the last push's; earlier runs gave buildifier only the files a change touched. Left as it is here. - Bazel analysis: ci_host_debug, host_release_test, //:tool_tests //:dart_tests, and every Linux build of builds.json with its install and its suite under its own configuration (47 of 47, 4 of them without RBE). The first analysis with the rolled Skia and Dart, whose BUILD files are generated when their repositories are set up. Not run: nothing was built, linked or run under Bazel on this tree, on Linux or on a Mac, and no Dart tool ran on a Mac. The merge's Mac and iOS side (the clang-tidy builds' Xcode, the Scenario app's runtime, the new iOS test source) and the new embedder dependency have their first build on the bots.
Releases underlying
ImageSourcereferences when undisposedEngineImage,ui.ImageShader, or_StaticEngineCodechandles are garbage-collected across CanvasKit and Skwasm. Also movesCkPictureandSkwasmPicturedisposal callbacks to static helpers soDomFinalizationRegistrydoes not strongly retain undisposedPictureinstances.EngineCodec,CkImageDelegate, andSkwasmImagedisposal idempotent so duplicate disposal calls are safe across explicitdispose()and GC finalization.ImageSourceacrossSkwasmPicture.toImageSyncdeferred images,EngineFragmentShader.setImageSamplersampler bindings, andEngineParagraphforeground/backgroundpaint shaders so disposing or collecting intermediate pictures, shaders, or source images does not close lazy texture sources early.Fixes #197242
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.