Skip to content

fix(imaging): Keep a shared BitmapImage download alive when one requester cancels, drop failed loads from the cache - #25101

Merged
MartinZikmund merged 5 commits into
unoplatform:masterfrom
mikernet:dev/mikernet/bitmap-cache-cancellation-25096
Oct 10, 2026
Merged

MartinZikmund merged 5 commits into
unoplatform:masterfrom
mikernet:dev/mikernet/bitmap-cache-cancellation-25096

Conversation

@mikernet

@mikernet mikernet commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

GitHub Issue: closes #25096

Builds on #25100 (merge that first; the first commit here is that PR's commit and the diff shrinks to the remaining four once it lands).

PR Type:

🐞 Bugfix

What changed? 🚀

On Skia, a BitmapImage whose remote download was cancelled by a different BitmapImage for the same URI stayed blank forever. In a virtualized ListView, ScrollIntoView right after ItemsSource is set leaves one or two tiles at the bottom of the viewport empty, most of the time but not always (see the issue for the full container-recycling sequence).

TryOpenSourceAsync shares one in-flight Task<ImageData> per (URI, decode size) through the static _bitmapImageCache, but that task ran on the first requester's cancellation token. When that requester re-opened (a recycled container binding a new UriSource cancels its previous open), the shared task caught the cancellation and completed with ImageData.FromError, so every other BitmapImage awaiting it raised ImageFailed, and nothing retried.

Two changes:

  • A shared load is never cancelled by a requester. A cached load runs on no requester's token; only an uncached load (IgnoreImageCache or cache disabled) still runs on its sole requester's token. Each requester awaits the shared task under its own token, so a superseded open neither fails nor applies a stale result, and the cancellation surfaces as a cancelled task that ImageSource.Open already drops. This matches WinUI, where ImageCache::OnRequestReleasing only drops the request from its lists and the download keeps running.
  • A failed shared load is dropped from the cache as soon as it completes, so the next requester downloads again instead of inheriting the error until LRU eviction. Previously an error result stayed cached (partly masked by the cancel-time removal this PR removes). The removal is guarded by a new LRUCache.Remove(key, value) that only removes the entry if it still holds that task, mirroring the identity check in WinUI's ImageProvider::RemoveImageCache.

How WinUI caches images, and how Uno differs

This PR fixes the shared-task bug inside Uno's existing design. It is worth knowing that the design itself differs from WinUI, in case the team would rather move towards parity than keep patching the LRU. From dxaml/xcp/core/imaging/ImagingProvider/ImageProvider.cpp, dxaml/xcp/components/imaging/ImageCache.cpp and dxaml/xcp/control/common/shared/ResourceManager.cpp on main:

