Skip to content

Add a deferred platform-view-created path to the shell and use it on Android - #196342

Merged
auto-submit[bot] merged 8 commits into
flutter:masterfrom
gmackall:async-notify-created
Nov 13, 2026
Merged

auto-submit[bot] merged 8 commits into
flutter:masterfrom
gmackall:async-notify-created

Conversation

@gmackall

@gmackall gmackall commented Nov 10, 2026 •

Copy link
Copy Markdown
Member

... and also make PlatformViewAndroid::NotifyChanged non-blocking at the same time.

On Android, surfaceCreated and surfaceChanged currently block the main thread until the raster thread has finished any queued SetupImpellerContext() work, created the swapchain, and set up the rasterizer. Because this runs inside the first view traversal, both the Activity's first native draw and Dart's first frame wait behind it (~80–110 ms on mid/low-tier Android devices with Impeller Vulkan, e.g. ~70 ms faster non-debuggable cold-start time-to-first-frame on a Moto G05 once unblocked).

Per Android's SurfaceHolder.Callback contract, only surfaceDestroyed is required to block until the render thread stops accessing the Surface; surfaceCreated and surfaceChanged can forward surface work asynchronously while fml::RefPtr<AndroidNativeWindow> (ANativeWindow_fromSurface) keeps the native window reference alive until teardown (see #196180 for more details)

Changes

shell/common:

  • Adds PlatformView::NotifyCreatedDeferred and PlatformView::Delegate::OnPlatformViewCreatedDeferred, used only by Android in this PR. The platform passes a SurfaceFactory callback; Shell posts surface creation + Rasterizer::Setup directly to the raster task runner (preserving FIFO ordering with subsequent resize/teardown tasks on the raster queue), posts CreateResourceContext to the IO task runner once a valid Surface is created, and schedules a UI frame without waiting.
  • Every other platform keeps calling PlatformView::NotifyCreated, which is unchanged.
  • Because Rasterizer::Setup can now run concurrently with platform-thread calls that disable or read the raster thread merger, protects merger access with raster_thread_merger_mutex_, starts a lazily created merger disabled if DisableThreadMergerIfNeeded() was called while setup was in flight, and resolves a spawned shell's parent merger lazily on the raster thread.

Android (shell/platform/android):

  • Updates PlatformViewAndroid::NotifyCreated and PlatformViewAndroid::NotifyChanged to post to the raster thread and return immediately. An atomic generation counter (surface_generation_) skips queued setup/resize tasks from a surface that has since been destroyed or replaced.
  • Keeps NotifyDestroyed (and NotifySurfaceWindowChanged for FlutterImageView resize) synchronous, and preserves existing attempt-and-validate failure handling when surface creation fails.

Perfetto cold-start traces on Moto G05 (Impeller Vulkan): before vs. after.

Fixes #196180, and is part of flutter/rfc#24

Pre-launch Checklist

If you need help, consider asking for advice on the #hackers-new channel on Discord.

…Android

On Android, surfaceCreated and surfaceChanged block the main thread until
the raster thread has created the swapchain and set up the rasterizer.
This happens inside the first view traversal, so the activity's first
draw and Dart's first frame both wait behind it (about 100 ms on a
Galaxy A16 and a Moto G05).

shell/common:
- Adds PlatformView::NotifyCreatedDeferred and
  PlatformView::Delegate::OnPlatformViewCreatedDeferred. The platform
  passes a surface factory; Shell runs it on the raster thread and
  requests a frame without waiting.
- The default delegate implementation is synchronous, and no other
  platform calls the new path.
- Rasterizer::Setup can now run while the platform thread disables or
  reads the thread merger, so that access is locked, a merger created
  while disabled starts disabled, and a spawned shell resolves its
  parent's merger lazily.

Android:
- PlatformViewAndroid::NotifyCreated and NotifyChanged post to the
  raster thread and return. A generation counter skips tasks from a
  surface that has since been destroyed or replaced.
- NotifyDestroyed stays synchronous, and a failed surface creation is
  handled as before.

Fixes flutter#196180
Add deterministic unit tests in shell_unittests and android_shell_holder_unittests covering non-blocking deferred surface creation, attempt-and-validate surface setup semantics (nullptr and invalid Surface rejection without calling Setup or CreateResourceContext, and setup continuation when SetNativeWindow fails yet CreateRenderingSurface returns a valid Surface), IO resource-context ordering after SetupImpellerContext, immediate UI frame scheduling whose draw orders after Rasterizer::Setup, in-flight NotifyDestroyed ordering and thread-merger disable safety, Shell destruction with pending deferred creation, Shell::Spawn thread-merger sharing when parent setup is deferred, and superseded surface_generation_ skipping.
@github-actions github-actions Bot added platform-android Android applications specifically engine flutter/engine related. See also e: labels. team-android Owned by Android platform team labels Nov 10, 2026
@gmackall gmackall added the CICD Run CI/CD label Nov 10, 2026
Removes the synchronous default implementation, which ran the surface
factory on the calling thread and was only there so test delegates did
not need an override. Shell is the only production delegate; the test
delegates now declare the method like the rest of the interface.
@github-actions github-actions Bot added a: text input Entering text in a text field or keyboard related problems platform-ios iOS applications specifically a: accessibility Accessibility, e.g. VoiceOver or TalkBack. (aka a11y) platform-fuchsia Fuchsia code specifically team-ios Owned by iOS platform team labels Nov 11, 2026
@gmackall
gmackall marked this pull request as ready for review November 11, 2026 02:08
@gmackall
gmackall requested review from a team as code owners November 11, 2026 02:08
@gmackall
gmackall requested review from okorohelijah and removed request for a team November 11, 2026 02:08

