Skip to content

[Impeller] Cap the Vulkan command pool recycler cache - #194793

Merged
auto-submit[bot] merged 2 commits into
flutter:masterfrom
sero583:impeller-vulkan-command-pool-cap
Nov 20, 2026
Merged

auto-submit[bot] merged 2 commits into
flutter:masterfrom
sero583:impeller-vulkan-command-pool-cap

Conversation

@sero583

@sero583 sero583 commented Oct 19, 2026

Copy link
Copy Markdown
Contributor

CommandPoolRecyclerVK kept every pool that came back to it. The raster thread moves to a fresh pool every frame and after every picture snapshot, and the previous one comes back once its work has finished on the GPU. In steady state about as many pools come back as are taken out again, but the recycler never destroyed one, so the number of pools never goes down: a frame with many snapshots, or a few frames with more work in flight, leaves that many pools in the list for good, each with the command buffers it recycled and the driver memory behind them.

The recycler now holds at most kMaxRecycledPools (8) pools. Typical rendering gets back about one pool per frame plus one per snapshot and takes them out again, so it stays below the cap and keeps reusing pools. A pool that comes back while the list is full is destroyed instead, freeing its buffers before the pool they were allocated from.

Evicting the oldest entry with vector::erase instead would be a use after free: erase move-assigns the remaining entries over the evicted slot, and move assignment runs in declaration order, so the overwritten entry's pool is destroyed before its recycled buffers are freed. That is how #189580 first capped the cache. It reproduced deterministically against SwiftShader and is the likely cause of the canvas_test crash under host_release on that PR. Dropping the incoming pool never moves an entry, and the RecycledData comment now says why the member order matters.

DroppedPoolsFreeBuffersBeforeTheirPool reclaims kMaxRecycledPools + 2 pools from as many threads, each with one recycled command buffer, and walks the recorded Vulkan calls: at every point there have to be at least as many vkFreeCommandBuffers calls as vkDestroyCommandPool calls, and exactly two of each in total. Without the cap nothing is destroyed and the totals fail with 0 against 2. With an erase based eviction, or with the pool destroyed before its buffers, the walk fails at the first destroyed pool with frees 0 against destroys 1.

Split out of #189580.

Fixes #194787

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.

CommandPoolRecyclerVK kept every pool that came back to it. The raster
thread moves to a fresh pool every frame and after every picture
snapshot, and the previous one comes back once its work has finished
on the GPU. In steady state about as many pools come back as are taken
out again, but the recycler never destroyed one, so the number of pools
never goes down: a frame with many snapshots, or a few frames with more
work in flight, leaves that many pools in the list for good, each with
the command buffers it recycled and the driver memory behind them.

The recycler now holds at most kMaxRecycledPools (8) pools. Typical
rendering gets back about one pool per frame plus one per snapshot and
takes them out again, so it stays below the cap and keeps reusing
pools. A pool that comes back while the list is full is destroyed
instead, freeing its buffers before the pool they were allocated from.

Evicting the oldest entry with vector::erase instead would be a use
after free: erase move-assigns the remaining entries over the evicted
slot, and move assignment runs in declaration order, so the
overwritten entry's pool is destroyed before its recycled buffers are
freed. That is how flutter#189580 first capped the cache. It reproduced
deterministically against SwiftShader and is the likely cause of the
canvas_test crash under host_release on that PR. Dropping the incoming
pool never moves an entry, and the RecycledData comment now says why
the member order matters.

DroppedPoolsFreeBuffersBeforeTheirPool reclaims kMaxRecycledPools + 2
pools from as many threads, each with one recycled command buffer, and
walks the recorded Vulkan calls: at every point there have to be at
least as many vkFreeCommandBuffers calls as vkDestroyCommandPool calls,
and exactly two of each in total. Without the cap nothing is destroyed
and the totals fail with 0 against 2. With an erase based eviction, or
with the pool destroyed before its buffers, the walk fails at the first
destroyed pool with frees 0 against destroys 1.
@github-actions github-actions Bot added engine flutter/engine related. See also e: labels. e: impeller Impeller rendering backend issues and features requests labels Oct 19, 2026
@sero583
sero583 marked this pull request as ready for review October 19, 2026 19:49