WinUI Uno (Skia)
What is cached Encoded bytes per URI, plus a decoded software surface per decode size inside that entry The decoded ImageData (composition surface) per (URI, decode width, decode height)
Which sources Absolute URIs only, unless IgnoreImageCache; ms-appdata is excluded by ResourceManager::CanCacheResource; stream sources (SetSource) have no key and are never cached Any absolute URI unless IgnoreImageCache (after #25100); no scheme exclusion, so ms-appdata is cached too
Ownership The provider's store does not own entries. An ImageCache is ref-counted by the image sources and in-flight requests using it, and removes itself from the store in its destructor The static LRUCache owns the task, and through it the decoded surface
Eviction Pure lifetime: an image stays cached exactly as long as some BitmapImage or pending request still refers to it. No count cap, no LRU, no timer 100 entries by count (not bytes), least-recently-used eviction on add, idle trim after 5 minutes (shorter under memory pressure with automatic memory management)
Cancelling a requester Download continues; aborted only in the destructor, i.e. when the last user is gone After this PR: download continues; before, the first requester's cancel failed everyone
Failed download Kept as DownloadFailed state on the live entry; dropped with the entry once its last user releases it, so the next request re-downloads After this PR: dropped on completion; before, cached until LRU eviction

The practical consequence of the ownership difference is the memory behaviour behind #25098: WinUI never holds a decoded image that no element uses, while Uno's cache holds up to 100 decoded images regardless of whether anything still displays them (and a cache bounded by count rather than bytes can hold gigabytes of full-size photos). A parity implementation would share the in-flight load and decoded result between live BitmapImage instances, keyed by URI, and let the entry go when the last one releases it, with no retention beyond that. This PR does not attempt that; it keeps the LRU and fixes the sharing bug and the error retention within it.

Tests

Given_BitmapImage runtime tests, Skia desktop only (they use a loopback TcpListener that sends the response headers immediately but holds the PNG bytes until released, so the test acts while a download is deterministically in flight):

  • When_Shared_Download_And_First_Requester_Cancelled: two BitmapImages open the same URI, the first one's UriSource is changed mid-download, the second must open, exactly one request was issued, and the cancelled one raises neither ImageOpened nor ImageFailed. Fails on master (second raises ImageFailed), passes with this PR.
  • When_Only_Requester_Cancelled_Then_Same_Uri_Reopened: the sole requester cancels mid-download, then a new BitmapImage for the same URI opens.
  • When_Shared_Download_Failed_Then_Same_Uri_Reopened: the server answers the first request with HTTP 500; the first BitmapImage fails, a second one for the same URI must re-download and open. Fails without the error-eviction change, passes with it.

The When_IgnoreImageCache_Then_Not_Added_To_Cache test in the same file comes from #25100.

Validation on Skia desktop: Given_BitmapImage, Given_BitmapSource, Given_Image, Given_ImageSource, Given_ImageBrush and the rest of Windows_UI_Xaml_Media_Imaging pass, apart from Given_WriteableBitmap.When_WriteableBitmap_Assigned_With_Data_Present, which fails identically on an untouched master checkout on this machine and never enters the changed code.

PR Checklist ✅

Copilot AI balanced review requested due to automatic review settings October 8, 2026 05:30

Copilot AI 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.

🟡 Changes recommended

Failed-task eviction can still race with new requesters, causing retries to reuse the previous error.

1 open finding
What changed in this PR

Fixes shared Skia BitmapImage downloads for #25096, building on #25100’s IgnoreImageCache correction.

Changes:

  • Separates requester cancellation from shared downloads.
  • Evicts failed loads using identity-checked cache removal.
  • Adds regression tests for cache bypass, cancellation, and retries.

Code review retained 2 moderate findings and 2 nits; 3 are lower priority.

File Description
src/​Uno.WinRT/​Helpers/​LRUCache.cs Adds identity-checked removal.
src/​Uno.UI/​UI/​Xaml/​Media/​Imaging/​BitmapImage.cs Updates cancellation, cache bypass, and failure eviction.
src/​Uno.UI.RuntimeTests/​Microsoft/​UI/​Xaml/​Media/​Imaging/​Given_BitmapImage.cs Adds cache regression tests and a controlled HTTP server.

🧠 Review effort: Balanced


Give feedback about Copilot approvals in this survey to enter a drawing for a $150 gift card.

`IgnoreImageCache` skipped the lookup in the static `_bitmapImageCache`
but still added its load task to it, so the decoded image was retained
by the cache exactly as if the option were not set. Gate the add (and
the cancellation-removal registration) on the option too, so the image
lives only as long as the `BitmapImage` that produced it and never
replaces an entry other consumers already share.

Fixes unoplatform#25098
…ster cancels

The in-flight load cached by URI and decode size is awaited by every BitmapImage opening the same source, but it ran on the first requester's cancellation token. When that requester re-opened (a recycled ListView container binding a new UriSource), the shared task completed with a cancellation error, so every other BitmapImage for that URI raised ImageFailed and stayed blank, and nothing retried.

The shared load now runs on no requester's token, as WinUI's ImageCache does when a request is released, and each requester waits under its own token so a cancelled open neither fails nor applies a stale result. Uncached loads (IgnoreImageCache or cache disabled) still cancel with their sole requester.

Fixes unoplatform#25096
…led requester

Uses a loopback server that holds the image bytes until released, so the test cancels the first requester while the download is deterministically in flight.
A cached load that completes with an error stayed in the LRU until eviction, so one transient failure (offline moment, 503, DNS hiccup) kept failing every later BitmapImage for that URI with no retry. WinUI's provider store does not own its ImageCache: a failed one is dropped as soon as its requesters release it and the next request downloads again. The LRU owns its entries, so a continuation on the shared task now removes the entry when the load fails, guarded so it only removes the entry while it still holds that very task, as ImageProvider::RemoveImageCache does.

Fixes unoplatform#25096
Copilot AI balanced review requested due to automatic review settings October 8, 2026 05:47
@mikernet
mikernet force-pushed the dev/mikernet/bitmap-cache-cancellation-25096 branch from bc35261 to fce0e3b Compare October 8, 2026 05:47

Copilot AI 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.

🟡 Changes recommended

The cache-eviction assertion can race the eviction continuation and cause intermittent test failures.

1 open finding
1 resolved since last review

🧠 Review effort: Balanced


Give feedback about Copilot approvals in this survey to enter a drawing for a $150 gift card.

…r requesters

The gated server can answer the next request with an HTTP 500, so a BitmapImage opened after one failed must download again and open.
Copilot AI balanced review requested due to automatic review settings October 8, 2026 05:56
@mikernet
mikernet force-pushed the dev/mikernet/bitmap-cache-cancellation-25096 branch from fce0e3b to 5254005 Compare October 8, 2026 05:56

Copilot AI 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.

🟢 Approval recommended

The focused lifecycle changes address the reported failures, with regression coverage and no unresolved blocking findings.

0 open findings

1 resolved since last review

🧠 Review effort: Balanced


Give feedback about Copilot approvals in this survey to enter a drawing for a $150 gift card.

@mikernet

mikernet commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

For a servicing/6.8 backport: ported onto the 6.8.0-dev.212 commit at Singulink@462d020197 (branch Singulink:custom/6.8): all four commits folded into one against BitmapImage.skia.cs, with LRUCache.Remove(key, value) in src/Uno.UWP. Tests pass on Skia desktop with the same fail-before evidence.

@MartinZikmund

Copy link
Copy Markdown
Member

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines successfully started running 1 pipeline(s).

@nventive-devops

Copy link
Copy Markdown
Contributor

The build 238502 found UI Test snapshots differences: skia-linux-screenshots: 118, skia-windows-screenshots: 1145

Details
  • skia-linux-screenshots: 118 changed over 2458

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • ButtonClippingTestsControl.png-dark
    • ButtonClippingTestsControl.png
    • Buttons.png-dark
    • Buttons.png
    • ClipboardTests.png-dark
    • CompositionEffectBrush.png-dark
    • CompositionEffectBrush.png
    • CompositionNineGridBrush_Source_Changes.png-dark
    • CompositionNineGridBrush_Source_Changes.png
    • CalendarView_Theming.png-dark
    • CalendarView_Theming.png
    • DisplayInformation.png-dark
    • DynamicFont.png-dark
    • DynamicFont.png
    • Focus_FocusVisual_Properties.png-dark
    • Focus_FocusVisual_Properties.png
    • ImageBrushInList.png-dark
    • ImageBrushInList.png
    • ImageIconPage.png-dark
    • ImageIconPage.png
  • skia-windows-screenshots: 1145 changed over 2474

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • AppBarButtonWithIconTest.png-dark
    • AppBarButtonWithIconTest.png
    • Attributed_text_Simple.png
    • AutoSizedPathCentered.png-dark
    • AutoSizedPathCentered.png
    • AutoSuggestBox_Keyboard.png-dark
    • AutoSuggestBox_Keyboard.png
    • BorderLeftwithmargins.png-dark
    • BorderLeftwithmargins.png
    • CalendarDatePicker_Description.png-dark
    • CalendarDatePicker_Description.png
    • ComboBox_Simple.png-dark
    • ComboBox_Simple.png
    • ComboBox_Stretch.png-dark
    • ComboBox_Stretch.png
    • AnimatedIconPage.png-dark
    • AnimatedIconPage.png
    • ApplicationViewSpanningRectsPage.png
    • AutoBorderStretchwithrightmargin.png
    • AutoSuggestBox_Icons.png-dark

@MartinZikmund
MartinZikmund merged commit a1682d1 into unoplatform:master Oct 10, 2026
53 checks passed
mikernet added a commit to mikernet/uno that referenced this pull request Oct 21, 2026
With the bitmap cache on, the decode shared by the BitmapImages that
load the same uri and decode size was owned by an LRU of
MaxBitmapImageCacheCount (100) entries. No source released it, and the
LRU kept it whether or not anything displayed it. An entry the LRU
evicted, or a shared load whose requesters were all cancelled, was left
to finalization (unoplatform#25128).

A shared decode now counts its uses: the opens waiting for it, and the
sources whose subscribers draw it or were given it to draw. Once it has
none, it waits on the same pending-release list as the decodes sources
own (1 s and MaxUndisplayedImageBytes, oldest first). When released, its
frames are freed and it leaves the cache, and a source that still holds
it opens again on its next subscriber. It keeps its pixel size, which an
Image showing that source measures with until then, as for the decodes
sources own.

An open hands its use over to its source once the source counts its own
use. Any other way out of the open (cancelled, failed, superseded, a
handler that throws) ends it, so nothing can release the result in
between, and nothing keeps it for good. A load whose requesters were all
cancelled keeps running for later ones, as since unoplatform#25101, and its result
then waits like any other.

The sharing follows WinUI's ImageCache, which leaves the provider's
store once the last BitmapImage using it lets it go (MUX Reference:
ImageProvider::EnsureCacheEntry, ImageProvider::RemoveImageCache). Like
that store, the cache does not own its decodes. An ImageBrush keeps its
subscription for its lifetime, so a source can be collected while it
still counts as a user. Sources are therefore held weakly, and a
collected one is dropped the next time the decode's uses change.

A subscriber that comes back still drawing a shared decode its source
replaced while it was away uses it again until it draws what replaced
it, as unoplatform#25124 lets it take back replaced pixels it owns.

The LRUCache helper had no other user and is removed.
MaxBitmapImageCacheCount no longer bounds anything; the next commit
marks it obsolete.
agneszitte added a commit that referenced this pull request Nov 2, 2026
…ared-bitmapimage-download-6.8

fix(imaging): Keep a shared BitmapImage download alive when one requester cancels, drop failed loads from the cache (backport #25101)
agneszitte added a commit that referenced this pull request Nov 2, 2026
…6.7/pr-25915

fix(imaging): Keep a shared BitmapImage download alive when one requester cancels, drop failed loads from the cache (backport #25101) (backport #25915)
mikernet added a commit to mikernet/uno that referenced this pull request Nov 12, 2026
With the bitmap cache on, the decode shared by the BitmapImages that
load the same uri and decode size was owned by an LRU of
MaxBitmapImageCacheCount (100) entries. No source released it, and the
LRU kept it whether or not anything displayed it. An entry the LRU
evicted, or a shared load whose requesters were all cancelled, was left
to finalization (unoplatform#25128).

A shared decode now counts its uses: the opens waiting for it, and the
sources whose subscribers draw it or were given it to draw. Once it has
none, it waits on the same pending-release list as the decodes sources
own (1 s and MaxUndisplayedImageBytes, oldest first). When released, its
frames are freed and it leaves the cache, and a source that still holds
it opens again on its next subscriber. It keeps its pixel size, which an
Image showing that source measures with until then, as for the decodes
sources own.

An open hands its use over to its source once the source counts its own
use. Any other way out of the open (cancelled, failed, superseded, a
handler that throws) ends it, so nothing can release the result in
between, and nothing keeps it for good. A load whose requesters were all
cancelled keeps running for later ones, as since unoplatform#25101, and its result
then waits like any other.

The sharing follows WinUI's ImageCache, which leaves the provider's
store once the last BitmapImage using it lets it go (MUX Reference:
ImageProvider::EnsureCacheEntry, ImageProvider::RemoveImageCache). Like
that store, the cache does not own its decodes. An ImageBrush keeps its
subscription for its lifetime, so a source can be collected while it
still counts as a user. Sources are therefore held weakly, and a
collected one is dropped the next time the decode's uses change.

A subscriber that comes back still drawing a shared decode its source
replaced while it was away uses it again until it draws what replaced
it, as unoplatform#25124 lets it take back replaced pixels it owns.

The LRUCache helper had no other user and is removed.
MaxBitmapImageCacheCount no longer bounds anything; the next commit
marks it obsolete.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Skia] BitmapImage: a cached in-flight download is cancelled by its first requester, failing every other BitmapImage sharing it

5 participants