@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 introduces deferred platform view creation to prevent blocking the platform thread during GPU context or swapchain initialization. It adds asynchronous rendering surface construction via a SurfaceFactory callable on the raster task runner, updates PlatformViewAndroid to utilize this deferred path with generation tracking, and adds thread-safety guards around the Rasterizer thread merger. Feedback suggests ensuring that all writes to raster_thread_merger_ (including in Teardown) are properly guarded by the new mutex, and defensively checking the validity of surface_factory before invocation to prevent potential crashes.

@gmackall
gmackall requested a review from mboetger November 11, 2026 02:17
mboetger
mboetger previously approved these changes Nov 11, 2026

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

Love it.

…e merged

NotifyChanged used RunNowOrPostTask on the raster task runner. While the
raster queue is merged onto the platform thread (hybrid composition), that
runs the resize inline, ahead of a surface setup or an earlier resize still
waiting in the raster queue. Post the resize unconditionally so it stays in
FIFO order.

Since the task can now be queued while the queues are merged, and
Shell::~Shell() does not drain a merged raster queue, the task no longer
captures `this`. It shares the surface generation counter instead, and the
destructor bumps the counter so a task that outlives the platform view is a
no-op.

Adds AndroidShellHolder.NotifyChangedStaysBehindQueuedSetupWhenThreadsMerge.
@gmackall

Copy link
Copy Markdown
Member Author

I found one ordering of operations bugs in the HC merged threads case, pushed a fix, but the description is:

While a Hybrid Composition platform view is on screen, raster work runs on the platform thread, so the previous use of RunNowOrPostTask ("run now if on the raster thread, otherwise post") resize ran immediately on surfaceChanged. That let it jump ahead of work still sitting in the raster queue (the surface setup, or an earlier resize), which either resized a surface that didn't exist yet or left the surface at a stale size. The fix always posts the resize so it stays in order (i.e., just use PostTask), and has the task hold a shared generation counter instead of the platform view, so a resize still queued when the engine is torn down does nothing.

@gmackall gmackall added the autosubmit Merge PR when tree becomes green via auto submit App label Nov 13, 2026
@auto-submit
auto-submit Bot added this pull request to the merge queue Nov 13, 2026
Merged via the queue into flutter:master with commit 04cb5e2 Nov 13, 2026
22 checks passed
@flutter-dashboard flutter-dashboard Bot removed the autosubmit Merge PR when tree becomes green via auto submit App label Nov 13, 2026
dayanruben pushed a commit to dayanruben/flutter that referenced this pull request Nov 14, 2026
…ed" (flutter#196575)

Reverts: [Reland "[android]: prewarms shaders when the context is
created"](flutter#196549)

Initiated by: @gaaclarke

Reason for reverting: merge conflict with flutter#196342 causing post submit
failures (
[example](https://logs.chromium.org/logs/flutter/buildbucket/cr-buildbucket/8665197447632156673/+/u/build_ci_android_emulator_debug_x64_flutter_impeller_renderer_backend_vulkan:vulkan_android_unittests_flutter_impeller_renderer_backend_vulkan:vulkan_android_apk_unittests_flutter_impeller_toolkit_android:unittests_flutter_shell_platform_android:flutter_shell_native_unittests/stdout))

Original PR Author: @gaaclarke

Reviewed By: @andywolff

The original PR description is provided below:

relands flutter#196069

~~Additions since relanding:~~
1) ~~A test has been added to duplicate the failure in the android test
runner~~
1) ~~A flush was added to the io thread when the io thread's context is
set~~
1) ~~The warmup is now limited to opengles since we got mixed results
from vulkan.~~

Additions since relanding:
1) Removed vulkan branch (with pixel format assert)
1) Started pushing warming up to raster thread

## 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
gaaclarke added a commit to gaaclarke/flutter that referenced this pull request Nov 14, 2026
…ew test delegate

flutter#196342 added the pure virtual
PlatformView::Delegate::OnPlatformViewCreatedDeferred, which the
MockPlatformViewDelegate added to platform_view_android_unittests.cc by
flutter#196549 didn't implement, so
flutter_shell_native_unittests failed to compile.
auto-submit Bot pushed a commit to flutter/packages that referenced this pull request Nov 16, 2026
flutter/flutter@1b95854...d8bd864