@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 a limit of 8 on the number of recycled Vulkan command pools kept for reuse to prevent unbounded caching. When this limit is exceeded, excess command pools and their associated buffers are explicitly destroyed, ensuring buffers are freed before the pool. A unit test is added to verify this destruction order. The review feedback suggests implementing a custom move assignment operator and constructor for RecycledData to guarantee correct destruction order during vector operations, and using emplace_back for in-place construction.

Comment on lines 118 to 121
struct RecycledData {
vk::UniqueCommandPool pool;
std::vector<vk::UniqueCommandBuffer> buffers;
};

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.

high

While documenting that RecycledData must not be move-assigned is helpful, relying on comments to prevent undefined behavior/use-after-free is fragile. Standard library container operations (such as std::vector::erase, std::vector::shrink_to_fit, or certain reallocations/swaps) can implicitly trigger move assignment.

By defining a custom move assignment operator that explicitly clears the destination's buffers before resetting the pool, we can guarantee the correct destruction order under all circumstances. Additionally, defining a constructor allows us to use emplace_back for safer and more efficient in-place construction.

  struct RecycledData {
    vk::UniqueCommandPool pool;
    std::vector<vk::UniqueCommandBuffer> buffers;

    RecycledData(vk::UniqueCommandPool p_pool,
                 std::vector<vk::UniqueCommandBuffer> p_buffers)
        : pool(std::move(p_pool)), buffers(std::move(p_buffers)) {}

    RecycledData(RecycledData&&) noexcept = default;

    RecycledData& operator=(RecycledData&& other) noexcept {
      if (this != &other) {
        buffers.clear();
        pool.reset();
        pool = std::move(other.pool);
        buffers = std::move(other.buffers);
      }
      return *this;
    }
  };

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.

I don't agree with this, I feel the documentation is sufficient

Comment on lines +303 to +304
recycled_.push_back(
RecycledData{.pool = std::move(pool), .buffers = std::move(buffers)});

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.

high

Use emplace_back to construct the RecycledData in-place, which is more efficient and works seamlessly with the custom constructor.

      recycled_.emplace_back(std::move(pool), std::move(buffers));

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.

you don't need this if you don't write a custom constructor

@gaaclarke
gaaclarke requested a review from andywolff October 20, 2026 20:35
@gaaclarke

Copy link
Copy Markdown
Member

@andywolff can you give this a look please

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

Comment on lines 118 to 121
struct RecycledData {
vk::UniqueCommandPool pool;
std::vector<vk::UniqueCommandBuffer> buffers;
};

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.

I don't agree with this, I feel the documentation is sufficient

Comment on lines +303 to +304
recycled_.push_back(
RecycledData{.pool = std::move(pool), .buffers = std::move(buffers)});

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.

you don't need this if you don't write a custom constructor

@gaaclarke
gaaclarke self-requested a review October 26, 2026 16:18
@andywolff andywolff added the CICD Run CI/CD label Oct 26, 2026

@gaaclarke gaaclarke left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The issue states: is the likely cause of the canvas_test crash under host_release on that PR.

Were we able to confirm that? Is the problem one that can be created with the Dart API or is this a hypothetical problem?

@HonQii

HonQii commented Nov 11, 2026

Copy link
Copy Markdown

@sero583, thanks for working on this. We reproduced similar Adreno memory growth and native crashes using standard Dart Canvas APIs. Could you help check whether this PR addresses the reproduction below?

We have not tested the patch or confirmed that our failure has the same root cause.

Environment

  • Flutter 3.47.5
  • Framework: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1
  • Engine: af7e796e161ae0bb1ff0758c71a7105418bd9ded
  • Physical vivo V2436A, Android 16
  • Adreno Vulkan driver: 0762.36
  • Default Impeller/Vulkan, without an attached VM profiler or Perfetto

Standalone reproduction

  1. Create a stock Flutter Android project.
  2. Replace lib/main.dart with the pure-Dart reproduction in this #192002 comment.
  3. Build with flutter build apk --profile, install the APK, and launch it normally. Repeat separately with flutter build apk --release.
  4. Keep the app in the foreground.

