Repository navigation
[Android] Fix Hybrid Composition resize deadlock - #196255
Conversation
… size Hybrid composition (HC) only merges the raster thread into the platform thread while platform views are in the scene. Once the last platform view leaves and the merge lease expires, frames are rasterized on the raster thread again, but the surface pool still holds the overlay layers. On the next frame-size change (for example, a rotation), `AndroidExternalViewEmbedder::PrepareFlutterView` called `DestroySurfaces()`, which posts to the platform thread and waits. If the platform thread is itself waiting for the raster thread at that moment (`NotifyChanged` from `surfaceChanged`, `Shell::Screenshot` from `FlutterRenderer.getBitmap()`, `NotifyDestroyed`, `NotifySurfaceWindowChanged`), neither thread makes progress and the app ANRs. This is the same deadlock that flutter#190638 fixed for HCPP. `PrepareFlutterView` no longer destroys overlay layers. `SurfacePool::GetLayer` already replaces layers that were allocated for a different frame size, and for HC it only runs while the threads are merged, so on the platform thread. `Teardown`, which the shell calls on the platform thread, releases any that remain. Reproduced on Flutter 3.47.9 stable (ACID Pixel 9 emulator, API 35, no debugger attached): after an HC view with an overlay was removed, calling `FlutterRenderer.getBitmap()` right after a size-changing rotation deadlocked in 5 of 19 trials, all of which ended in an ANR. The main thread was blocked in `Shell::Screenshot` and the raster thread in `AndroidExternalViewEmbedder::DestroySurfaces` <- `PrepareFlutterView`. Tests: - `ResizeDoesNotBlockRasterOnPlatformThread` (new): the HC counterpart of the HCPP regression test from flutter#190638. Before this change it times out after 10 s. - `ReplacesStaleOverlayLayersAfterSizeChange` (replaces `DestroyOverlayLayersOnSizeChange`): the stale overlay is destroyed and replaced on the next overlay frame, not in `PrepareFlutterView`. - `DoesNotDestroyOverlayLayersOnSizeChange`: now expects no destroy, which matches its name.
…orm thread The previous commit stopped `PrepareFlutterView` from destroying HC overlay layers on a frame-size change and relied on `SurfacePool::GetLayer` to replace them lazily. That mirrors flutter#190638, but HCPP keeps one persistent overlay that it resizes in place, while HC overlays are `ImageReader`s sized to the frame and can't be resized. Keeping them meant that after a resize with no further overlay frames, the old overlays (three buffers each) stayed allocated until teardown. This restores HC's lifecycle, where overlays are destroyed when the frame size changes, without the blocking hop: - `SurfacePool::TakeLayers` removes the layers from the pool without calling into Java, so the next overlay is allocated at the new size. - `AndroidExternalViewEmbedder::ReleaseOverlayLayers` releases their rendering surfaces on the thread that renders into them, then destroys the overlay views on the platform thread without waiting. When the threads are merged that call still runs inline, as before. Tasks run in the order they are posted, including across merged task queues, so the views are destroyed before a later frame can allocate new overlays. - `DestroySurfaces` still waits, but only `Teardown` calls it, and the shell calls `Teardown` on the platform thread. Tests: - `DestroyOverlayLayersOnSizeChange` and `DoesNotDestroyOverlayLayersOnSizeChange` are restored from master. They now verify their expectations inside the test. Previously, the task that `PrepareFlutterView` posts kept the JNI mock alive past the end of the test, so their destroy expectations were only checked at exit. - `ResizeDoesNotBlockRasterOnPlatformThread` now also checks that the old overlays are destroyed on the platform thread once it is free, that the next overlay frame allocates a new overlay without destroying again, and that teardown destroys it. It times out against master and fails against the previous commit. - New `SurfacePool.TakeLayers` test.
`ReleaseOverlayLayers()` previously posted a parameterless `FlutterViewDestroyOverlaySurfaces()` task to the platform runner assuming tasks execute in order across merged queues. When `MergeWithLease` merges the raster queue into the platform queue, `MessageLoopTaskQueues` orders tasks across both queues by `(target_time, order_)` assigned at `PostTask` time. A raster draw task queued before `ReleaseOverlayLayers()` posts to the platform runner runs ahead of that posted task once merged, allocates a fresh overlay surface, and then has its `ImageReader` closed when the parameterless destroy task runs. Track the overlay IDs removed by `SurfacePool::TakeLayers()` in `pending_overlay_destroys_` and destroy only those stale IDs via a new `FlutterViewDestroyOverlaySurfacesById(const std::vector<int32_t>&)` / `FlutterJNI.destroyOverlaySurfaces(int[])` overload: - Any overlay allocated on a merged frame ahead of the posted task receives a higher ID from `PlatformViewsController.nextOverlayLayerId` and stays intact. - `DestroySurfaces()` drains any `pending_overlay_destroys_` synchronously during `Teardown()` so no JNI call executes after `Teardown()` returns. - Guard null `SurfaceFrame` returns in `CreateSurfaceIfNeeded()` and `SubmitFlutterView()` if `AcquireFrame()` fails on a disconnected consumer. Tests: - `AdversarialQueuedRasterTaskCreatesNewOverlayBeforeAsyncDestroyRuns` - `TeardownDrainsPendingAsyncOverlayDestroy` - `PlatformViewAndroidJNIImplTest.DestroyOverlaySurfacesByIdMarshalsIdsAndReleasesLocalRef` - `PlatformViewsControllerTest.destroyOverlaySurfacesById_leavesNewerLiveOverlayIntact`
… pending flag Replace the cross-JNI overlay ID list (`FlutterViewDestroyOverlaySurfacesById` / `destroyOverlaySurfaces(int[])`) and `PendingOverlayDestroys` mutex with a `pending_java_destroy_` flag inside `SurfacePool`: - `SurfacePool::TakeLayers()` sets `pending_java_destroy_ = true` under `SurfacePool::mutex_` when evicting cached layers without calling into Java. - `SurfacePool::GetLayer()` flushes `pending_java_destroy_` on the platform thread before allocating any new overlay surface, so a merged raster task that runs ahead of the posted `DestroyPendingLayers()` task destroys stale Java `ImageReader`s first and turns the delayed task into a no-op. - `SurfacePool::DestroyLayers()` flushes `pending_java_destroy_` during `Teardown()` so no JNI call executes after `Teardown()` returns. - Revert the 10 JNI, Java, and mock files back to `master` and deduplicate the HC resize concurrency test harness.
- Drain queued `MaybeResizeSurfaceView` tasks on `platform_thread` before calling `VerifyAndClearExpectations` in `MergedTaskAheadOfPostedResizeDestroyDestroysOldBeforeCreatingNew`, and join `1.raster` before clearing expectations on timeout in `ResizeDoesNotBlockRasterOnPlatformThread`. - Add `NullOverlaySurfaceFrameSkipsDisplayAndSubmit` covering null overlay `SurfaceFrame` returns in `CreateSurfaceIfNeeded()` and `SubmitFlutterView()`. - Extend `SurfacePool` unit tests to cover `TakeLayers() -> DestroyLayers()`, multi-overlay frames flushing `pending_java_destroy_` once, and `size1 -> size2 -> size1` unmerged resize oscillation before `GetLayer()`. - Document `GetLayer()` and `DestroyLayers()` platform-thread requirements and `CreateSurfaceIfNeeded()`'s null return in headers.
There was a problem hiding this comment.
Code Review
This pull request updates the Android external view embedder to release overlay layers asynchronously on the platform thread without blocking the raster thread during frame size changes, preventing potential deadlocks. It transitions SurfacePool to a shared pointer, introduces ReleaseOverlayLayers, and updates SurfacePool to track and flush pending Java overlay destructions when taking layers or allocating new ones. Additionally, it adds comprehensive unit tests to verify these thread-safety and resize behaviors. There are no review comments, and I have no feedback to provide.
gmackall
left a comment
There was a problem hiding this comment.
the race description, and also the approach of
Free the surfaces asap from the raster thread, and post the freeing of the java portion async to the platform thread
seems correct and safe to me. LGTM though still not a c++ expert
flutter/flutter@1b95854...d8bd864 2026-11-16 [email protected] Roll Skia from f2790b0ea630 to 118eaff3deb4 (8 revisions) (flutter/flutter#196661) 2026-11-16 [email protected] [native_assets] Keep a dylib's install name in flutter test when its path does not fit (flutter/flutter#194802) 2026-11-16 [email protected] Reland "[android]: prewarms shaders when the context is created" (flutter/flutter#196579) 2026-11-16 [email protected] [flutter_tools] Bound Browser.close in Chromium.close (flutter/flutter#196211) 2026-11-16 [email protected] Roll Skia from e8ff7a4187ec to f2790b0ea630 (13 revisions) (flutter/flutter#196652) 2026-11-14 [email protected] Revert: Balance web_canvaskit_tests and web_skwasm_tests subshards by duration (flutter/flutter#196580) 2026-11-14 [email protected] Revert: Reland "[android]: prewarms shaders when the context is created" (flutter/flutter#196575) 2026-11-14 [email protected] [flutter_tools] Guard ExtensionManager initialization against concurrent disposal (flutter/flutter#196459) 2026-11-14 [email protected] [ImpellerC] Escape spaces in depfile paths (flutter/flutter#196555) 2026-11-14 [email protected] Reland "[android]: prewarms shaders when the context is created" (flutter/flutter#196549) 2026-11-14 [email protected] Balance web_canvaskit_tests and web_skwasm_tests subshards by duration (flutter/flutter#196260) 2026-11-13 [email protected] Safely return null on malformed stack trace line in StackFrame.fromStackTraceLine (flutter/flutter#194673) 2026-11-13 [email protected] Clarify that super.dispose() must be called synchronously (flutter/flutter#193416) 2026-11-13 [email protected] Consolidate exit-code parameters on runCommand with ExpectedExit (flutter/flutter#196479) 2026-11-13 [email protected] Support multi-view apps in widget test binding (flutter/flutter#194480) 2026-11-13 [email protected] Document using a ListView inside a Column (flutter/flutter#195145) 2026-11-13 [email protected] Add didChangeAlwaysUse24HourFormat to WidgetsBinding and update MediaQuery (flutter/flutter#196117) 2026-11-13 [email protected] Build local engine wasm configs on 32-core Linux bots (flutter/flutter#196284) 2026-11-13 [email protected] [Android] Fix Hybrid Composition resize deadlock (flutter/flutter#196255) 2026-11-13 [email protected] Roll Skia from 11f46cfe8838 to e8ff7a4187ec (9 revisions) (flutter/flutter#196557) 2026-11-13 [email protected] [Impeller] Fix SurfaceContextVK submission tracking and double HostBuffer reset (flutter/flutter#196064) 2026-11-13 [email protected] Manual roll Packages from 14f9933 to 015df97 (5 revisions) (flutter/flutter#196558) 2026-11-13 [email protected] Remove routes_transition_test from widgets (flutter/flutter#186620) 2026-11-13 [email protected] [flutter_tools] Replace TargetPlatform.simpleName with cpuArch (flutter/flutter#196264) 2026-11-13 [email protected] Add a deferred platform-view-created path to the shell and use it on Android (flutter/flutter#196342) 2026-11-13 [email protected] Optimize RenderSliverVariedExtentList and introduce protected itemExtentOf API in RenderSliverFixedExtentBoxAdaptor (flutter/flutter#192384) 2026-11-13 [email protected] 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 [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
Fixes an Android Hybrid Composition (HC) platform <-> raster thread deadlock during frame-size changes (the HC counterpart of #190638).
Summary
1.raster, whileSurfacePoolstill holds the previously allocated HCOverlayLayerinstances (ImageReadersurfaces sized to the old viewport). On the next frame-size change (such as rotation),AndroidExternalViewEmbedder::PrepareFlutterViewcalledDestroySurfaces(), posting a task to the platform thread and blocking on aWaitableEventlatch:1.raster(Shell::ScreenshotfromFlutterRenderer.getBitmap(),PlatformViewAndroid::NotifyChangedfromsurfaceChanged,NotifyDestroyed, orNotifySurfaceWindowChanged), neither thread can advance and the app ANRs.1.raster,1.rasterstalls behind main-thread Looper work and executesDestroySwapchainKHR/DestroySurfaceKHRon the platform thread instead of1.raster.SurfacePool::TakeLayers()removes cachedOverlayLayerentries from the pool without calling into Java and setspending_java_destroy_ = trueunderSurfacePool::mutex_so subsequent HC frames allocate overlays at the new frame size.AndroidExternalViewEmbedder::ReleaseOverlayLayers()clears thoseOverlayLayerreferences directly on the rasterizing thread (releasing the Impeller/Skia GPU surface andVkSwapchainKHRon1.raster) and posts a non-blockingSurfacePool::DestroyPendingLayers()call to close the stale JavaImageReaders on the platform thread viaFlutterViewDestroyOverlaySurfaces().SurfacePool::GetLayer()andSurfacePool::DestroyLayers()also flushpending_java_destroy_on the platform thread before creating new overlays or returning fromTeardown().AndroidExternalViewEmbedder::CreateSurfaceIfNeeded()andSubmitFlutterView()guard nullSurfaceFramereturns ifAcquireFrame()fails on an overlay surface, skippingFlutterViewDisplayOverlaySurface()and overlay submission instead of dereferencing null.Important
Why
SurfacePoolflushespending_java_destroy_inGetLayer()andDestroyLayers(): When a subsequent HC frame triggersRasterThreadMerger::MergeWithLease,MessageLoopTaskQueuesorders tasks across the merged platform and raster queues by(target_time, order_)assigned atPostTasktime. A raster draw task queued beforeReleaseOverlayLayers()posts to the platform runner executes on the platform thread ahead of that posted cleanup task. Flushingpending_java_destroy_at the top ofSurfacePool::GetLayer()destroys the stale JavaImageReaders onmainbefore allocating a fresh overlay, turning the delayed cleanup task into a no-op and preventing post-Teardown()JNI calls.Execution & Threading Flows (Before vs. After)
1. Unmerged Resize During Concurrent Platform <-> Raster Calls
Before (
master): Synchronous Latch Causes AB-BA Deadlock & Main-Thread GPU TeardownsequenceDiagram participant P as Platform Thread (main) participant R as Raster Thread (1.raster) participant Pool as SurfacePool Note over P,Pool: HC platform view removed, merge lease expired (unmerged, stale OverlayLayer id=0 in Pool) P->>R: Resize viewport + BeginFrame submits resized LayerTree par Platform calls into Raster P->>R: Shell::Screenshot / NotifyChanged posts task + waits on raster latch and Raster calls into Platform R->>R: PrepareFlutterView detects frame_size_ != size R->>P: DestroySurfaces() posts task + waits on platform latch end Note over P,R: AB-BA DEADLOCK (both threads sleep forever -> ANR) Note over P,Pool: Even without Screenshot, 1.raster stalls until main is free, and main runs VkSwapchain teardownAfter (This PR): Non-Blocking Raster GPU Release + Async Java
ImageReaderCleanupsequenceDiagram participant P as Platform Thread (main) participant R as Raster Thread (1.raster) participant Pool as SurfacePool Note over P,Pool: Unmerged mode with stale OverlayLayer id=0 in Pool P->>R: Resize viewport + BeginFrame submits resized LayerTree P->>R: Shell::Screenshot / NotifyChanged waits on raster latch R->>Pool: ReleaseOverlayLayers() -> TakeLayers() swaps layers_ & sets pending_java_destroy_ = true R->>R: layers.clear() drops GPU surface (VkSwapchain freed on 1.raster) R-)P: Post async task (no wait) -> DestroyPendingLayers() R->>R: RecreateSwapchain + finish Draw + service Screenshot R-->>P: Signal Screenshot latch (platform thread unblocks) P->>Pool: DestroyPendingLayers() flushes pending_java_destroy_ -> destroyOverlaySurfaces()2. Dynamic Thread-Merge Queue Ordering & Teardown Barrier
On
master,PrepareFlutterViewblocked1.rasteron a synchronous latch beforePostPrerollActioncould reachMergeWithLease()(the deadlock shown in Section 1). Making resize cleanup non-blocking introduces a cross-queue ordering hazard unlessSurfacePooltracks pending Java overlay destruction:Naive Async
PostTask(Withoutpending_java_destroy_): Delayed Cleanup Closes Live Overlay & RacesTeardown()sequenceDiagram participant R as Raster Queue (1.raster) participant Pool as SurfacePool (mutex_) participant P as Platform Queue (main) participant PVC as PlatformViewsController (Java) Note over R,P: Draw 1 runs on 1.raster while Draw 2 (with HC view) is already queued on Raster Queue (order=10) R->>Pool: Draw 1 PrepareFlutterView -> TakeLayers() empties layers_ (no pending flag) R-)P: Post async FlutterViewDestroyOverlaySurfaces() to Platform Queue (order=11) R->>P: Draw 1 PostPrerollAction -> MergeWithLease() merges queues + kSkipAndRetryFrame Note over Pool,PVC: Merged queue executes order=10 BEFORE order=11 P->>Pool: Merged Draw 2 (order=10) GetLayer() sees empty layers_ Pool->>PVC: createOverlaySurface() allocates live overlay (id=1) while stale id=0 stays open P->>PVC: Queued task (order=11) calls destroyOverlaySurfaces() -> closes BOTH stale id=0 AND live id=1! Note over Pool,PVC: If Teardown() runs before order=11 executes, HasLayers() == false returns early and order=11 calls JNI after Teardown()After (This PR,
SurfacePool::pending_java_destroy_):GetLayer()&DestroyLayers()Flush Stale Overlays FirstsequenceDiagram participant R as Raster Queue (1.raster) participant Pool as SurfacePool (mutex_) participant P as Platform Queue (main) participant PVC as PlatformViewsController (Java) Note over R,P: Draw 1 runs on 1.raster while Draw 2 (with HC view) is already queued on Raster Queue (order=10) R->>Pool: Draw 1 PrepareFlutterView -> TakeLayers() sets pending_java_destroy_ = true R-)P: Post async DestroyPendingLayers() to Platform Queue (order=11) R->>P: Draw 1 PostPrerollAction -> MergeWithLease() merges queues + kSkipAndRetryFrame Note over Pool,PVC: Merged queue executes order=10 BEFORE order=11 P->>Pool: Merged Draw 2 (order=10) GetLayer() sees pending_java_destroy_ == true Pool->>PVC: Clears flag & calls destroyOverlaySurfaces() (closes id=0) BEFORE createOverlaySurface() (id=1) P->>Pool: Queued DestroyPendingLayers() (order=11) sees pending_java_destroy_ == false -> no-op (id=1 stays live) Note over Pool,PVC: If Teardown() runs before order=11 executes, DestroyLayers() flushes pending_java_destroy_ inlinePerfetto Benchmark (Before vs. After on Physical Pixel 8, API 34)
Measured on a physical Google Pixel 8 (
shiba, Android 14 / API 34,arm64-v8a, Impeller Vulkan, debug-unopt local engine builds) acrossn = 500Before vs.n = 500After unmerged HC resize cycles (5interleaved ABBA batch pairs x100cycles per arm), plusn = 20paireddeadlock_reprotrials andn = 5cold-startdumpsys meminfoGraphicschecks per arm. Each cycle renders an HCPlatformViewwith an intersecting Flutter overlay, letsRasterThreadMerger's 10-frame lease expire back to1.raster, resizes theFlutterView, and spinsmainfor55 msimmediately afterAnimator::EndFramesubmits the resizedLayerTreeto1.raster:master,b718471b2c2)#196255,62855a33e4c)p50/mean)FlutterRenderer.getBitmap()(n = 20trials/arm)20 / 20(100%) deadlocked / ANR (main&1.rasterstuck inS)0 / 20(0%) deadlocked (getBitmap()p50252.0 ms,p95279.5 ms,mean251.9 ± 21.2 ms)20/20 -> 0/20)1.rasterresizeGPURasterizer::Drawunder 55 msmainload (n = 500/arm)p5081.76 ms,p9594.60 ms(mean82.26 ± 6.77 ms)p5015.51 ms,p9522.23 ms(mean16.38 ± 4.61 ms)-66.25 ms(-81.0%p50/-80.1%mean)1.rastersleep (S) inside resizeGPURasterizer::Draw(n = 500/arm)p5060.80 ms,p9564.80 ms(mean61.24 ± 1.97 ms) onDestroySurfaces()latchp500.37 ms,p951.39 ms(mean0.62 ± 2.30 ms) (0 mswaiting onmain)-60.43 ms(-99.4%p50/-99.0%mean)n = 500/arm)p501.46 ms,p952.38 ms(mean1.53 ± 0.48 ms; fullDestroyLayersLockedspanp503.31 ms)p500.013 ms(13.2 us),p950.021 ms(mean0.014 ± 0.006 msImageReader.close())-99.1%slices (-99.6%span)n = 500/arm)main:p501.37 ms,p952.25 ms(mean1.43 ± 0.47 ms)main:0.000 ms(0/500);1.raster:p501.15 ms,p951.84 ms(mean1.23 ± 0.36 ms)-100%Vulkan teardown onmaindumpsys meminfoGraphicsafter unmerged resize (n = 5/arm)p50300,120 KB -> 151,284 KB(-148.8 MB)p50300,120 KB -> 151,288 KB(-148.8 MB)~149 MBreclaimedTests
AndroidExternalViewEmbedder.ResizeDoesNotBlockRasterOnPlatformThread: verifies unmerged frame-size changes do not block1.rasterwhile the platform thread is held, destroy stale overlays once the platform thread runs, and allocate fresh overlays on subsequent HC frames.AndroidExternalViewEmbedder.MergedTaskAheadOfPostedResizeDestroyDestroysOldBeforeCreatingNew: reproduces the merged-queue(target_time, order_)interleaving and verifiesSurfacePool::GetLayer()destroys the stale overlay before creating the new overlay and turns the delayed cleanup task into a no-op.AndroidExternalViewEmbedder.TeardownDrainsPendingAsyncOverlayDestroy: verifiesTeardown()synchronously flushespending_java_destroy_so zero JNI calls fire afterTeardown()returns.AndroidExternalViewEmbedder.NullOverlaySurfaceFrameSkipsDisplayAndSubmit: verifies null overlaySurfaceFramereturns skipFlutterViewDisplayOverlaySurface()and overlaySubmit()while still submitting the root frame.AndroidExternalViewEmbedder.DestroyOverlayLayersOnSizeChangeandDoesNotDestroyOverlayLayersOnSizeChange: verify overlay layer lifecycle across changed and unchanged frame sizes.SurfacePool.TakeLayers,GetLayerFlushesPendingDestroyOnceAcrossMultipleOverlaysInFrame, andTakeLayersPreservesPendingDestroyAcrossResizeBackToOriginalSize: verifyTakeLayers(),DestroyPendingLayers(),DestroyLayers(), multi-overlay pending-destroy flushing, andsize1 -> size2 -> size1resize oscillation.Pre-launch Checklist
///).