2026-11-16 engine-flutter-autoroll@skia.org Roll Skia from f2790b0ea630 to 118eaff3deb4 (8 revisions) (flutter/flutter#196661)
2026-11-16 denisov.shureg@gmail.com [native_assets] Keep a dylib's install name in flutter test when its path does not fit (flutter/flutter#194802)
2026-11-16 30870216+gaaclarke@users.noreply.github.com Reland "[android]: prewarms shaders when the context is created" (flutter/flutter#196579)
2026-11-16 ammari.ali.0001@gmail.com [flutter_tools] Bound Browser.close in Chromium.close (flutter/flutter#196211)
2026-11-16 engine-flutter-autoroll@skia.org Roll Skia from e8ff7a4187ec to f2790b0ea630 (13 revisions) (flutter/flutter#196652)
2026-11-14 154381524+flutteractionsbot@users.noreply.github.com Revert: Balance web_canvaskit_tests and web_skwasm_tests subshards by duration (flutter/flutter#196580)
2026-11-14 154381524+flutteractionsbot@users.noreply.github.com Revert: Reland "[android]: prewarms shaders when the context is created" (flutter/flutter#196575)
2026-11-14 bkonyi@google.com [flutter_tools] Guard ExtensionManager initialization against concurrent disposal (flutter/flutter#196459)
2026-11-14 97480502+b-luk@users.noreply.github.com [ImpellerC] Escape spaces in depfile paths (flutter/flutter#196555)
2026-11-14 30870216+gaaclarke@users.noreply.github.com Reland "[android]: prewarms shaders when the context is created" (flutter/flutter#196549)
2026-11-14 magder@google.com Balance web_canvaskit_tests and web_skwasm_tests subshards by duration (flutter/flutter#196260)
2026-11-13 reginaldalfret@gmail.com Safely return null on malformed stack trace line in StackFrame.fromStackTraceLine (flutter/flutter#194673)
2026-11-13 awababushnagh0@gmail.com Clarify that super.dispose() must be called synchronously (flutter/flutter#193416)
2026-11-13 awolff@google.com Consolidate exit-code parameters on runCommand with ExpectedExit (flutter/flutter#196479)
2026-11-13 81323680+awaisdev5765@users.noreply.github.com Support multi-view apps in widget test binding (flutter/flutter#194480)
2026-11-13 pankoff2000@gmail.com Document using a ListView inside a Column (flutter/flutter#195145)
2026-11-13 matoshri1420@gmail.com Add didChangeAlwaysUse24HourFormat to WidgetsBinding and update MediaQuery (flutter/flutter#196117)
2026-11-13 magder@google.com Build local engine wasm configs on 32-core Linux bots (flutter/flutter#196284)
2026-11-13 boetger@google.com [Android] Fix Hybrid Composition resize deadlock (flutter/flutter#196255)
2026-11-13 engine-flutter-autoroll@skia.org Roll Skia from 11f46cfe8838 to e8ff7a4187ec (9 revisions) (flutter/flutter#196557)
2026-11-13 awolff@google.com [Impeller] Fix SurfaceContextVK submission tracking and double HostBuffer reset (flutter/flutter#196064)
2026-11-13 36861262+QuncCccccc@users.noreply.github.com Manual roll Packages from 14f9933 to 015df97 (5 revisions) (flutter/flutter#196558)
2026-11-13 lozhkovoi@gmail.com Remove routes_transition_test from widgets (flutter/flutter#186620)
2026-11-13 bkonyi@google.com [flutter_tools] Replace TargetPlatform.simpleName with cpuArch (flutter/flutter#196264)
2026-11-13 34871572+gmackall@users.noreply.github.com Add a deferred platform-view-created path to the shell and use it on Android (flutter/flutter#196342)
2026-11-13 50643541+Mairramer@users.noreply.github.com Optimize RenderSliverVariedExtentList and introduce protected itemExtentOf API in RenderSliverFixedExtentBoxAdaptor (flutter/flutter#192384)
2026-11-13 154381524+flutteractionsbot@users.noreply.github.com Revert: [android]: prewarms shaders when the context is created (flutter/flutter#196468)

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 louisehsu@google.com,stuartmorgan@google.com 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

a: accessibility Accessibility, e.g. VoiceOver or TalkBack. (aka a11y) a: text input Entering text in a text field or keyboard related problems CICD Run CI/CD engine flutter/engine related. See also e: labels. platform-android Android applications specifically platform-fuchsia Fuchsia code specifically platform-ios iOS applications specifically team-android Owned by Android platform team team-ios Owned by iOS platform team

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Android] Avoid blocking the platform thread in PlatformViewAndroid::NotifyCreated and NotifyChanged

2 participants