The snippet continuously paints 200 small saveLayers, plus 100 more during half of each 500 ms cycle. Each layer contains two overlapping rectangles. It requires no images, text, blur, application assets, or direct Flutter GPU API calls.

We reproduced native crashes with the unmodified Dart snippet in both profile and release. Captured signatures include:

Scudo: Can't populate more pages for size class 65552
Adreno-GSL: mmap failed errno 12 Out of memory
1.raster: SIGSEGV, fault addr 0x1c, vulkan.adreno.so

The driver entry point includes vkCmdBeginRenderPass or vkBeginCommandBuffer across captures. Another attempt ended in a Scudo internal-map-failure SIGABRT through Adreno calloc; we recorded that separately.

Additional frequency and idle-retention controls

Using one instrumented profile APK, we added a 5-second static 200-layer warm-up and varied the interval between high/low changes. The full cycle is twice this interval. Each row is one fresh-process trial, observed for up to 120 seconds:

High/low interval Result
250 ms SIGSEGV after approximately 25 seconds
500 ms SIGSEGV after approximately 32 seconds
1000 ms Completed 120 seconds; sampled PSS reached approximately 1066 MiB
2500 ms SIGSEGV after approximately 45 seconds
5000 ms SIGSEGV after approximately 90 seconds
Constant 300 layers, continuously repainting Completed 120 seconds; sampled PSS maximum approximately 376 MiB

For idle retention, we repeated this sequence five times:

  1. Fluctuate between 200/300 layers at 250 ms intervals for 1 second.
  2. Stop the ticker and paint one static 200-layer frame.
  3. Keep the screen on and idle for 60 seconds without requesting more frames.

The paint counter did not advance during any idle window. ImageCache remained at 0 bytes / 0 entries.

  • Baseline PSS: approximately 233 MiB.
  • Late-idle PSS by round: 366 → 477 → 514 → 549 → 536 MiB.
  • Control using a constant 300-layer load for 1 second before each identical idle: baseline approximately 234 MiB; late-idle PSS 361 → 406 → 406 → 408 → 409 MiB.

Heap Alloc was not monotonic, so we are not interpreting all retained PSS as a leak.

We sampled dumpsys meminfo approximately every 4 seconds, with additional phase snapshots and /proc/<pid>/maps. Late-idle values use samples wholly inside the idle window, around 57–59 seconds, to exclude the next burst. Fifth-round 60-second snapshots agreed. These are sampled values, not guaranteed peak memory or total GPU allocations.

Related reports

  • #192002: the closest report, including the linked Canvas reproduction and command-pool-recycling hypothesis.
  • #160941: similar Adreno allocation-failure / raster SIGSEGV symptoms; we have not established the same cause.
  • #172068: historical Flutter GPU command-buffer OOM, fixed by #173663. That fix is already in our SDK, and its explicit Flutter GPU API path differs from this Canvas reproduction.

Would you be able to try the linked Dart reproduction with this patch? In particular, would you expect the cap to help only with pools already returned to recycled_, or also with active-load OOM when recycling falls behind?

If additional counters or a different minimal workload would help distinguish these cases, please let us know. Thank you.

@sero583

sero583 commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Not hypothetical. I hit it while stress testing the desktop Vulkan backend (#183382) with flutter-benchmark; the cap comes from there.

It's also reachable from plain dart:ui: 128 Picture.toImage calls in flutter_tester (Linux release, SwiftShader) grow the cache to 44 to 69 command pools on master, and none are freed while the context lives. With this PR the cache stops at 8.

The crash: #183382 released the evicted entry's buffers before the erase, #189580 dropped that. With #189580's eviction on master, the same program segfaults in the first eviction, every run; #183382's version, master and this PR run clean.

I couldn't tie the CI canvas_test crash to it, though: locally canvas_test never caches more than 4 pools, so the eviction never runs. I'll fix the wording in the issue.

@sero583
sero583 requested a review from gaaclarke November 19, 2026 00:50
@sero583

sero583 commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

@HonQii thanks for the detailed report. Here is what this PR changes and what it doesn't.

It caps recycled_, the list of pools that are back from Reclaim, at 8. A pool that comes back while 8 are already cached is destroyed with its buffers instead of being cached. So once the resource manager has caught up after a burst, the extra pools and their command buffers are freed instead of staying alive for the lifetime of the context. That is what your idle-retention runs show (366 to 549 MiB after repeated bursts), and I'd expect the cap to bound it.

It doesn't help with the growth under sustained load, though. yazd's measurements in #192002 point to the cause: when more than 16 buffers of a pool went unused in a frame, the pool is reset with VK_COMMAND_POOL_RESET_RELEASE_RESOURCES_BIT, which took about 115 ms per pool on Adreno 750. The resource manager has a single thread, so it falls behind, recycled_ is empty when a frame starts, and Create() makes a new pool. Pools still waiting in that queue are not in recycled_ yet, so the cap doesn't count them, and it doesn't make the reset any faster. With a swing that keeps going, as in your 250 ms to 5000 ms runs, the queue never clears and memory keeps growing until an allocation fails. That needs a change to the trim path itself, which is outside this PR.

Two numbers would tell the cases apart on your device: how often Create() finds recycled_ empty and creates a new pool, and how long resetCommandPool in Reclaim takes when should_trim is set. If new pools keep appearing during the swing while those resets take tens of milliseconds, it is that backlog. With this patch, the pool count should drop back once a burst is over, but still climb while the swing goes on.

I have an Adreno phone here, so I'll try to track down the trim path when I have time for it; it won't be right away, though.

@gaaclarke gaaclarke added the autosubmit Merge PR when tree becomes green via auto submit App label Nov 19, 2026
@auto-submit auto-submit Bot removed the autosubmit Merge PR when tree becomes green via auto submit App label Nov 19, 2026
@auto-submit

auto-submit Bot commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

autosubmit label was removed for flutter/flutter/194793, because The base commit of the PR is older than 7 days and can not be merged. Please merge the latest changes from the main into this branch and resubmit the PR.

@auto-submit

auto-submit Bot commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

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

  • The status or check suite Google testing has failed. Please fix the issues identified (or deflake) before re-applying this label.
  • The status or check suite Mac_arm64_verify_binaries has failed. Please fix the issues identified (or deflake) before re-applying this label.
  • The status or check suite Tree_analyze has failed. Please fix the issues identified (or deflake) before re-applying this label.

@flutter-dashboard flutter-dashboard Bot removed the CICD Run CI/CD label Nov 19, 2026
@sero583

sero583 commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

@gaaclarke thanks for the approval. Autosubmit was removed because the base was older than 7 days, so I merged the latest master. The PR's own diff is unchanged.

@andywolff andywolff added CICD Run CI/CD autosubmit Merge PR when tree becomes green via auto submit App labels Nov 19, 2026
@auto-submit
auto-submit Bot added this pull request to the merge queue Nov 20, 2026
Merged via the queue into flutter:master with commit d2a2279 Nov 20, 2026
24 checks passed
@flutter-dashboard flutter-dashboard Bot removed the autosubmit Merge PR when tree becomes green via auto submit App label Nov 20, 2026
auto-submit Bot pushed a commit to flutter/packages that referenced this pull request Nov 20, 2026
Roll Flutter from e8cc6f3451b7 to b34b017b48ad (36 revisions)

flutter/flutter@e8cc6f3...b34b017

2026-11-20 [email protected] Fix OverflowBox dry layout when deferToChild overrides the constraints (flutter/flutter#196839)
2026-11-20 [email protected] Roll Dart SDK from f118f476ebce to 3b5f45d812f8 (1 revision) (flutter/flutter#197048)
2026-11-20 [email protected] [macOS] Register plugins in multiple_windows example (flutter/flutter#196068)
2026-11-20 [email protected] Roll Skia from 87027a9d4659 to a1edf5c2ea5c (1 revision) (flutter/flutter#197045)
2026-11-20 [email protected] Add highp directives to UberSDF to prevent overflow (flutter/flutter#196997)
2026-11-20 [email protected] [Impeller] Cap the Vulkan command pool recycler cache (flutter/flutter#194793)
2026-11-20 [email protected] Roll Skia from 12610b69511d to 87027a9d4659 (4 revisions) (flutter/flutter#197037)
2026-11-20 [email protected] [macOS] Unregister nil binary message handlers (flutter/flutter#193672)
2026-11-20 [email protected] Roll Dart SDK from b803c3ec01de to f118f476ebce (2 revisions) (flutter/flutter#197034)
2026-11-20 [email protected] Roll Skia from 2f1436ba8e64 to 12610b69511d (3 revisions) (flutter/flutter#197030)
2026-11-20 [email protected] [Android] Do not use the HCPP external view embedder from its platform tasks (flutter/flutter#196490)
2026-11-20 [email protected] Roll Dart SDK from 849e17ad3ae6 to b803c3ec01de (1 revision) (flutter/flutter#197012)
2026-11-20 [email protected] [iOS a11y] Synchronize hit-test children when replacing semantics objects (flutter/flutter#196439)
2026-11-20 [email protected] Sync CHANGELOG.md from stable (flutter/flutter#197019)
2026-11-19 [email protected] [flutter_tools] Reland "Extract Windows archives using native tar" (flutter/flutter#193515)
2026-11-19 [email protected] [Reland][flutter_tools] Migrate lib/runner.dart off runInContext and overrides (flutter/flutter#196931)
2026-11-19 [email protected] Include assigned issues in Android incoming triage link (flutter/flutter#197008)
2026-11-19 [email protected] [Flutter GPU] Record on the UI thread, encode and submit on the raster thread (flutter/flutter#194882)
2026-11-19 [email protected] Add Pixel 7 Pro Impeller benchmarks without fixed-performance mode (flutter/flutter#197010)
2026-11-19 [email protected] Reduce time of uiscene_plugin_lifecycle_test_ios (flutter/flutter#196363)
2026-11-19 [email protected] [native assets] Respect Apple deployment targets (flutter/flutter#194146)
2026-11-19 [email protected] iOS: Represent platform view frames as FlutterPlatformViewFrames (flutter/flutter#196955)
2026-11-19 [email protected] Roll Skia from 0bf961e4ff05 to 2f1436ba8e64 (3 revisions) (flutter/flutter#196999)
2026-11-19 [email protected] [ios] Record OCMReject expectations before the stimulus in FlutterPluginAppLifeCycleDelegateTest (flutter/flutter#193011)
2026-11-19 [email protected] Fix post-monorepo doc rot in docs/infra and dev/bots/README.md (flutter/flutter#193010)
2026-11-19 [email protected] Roll Skia from c3567e170362 to 0bf961e4ff05 (4 revisions) (flutter/flutter#196994)
2026-11-19 [email protected] Close Linux popups when their parent loses focuses (flutter/flutter#196825)
2026-11-19 [email protected] Roll Packages from dca2e58 to 81b7c44 (6 revisions) (flutter/flutter#196992)
2026-11-19 [email protected] Roll Dart SDK from d8d40cf9c21b to 849e17ad3ae6 (1 revision) (flutter/flutter#196986)
2026-11-19 [email protected] Fix RouteObserver didPushNext not firing when routes are pushed synchronously (flutter/flutter#189057)
2026-11-19 [email protected] [Impeller] Reuse render targets on text shadow cache misses (flutter/flutter#194769)
2026-11-19 [email protected] Roll Skia from 81de64af9806 to c3567e170362 (3 revisions) (flutter/flutter#196982)
2026-11-19 [email protected] Reland: "Move macOS desktop builds to ThinLTO" (flutter/flutter#196928)
2026-11-19 [email protected] [Linux] Desynchronize the Wayland subsurface so frames don't redraw the GTK window (flutter/flutter#195287)
2026-11-19 [email protected] Roll Skia from 3dfb69d709c7 to 81de64af9806 (1 revision) (flutter/flutter#196975)
2026-11-19 [email protected] Update `ProxyAnimation.didStartListening` and `ProxyAnimation. didStopListening` to use dart's `Conditional member access` (flutter/flutter#195762)

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:
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CICD Run CI/CD e: impeller Impeller rendering backend issues and features requests engine flutter/engine related. See also e: labels.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Impeller] The Vulkan command pool recycler never releases the pools it caches

4 participants