Repository navigation
[Android] Map: Stop pin icons and cluster icons evicting each other - #37944
Conversation
dotnet#37774 merged the per-pin icon cache into the cluster one, and a single shared instance makes the two kinds of image fight over the same 64 entries. A map with more distinct pin images than the capacity evicts the cluster entry on every pass, because pin traffic keeps it the least recently used - so the cluster image is re-decoded each recluster, which is what the cache was originally added to stop. Above the capacity the whole thing degenerates to a 0% hit rate, leaving that map worse off than before the cache existed. The other direction hurts too: a ClusterImageVersion bump means the app's cluster images changed, and clearing the shared cache threw away the pins' decoded icons with them even though no pin ImageSource had changed. Two instances, and the version bump now clears only the cluster one. A pin and a cluster naming the same image decode twice, which is a smaller cost than either eviction path. UpdatePinImageSourceAsync goes through the pin cache as well, so the two pin-icon paths agree. Switching many live pins to one image - a selection highlight - coalesced into a single load instead of one per pin, and the following recluster pass finds the entry instead of decoding it again. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
|
🚀 Dogfood this PR with:
curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 37944Or
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 37944" |
|
Azure Pipelines: There may be pipelines that require an authorized user to comment /azp run to run. |
|
Hey there @@kevin68! Thank you so much for your PR! Someone from the team will get assigned to your PR shortly and we'll get it reviewed. |
|
Hey there @kevin68! Thank you so much for your PR! Someone from the team will get assigned to your PR shortly and we'll get it reviewed. |
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
fcf0ec7 to
83d96a8
Compare
MauiBot
left a comment
There was a problem hiding this comment.
Expert Review — 3 findings
See inline comments for details.
| // into a single load, and the next recluster pass finds the entry. Note GetIconAsync | ||
| // drops ct for a keyable load, so this can outlive a pins reset - the guards below | ||
| // still discard the result. | ||
| icon = await GetIconAsync(_pinIconCache, requestedSource, mauiContext, ct); |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[moderate] Logic and Correctness / Regression Prevention — This line converts UpdatePinImageSourceAsync from an unconditional fresh load (LoadPinIconAsync) into a cache lookup. Combined with the change at line 424 (the version bump now clears only _clusterIconCache), _pinIconCache is left with exactly one clear site: handler cleanup at line 143. So for the whole lifetime of a connected handler there is no longer any path that re-decodes a keyed pin source.
Concrete scenario: Pin.ImageSource is an IFileImageSource pointing at a rooted path (e.g. a PNG under FileSystem.CacheDirectory — the exact fixture used to verify #37769/#37774). The app rewrites that file and re-assigns a new FileImageSource with the same File to raise the property change. GetIconCacheKey yields the same file:<path> key, GetIconCacheExpiry returns DateTime.MaxValue for non-URI sources, so the entry never expires and the pin keeps rendering the previous bitmap until the handler disconnects or LRU eviction happens to drop it. Before this diff the property-change path bypassed the handler cache and reloaded.
IUriImageSource is unaffected (bounded by CacheValidity), and IFontImageSource keys encode every render input, so the exposure is specifically the file-path-with-mutated-content case. If accepting that is intentional, the comment above should say so — it currently frames the change only as coalescing, which reads as a pure optimization.
| // traffic past the capacity must not evict the cluster entries on every pass. The cost is | ||
| // that a pin and a cluster naming the same image decode twice. | ||
| readonly IconCache<BitmapDescriptor> _pinIconCache = new(MaxIconCacheSize); | ||
| readonly IconCache<BitmapDescriptor> _clusterIconCache = new(MaxIconCacheSize); |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[moderate] Memory Leak Prevention / Performance — MaxIconCacheSize (64) is now applied twice rather than split, so the handler's worst-case retained descriptor count doubles from 64 to 128. Each entry is a BitmapDescriptor over a 64x64 bitmap plus a JNI global ref, and both caches are constructed without the optional disposeValue action, so IconCache.Clear() and EvictLeastRecentlyUsed() only drop managed references — the Java peers are released whenever the GC bridge gets to them, not deterministically.
Concrete scenario: a map with >64 distinct pin images plus a IMapClusterImageProvider returning several distinct cluster images now holds up to 128 live descriptors where the previous single cache capped at 64.
A cluster image provider typically yields a handful of distinct images, not 64, so consider partitioning the existing budget instead of duplicating it (e.g. MaxPinIconCacheSize = 48 / MaxClusterIconCacheSize = 16). That still achieves the stated goal — pin churn can no longer evict cluster entries — without raising the handler's peak native footprint.
| _clusterImageVersion = version; | ||
| _iconCache.Clear(); | ||
| // Cluster entries only: a version bump says nothing about the pins' own ImageSources. | ||
| _clusterIconCache.Clear(); |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[moderate] Regression Prevention — This narrows cache invalidation scope (version bump and owner change no longer drop pin icons), and it lands on code churned by three PRs in quick succession (#37769, #37770, #37774) with #37943 already reporting a regression from #37774. No test in this PR pins either of the two invariants the new comment at line 52 asserts: (a) a ClusterImageVersion bump leaves pin entries intact, and (b) cluster entries survive pin traffic past MaxIconCacheSize.
src/Controls/tests/Core.UnitTests/MapTests.cs already exercises IconCache<T> directly (IconCacheEvictsLeastRecentlyUsedEntry, IconCacheCoalescesConcurrentLoads, IconCacheDoesNotReloadAKeyedSourceOnALaterPass) and MapHandler.GetIconCacheKey, so the platform-neutral seam for a partition test exists — what is missing is a seam on the Android handler that lets a test observe which cache a bump clears. Note the owner-change branch above also stops clearing pin entries when the handler is rebound to a different IMap; that appears benign because keys are content-derived, but it is a second untested behavior change folded into the same line.
MauiBot
left a comment
There was a problem hiding this comment.
AI Review Summary
@kevin68 — new AI review results are available based on commit
83d96a8.
🗂️ Review Sessions — click to expand
🚦 Gate — Test Before & After Fix
Gate Result: ⚠️ SKIPPED
No tests were detected in this PR.
Recommendation: Add tests to verify the fix using the write-tests-agent.
📋 Pre-Flight — Context & Validation
PR #37944 Pre-Flight
Context
- Title:
[Android] Map: Stop pin icons and cluster icons evicting each other - Base / head:
net11.0/fix/android-map-pin-icon-cache-eviction - Local review commit:
6db29085866b2af792e5123656eff2c9db0f2eb7(PR #37944 squashed for review) - Issue: #37943, Android Maps regression introduced by #37774.
- Problem: A single bounded
IconCache<BitmapDescriptor>holds both pin and cluster icons. More than 64 distinct pin images can continuously evict the cluster icon, while a cluster-image version change clears unrelated pin icons. Both paths cause repeated decode/resize work, allocation churn, and zoom jank without changing rendered correctness.
Existing PR approach
The PR changes only src/Core/maps/src/Handlers/Map/MapHandler.Android.cs:
- Replaces
_iconCachewith separate_pinIconCacheand_clusterIconCacheinstances. - Clears both caches on handler disconnect, but clears only the cluster cache when the cluster image owner/version changes.
- Changes
GetIconAsyncto accept the selected cache. - Routes pin-add and pin-property-change loads through the pin cache, while cluster loads use the cluster cache.
This directly isolates the two traffic classes. Alternative candidates must use a different root-cause mechanism rather than reproducing the same two-cache partition.
Constraints and baseline
- Platform: Android.
- The source worktree is clean; unrelated pre-existing
.github/engharness changes must remain untouched. - The try-fix baseline must be established and restored only with
.github/scripts/EstablishBrokenBaseline.ps1. - The baseline allow-list is expected to contain only
src/Core/maps/src/Handlers/Map/MapHandler.Android.cs; if it does not, the attempt must be blocked rather than edit another tracked file. - No public API change is involved.
Test evidence and bounded validation
-
Gate result is already persisted and must not be rerun: SKIPPED — no tests detected in this PR.
-
Android
Controls.DeviceTestsmap tests cannot instantiateMapViewbecause the test environment has no Google Maps API key. -
The only permitted regression command for each candidate is the author-reported targeted class:
dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --filter "FullyQualifiedName~Microsoft.Maui.Controls.Core.UnitTests.MapTests"
-
Do not run a full suite or any gate verification. Each candidate receives one implementation/test pass and at most one focused correction/retest.
Candidate differentiation
Candidate 1 must avoid the PR's two-cache partition. Candidate 2 must additionally read candidate 1's persisted result and avoid both its mechanism and the PR mechanism. A blocked or failed attempt is still a completed candidate and must be recorded honestly.
🔬 Code Review — Deep Analysis
Expert Code Review — PR #37944
Independent Assessment
What this changes: The Android MapHandler replaces one shared 64-entry IconCache<BitmapDescriptor> with separate pin and cluster caches, passes the selected cache into a static GetIconAsync helper, clears both caches during handler cleanup, and limits cluster-version invalidation to the cluster cache. It also changes UpdatePinImageSourceAsync from a direct image load to the pin cache.
Inferred motivation: Isolating the caches prevents high-cardinality pin traffic from evicting cluster descriptors and prevents a cluster-image version change from invalidating unrelated pin descriptors. Reusing the pin cache from the property-change path also coalesces identical concurrent pin loads.
The partitioning mechanism is sound: each IconCache<T> owns its synchronization, entries, in-flight loads, generation, and LRU counter. Cluster-image versioning applies only to images obtained from IMapClusterImageProvider, and cancellation/post-await guards remain intact.
Reconciliation with PR Narrative
The description accurately explains the cross-eviction regression, the two-cache fix, and the newly cached property-change path. The latter is an independent behavioral change rather than a prerequisite for cache partitioning: keyed file sources no longer have a guaranteed fresh-load path during a connected handler's lifetime. That consequence should be made explicit or avoided.
Prior Review Reconciliation
Prior review and CI surfaces were unavailable to the expert reviewer because GitHub CLI authentication was unavailable. No prior error-level finding was present in the supplied pre-flight record.
Blast Radius Assessment
- Runs for all affected instances: Android maps that use pin images and/or cluster images; other platforms are unchanged.
- Startup impact: none.
- Static/shared state: none; both caches remain handler-instance fields.
- Lifecycle: both caches are cleared when the handler disconnects.
- Public API: unchanged.
CI Status
- Required-check result: unavailable to the expert reviewer.
- Gate result: skipped because this PR contains no detected tests.
- Classification: code mechanism reviewed, regression coverage undetermined.
- Action taken: confidence capped by the Android handler scope and missing PR tests.
Findings
⚠️ Warning — The property-change path can retain stale file-backed icons
UpdatePinImageSourceAsync now uses _pinIconCache, whose only remaining clear site is handler cleanup. Rewriting a file and assigning a new FileImageSource with the same path produces the same non-expiring cache key, so the old descriptor can remain until disconnect or incidental LRU eviction. The partition fix does not require this change. Either preserve a fresh load on the property-change path or explicitly document and accept the changed refresh semantics.
⚠️ Warning — The maximum retained descriptor budget doubles
Both new caches use MaxIconCacheSize (64), increasing the per-handler worst case from 64 to 128 descriptors. Because eviction drops references without deterministic native disposal, retain the isolation while partitioning the previous total budget between pin and cluster caches.
⚠️ Warning — The new isolation invariants have no regression coverage
The PR does not test that pin traffic cannot evict cluster entries or that cluster invalidation leaves pin entries intact. Existing platform-neutral IconCache<T> tests provide a practical seam for the partition behavior, although handler wiring would need an observable seam for direct invalidation verification.
Failure-Mode Probing
- Pin and cluster loads in flight at the same time: they no longer coalesce across categories, but the image services are re-entrant and the duplicate load is the stated isolation tradeoff.
- Pins reset while a keyed load continues: the unchanged cancellation, source-identity, and marker-id guards discard obsolete results.
- Handler disconnect/reconnect: both caches clear during cleanup; no state survives handler disposal.
- Map owner changes while keys overlap: retained pin values are content-keyed, so ordinary unchanged image sources remain valid, but mutable same-path file content exposes the stale-entry warning above.
- More than 64 distinct pin images: pin churn stays confined to the pin cache and no longer evicts cluster entries.
External Output Contract
Not applicable.
Verdict: NEEDS_DISCUSSION
Confidence: low
Summary: The submitted partitioning fix addresses the reported cross-eviction root cause with a small, coherent Android-only change. A consolidated refinement can preserve the prior memory budget, avoid the newly introduced stale-file refresh behavior, and add focused coverage; the skipped Gate prevents treating the raw PR as fully verified.
🛠️ Try-Fix — Analysis & Comparison
PR #37944 Try-Fix Aggregate
Pre-flight status
Complete. PR #37944 ([Android] Map: Stop pin icons and cluster icons evicting each other,
base net11.0, local squashed review commit 6db2908586) changes only
src/Core/maps/src/Handlers/Map/MapHandler.Android.cs. Existing PR mechanism: split the single
64-entry IconCache<BitmapDescriptor> into _pinIconCache / _clusterIconCache, pass the chosen
cache into a static GetIconAsync, route pin and cluster loads separately, and clear only the
cluster cache on a ClusterImageVersion bump. Gate: SKIPPED — no tests detected in this PR
(persisted; must not be rerun). Android device MapTests are unavailable (no Google Maps API key);
the only permitted validation command is the targeted MapTests filter on
Controls.Core.UnitTests. Candidates must not reproduce the PR's two-cache partition.
Candidate 1 — Blocked
Result: Blocked (blocked at Workflow Step 2, before any source file was modified)
Artifacts: CustomAgentLogsTmp/PRState/37944/PRAgent/try-fix/attempt-1/
(baseline.log, approach.md, reviewer-findings.json, reviewer-findings.diff, result.txt,
fix.diff, test-output.log, analysis.md).
Problem restated
src/Core/maps/src/Handlers/Map/MapHandler.Android.cs uses one 64-entry
IconCache<BitmapDescriptor> (_iconCache) for both pin icons and cluster icons. High-cardinality
pin traffic evicts the cluster icon on every recluster pass, and UpdateClusterImageVersion calls
_iconCache.Clear(), destroying unrelated pin icons. Both paths cause repeated Android
decode/rescale work and zoom jank without changing rendered correctness.
Approach and mechanism-level difference from the PR
Candidate approach — Handler-Owned, Version-Keyed Cluster Icon Memo (designed, never applied).
Keep exactly ONE IconCache<BitmapDescriptor> (_iconCache, capacity 64) serving pin icons only.
Give the cluster icon an explicit owner instead of cache residency: a handler field holding
(int Version, string? Key, BitmapDescriptor Icon). The cluster marker path consults that memo; on
miss it calls LoadPinIconAsync directly, bypassing IconCache entirely, and stores the descriptor
with the current _clusterImageVersion and GetIconCacheKey value. UpdateClusterImageVersion
resets only that field and no longer calls _iconCache.Clear().
Prior approach avoided. The PR partitions the single bounded LRU into _pinIconCache and
_clusterIconCache, converts GetIconAsync to a static that takes the chosen cache, routes pin-add
and pin-property-change loads to the pin cache and cluster loads to the cluster cache, clears both
on disconnect, and clears only the cluster cache on a version bump. Its framing of the failure
mechanism is capacity contention: two traffic classes competing for the same 64 LRU slots. The
PR did not fail — it is simply the mechanism this candidate is forbidden to reproduce.
Mechanism-level difference (cause-to-effect chain). This candidate rejects the
capacity-contention framing and adopts a lifetime-ownership root cause: the cluster icon is a
single, map-scoped, explicitly versioned resource that was wrongly modelled as an anonymous,
image-source-keyed, evictable LRU entry. Because it had no owner, two consequences followed:
(a) its lifetime was decided by LRU pressure from unrelated pin cardinality, and (b) its only
invalidation signal — a ClusterImageVersion bump — had to be broadcast destructively as Clear()
because the cache had no vocabulary for "just the cluster entry". Naming the cluster icon in a
handler field breaks both links with one change: an entry that never enters the LRU cannot be
evicted by pin traffic at any cardinality, and an invalidation that targets a field can never reach
pin entries. This is not the PR's split relocated — it removes the cluster icon from cache-managed
lifetime altogether, so there is no second LRU, no cache parameter threaded through GetIconAsync
(signature unchanged), and cluster decode is bounded to once per version rather than once per
eviction. IconCache itself lives in MapHandler.cs, outside the allow-list, and was never a
candidate for modification.
Files changed
None. Zero source files were modified. The attempt was blocked before Step 5 (Apply the Fix).
Exact captured diff
git diff -- src/ was empty; attempt-1/fix.diff is a 0-byte file:
Blocker detail
pwsh .github/scripts/EstablishBrokenBaseline.ps1 aborted with:
╔═══════════════════════════════════════════════════════════════════╗
║ ERROR: DIRTY WORKING DIRECTORY - Cannot establish baseline ║
╚═══════════════════════════════════════════════════════════════════╝
...
EstablishBrokenBaseline.ps1 failed: Working directory is not clean.
Clean up before establishing baseline.
(throw at EstablishBrokenBaseline.ps1:392, exit code 1; full text in attempt-1/baseline.log.)
The ~58 dirty tracked paths are all harness-owned files under .github/scripts/, .github/skills/
and eng/scripts/ — which this exercise forbids editing, reverting, cleaning, stashing, or
disturbing. The script's fail-fast clean gate is unconditional and has no exclusion/force parameter
(its only parameters are -BaseBranch, -DryRun, -Restore; the .github/* entry in
$script:TestPathPatterns filters fix-file detection only, not the clean gate).
Consequently .github/.baseline-state.json was never created. With no state file there is no
RevertedFiles allow-list, and try-fix Core Principle 7 / Step 2 mandate reporting Blocked before
editing any tracked file. Editing MapHandler.Android.cs regardless would have produced drift the
script-only restore path could not undo.
Test command and result
The single permitted validation command,
dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --filter "FullyQualifiedName~Microsoft.Maui.Controls.Core.UnitTests.MapTests"
was deliberately not executed. With zero code changes it could only re-measure the unmodified
tree and could produce no evidence about the candidate fix. No full suite, no extra builds, and no
other tests were run. Gate verification was not rerun and gate/content.md was not touched.
Self-review
Count: 0 findings (reviewer-findings.json = []). Performed inline against
.github/agents/maui-expert-reviewer.md (Overarching Principles plus the always-active Logic and
Correctness, Regression Prevention, and Complexity Reduction dimensions) over an empty diff — the
documented zero-change path. No reviewer sub-agent was spawned. Step 7.5 drift check: the diff was
empty at Step 6 and still empty afterwards, so no refresh was required.
Failure analysis
The blocker is environmental and deterministic, not approach-specific. Any candidate for this PR
hits the identical gate while the worktree carries harness-owned tracked modifications, because the
gate runs before fix-file detection and cannot be satisfied without disturbing files this exercise
protects. Nothing about the cluster-icon design caused the block, and no evidence was obtained for
or against it.
Because the bound allows one implementation/test pass plus at most one focused correction, and the
only available "correction" would have been to clean the protected harness paths (explicitly
prohibited) or to edit source without an allow-list (prohibited by Step 2), the honest terminal
state is Blocked. No retry was attempted.
Carry-forward for candidate 2: expect the same Blocked outcome unless the clean gate is relaxed.
The handler-owned, version-keyed cluster-icon memo above remains untested and unvalidated, so
candidate 2 must still choose a third mechanism distinct from both the PR's two-cache partition and
this ownership memo.
Restoration
pwsh .github/scripts/EstablishBrokenBaseline.ps1 -Restore was run as the only cleanup command and
reported No baseline state found / Restored False — the expected result for the verified
no-state path with zero attempt edits. git status --porcelain src/ is empty: no attempt-created
source changes remain. Pre-existing harness-owned .github/eng changes were left untouched.
Candidate 2 — Blocked
Result
Blocked at Workflow Step 2, before any source modification.
Approach
Single-LRU Admission Control with Version-Scoped Cluster Keys. Retain one shared IconCache<BitmapDescriptor>, but admit only a bounded working set of stable pin keys, leaving residency for cluster entries; pin keys outside that working set load directly and never pollute the LRU. Cluster lookups use a key namespaced by map owner/version. A version bump therefore selects a new cluster entry rather than calling Clear(), while the stale entry ages out normally.
Explicit differences from both excluded approaches
The existing PR physically partitions traffic into two bounded LRU instances (_pinIconCache and _clusterIconCache) and routes each call to one cache. Candidate 1 instead removes cluster descriptors from cache-managed lifetime and holds one handler-owned (Version, Key, Icon) memo. Candidate 2 does neither: it retains exactly one LRU and cluster descriptors remain ordinary entries in that LRU; it introduces no handler-owned cluster-icon field.
The cause-to-effect model is also different. The PR treats capacity contention by isolation, and candidate 1 treats cluster lifetime as explicit handler ownership. Candidate 2 treats indiscriminate admission plus destructive invalidation as the root causes: non-reusable high-cardinality pin keys do not enter the shared LRU and therefore cannot evict a hot cluster entry; cluster version/owner participates in lookup identity, so invalidation makes only the old cluster identity unreachable and never clears pins. Old cluster entries leave through normal LRU pressure. This is admission and key-policy control, not cache partitioning or out-of-cache memoization.
Baseline and blocker
The mandatory command was run once and captured in try-fix/attempt-2/baseline.log:
pwsh .github/scripts/EstablishBrokenBaseline.ps1
It exited 1 with ERROR: DIRTY WORKING DIRECTORY - Cannot establish baseline and listed the pre-existing harness-owned .github/eng changes. Afterward .github/.baseline-state.json was absent. Therefore there was no RevertedFiles allow-list; the target could not legally be edited. NewFiles could not be evaluated because no state file existed. The protected dirty files were not cleaned, stashed, reverted, deleted, or otherwise disturbed.
Files changed
None. The planned allow-listed file was src/Core/maps/src/Handlers/Map/MapHandler.Android.cs, but it was not modified.
Exact captured diff
attempt-2/fix.diff is empty:
Validation
The only permitted validation command was:
dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --filter "FullyQualifiedName~Microsoft.Maui.Controls.Core.UnitTests.MapTests"
Result: NOT RUN. With baseline establishment blocked and no implementation applied, it could provide no candidate evidence. No gate, device test, build, full suite, extra test, correction, or retest was run.
Inline expert self-review
0 findings (attempt-2/reviewer-findings.json contains []). With an empty source diff, the review applied the eight Overarching Principles and the always-active Logic and Correctness, Regression Prevention, and Complexity Reduction dimensions from .github/agents/maui-expert-reviewer.md. reviewer-findings.diff matches the empty final source diff. No reviewer or other agent was spawned.
Failure analysis
This is a deterministic environment gate failure, not evidence for or against the proposed mechanism. The script rejects the dirty worktree before generating baseline state; bypassing it or disturbing the pre-existing harness changes was prohibited. The final candidate therefore ends honestly as Blocked, with the third mechanism designed but never applied or tested.
Restoration
Immediately after artifact capture, the only restoration command executed was exactly:
pwsh .github/scripts/EstablishBrokenBaseline.ps1 -Restore
It exited 0 and reported:
No baseline state found. Nothing to restore.
Name Value
---- -----
Message No baseline state found
Restored False
This is the expected no-state result because baseline creation failed and no attempt source edits were made. The target remains free of attempt-created changes.
Artifacts
All required files exist under CustomAgentLogsTmp/PRState/37944/PRAgent/try-fix/attempt-2/: baseline.log, approach.md, reviewer-findings.json, reviewer-findings.diff, result.txt, fix.diff, test-output.log, and analysis.md.
📝 PR Finalize — Recommended Title & Description
Assessment: ✏️ Recommend updating — the title is precise, but the description's absolute “no correctness change” claim omits the raw PR's same-key file refresh behavior and its doubled aggregate cache capacity.
Recommended title
[Android] Map: Stop pin icons and cluster icons evicting each other
Recommended description
### Description of Change
Fixes #37943.
#37774 added a bounded LRU of decoded marker icons, and during review I merged the per-pin cache into the cluster one so a single instance served both. That sharing is the bug — I introduced it, so this is a self-report.
Pin icons and cluster icons compete for the same 64 entries and evict each other in both directions:
- **Pin traffic evicts the cluster icon.** Un-clustered pins decode on every recluster pass, so with more distinct pin images than the capacity they keep the cluster entry least recently used. It is evicted and re-decoded each pass — the exact work the cache was added to avoid. Past the capacity the cache degenerates to a 0% hit rate, leaving such a map worse off than before it existed.
- **A cluster image change discards the pin icons.** `UpdateClusterImageVersion` calls `Clear()` on the shared instance, so a `ClusterImageSource` change throws away every decoded pin icon even though no pin `ImageSource` changed.
Two instances isolate the eviction domains, and the version bump now clears only the cluster one. Each instance retains up to 64 entries, so the handler's aggregate maximum increases from 64 to 128 descriptors. A pin and a cluster naming the same image also decode twice; that is rarer than either cross-eviction path.
`UpdatePinImageSourceAsync` also goes through the pin cache now, so the two pin-icon paths agree — previously `AddPinAsync` used the cache and the property-change path did not. This makes switching many live pins to one image coalesce into a single load instead of one per pin, and leaves the entry there for the following recluster pass. It hands a keyable load `CancellationToken.None`, so such a load can outlive a pins reset; the guards after the await still discard the result, matching the trade `AddPinAsync` already made.
Caching the property-change path also changes refresh behavior for stable keys. In particular, replacing the contents of a file and assigning a new `FileImageSource` with the same path can reuse the descriptor already held by the pin cache until that entry is evicted or the handler disconnects. Stable image sources whose content has not changed render identically before and after; the fix targets decode and rescale churn on zoom.
### Issues Fixed
Fixes #37943
### Validation
The repro page is on a branch rather than in this PR: [`repro/issue-37943`](https://github.com/kevin68/maui/blob/repro/issue-37943/src/Controls/tests/TestCases.HostApp/Issues/Issue37943.cs), matching what was done for #37775. It is not merged here because the symptom is decode churn with no UI-observable effect, so there is no `TestCases.Shared.Tests` case to drive it — a page nothing runs in CI is maintenance surface, not coverage.
The page drives three scenarios and emits `PROBE` phase markers. Counting decodes needs one line inside `LoadPinIconAsync`, which its header comment gives.
Measured on a Samsung SM-X230, Android 16, running that page on both arms with the line in place. Counts are decodes of the named image:
| phase | image counted | before | after |
|---|---|---|---|
| 1 — 6 recluster passes, 100 distinct pin images | cluster image | **1 per pass** (7 total) | **1 total** |
| 2 — `ClusterImageSource` changed | pin icons | **5 re-decoded** | **0** |
| 3 — 12 live pins switched to one image | that image | **12** | **1** |
| 3 — the recluster pass that follows | that image | **1 more** | **0** |
The 100 distinct pin images in phase 1 are re-decoded identically in both arms (700 each) — more distinct images than the capacity is ordinary bounded-LRU behaviour, not the regression. They are there to create the eviction pressure the measurement needs.
`Microsoft.Maui.Controls.Core.UnitTests` MapTests: 108/108.
🏁 Report — Final Recommendation
⚠️ Final Recommendation: REQUEST CHANGES
Winner: pr (the raw submitted fix)
The submitted PR is the only implemented candidate without a known build regression. Its separate pin and cluster caches directly remove both cross-eviction paths, preserve handler cleanup and post-await guards, and have author-reported targeted MapTests evidence of 108/108 passing. That evidence was not rerun in this phase, and the trusted Gate was skipped because the PR adds no tests.
Comparative ranking
| Rank | Candidate | Mechanism | Validation | Assessment |
|---|---|---|---|---|
| 1 | pr |
Separate pin and cluster IconCache<BitmapDescriptor> instances; cluster version changes clear only cluster entries |
Author reports 108/108 targeted MapTests; Gate skipped with no PR tests |
Winner. Smallest complete implementation and no observed build failure, but expert-review discussion items remain unresolved. |
| 2 | try-fix-1 |
Proposed handler-owned, version-keyed cluster memo outside the pin LRU | Blocked before implementation or tests | Plausible isolation model, but there is no diff or empirical evidence to evaluate. |
| 3 | try-fix-2 |
Proposed one-LRU admission control plus version-scoped cluster keys | Blocked before implementation or tests | More policy complexity than the submitted split and likewise has no implementation or validation evidence. |
| 4 | pr-plus-reviewer |
Raw PR plus fresh property-change loads, a 48/16 cache-budget split, and a testable cache-pair abstraction | Failed: Maps.csproj did not compile; no tests ran |
The intended refinements address the expert comments, but the persisted candidate has a concrete syntax regression and must rank below the passing raw-PR evidence. |
Both try-fix attempts were blocked by the mandatory broken-baseline script rejecting pre-existing harness-owned changes. Neither modified source or ran the permitted test command, so they cannot displace an implemented fix.
Expert evaluation of the submitted fix
The cache partition itself is sound. Each cache owns its entries, LRU counters, generation, synchronization, and in-flight loads; cluster versioning is scoped to cluster images; both caches clear on disconnect; and the existing cancellation and stale-result guards remain intact.
Three non-error findings prevent an approval recommendation:
UpdatePinImageSourceAsyncnow caches stable keys for the handler lifetime. Replacing a file's contents and reassigning aFileImageSourcewith the same path can retain the old descriptor until eviction or disconnect, whereas the pre-PR property-change path loaded fresh.- Applying the 64-entry capacity independently to both caches raises the worst-case retained descriptor count from 64 to 128.
- The PR adds no regression test for either isolation invariant, and the trusted Gate is therefore skipped.
The failed pr-plus-reviewer result does not disprove those review concerns; it only means that candidate cannot be recommended as the ready-to-apply solution. The raw PR remains the best candidate, but the author should resolve or explicitly justify the refresh and memory-budget tradeoffs and add focused regression coverage before approval.
Decision
Select pr as the single winner. Request changes rather than approve because the Gate does not permit approval and the expert review leaves concrete discussion items unresolved. Do not apply the pr-plus-reviewer patch as persisted: its sole targeted validation failed before test execution.
📱 UI Tests — Button,Label,Layout
Detected UI test categories: Button,Label,Layout
✅ Deep UI tests — 360 passed, 0 failed, 7 skipped across 3 categories on platform-pool agent (replaces in-process counts above).
🧪 UI Test Execution Results (deep, platform pool)
| Category | Tests | Snapshot diffs |
|---|---|---|
Button |
71/73 (2 skipped) ✓ | — |
Label |
97/99 (2 skipped) ✓ | — |
Layout |
192/195 (3 skipped) ✓ | — |
📎 Download drop-deep-uitests artifact (TRX + snapshot diffs) |
🧭 Next Steps — review latest findings
No alternative fix was selected for this run. Review the session findings and CI results before merging.
Description of Change
Fixes #37943.
#37774 added a bounded LRU of decoded marker icons, and during review I merged the per-pin cache into the cluster one so a single instance served both. That sharing is the bug — I introduced it, so this is a self-report.
Pin icons and cluster icons compete for the same 64 entries and evict each other in both directions:
UpdateClusterImageVersioncallsClear()on the shared instance, so aClusterImageSourcechange throws away every decoded pin icon even though no pinImageSourcechanged.Two instances, and the version bump now clears only the cluster one. The cost is that a pin and a cluster naming the same image decode twice, which is rarer than either eviction path.
UpdatePinImageSourceAsyncalso goes through the pin cache now, so the two pin-icon paths agree — previouslyAddPinAsyncused the cache and the property-change path did not. This makes switching many live pins to one image coalesce into a single load instead of one per pin, and leaves the entry there for the following recluster pass. Note it hands a keyable loadCancellationToken.None, so such a load can outlive a pins reset; the guards after the await still discard the result, and it is the tradeAddPinAsyncalready made.Nothing here is a correctness change — icons rendered correctly before and after. This is decode and rescale churn on zoom.
Issues Fixed
Fixes #37943
Validation
The repro page is on a branch rather than in this PR:
repro/issue-37943, matching what was done for #37775. It is not merged here because the symptom is decode churn with no UI-observable effect, so there is noTestCases.Shared.Testscase to drive it — a page nothing runs in CI is maintenance surface, not coverage.The page drives three scenarios and emits
PROBEphase markers. Counting decodes needs one line insideLoadPinIconAsync, which its header comment gives.Measured on a Samsung SM-X230, Android 16, running that page on both arms with the line in place. Counts are decodes of the named image:
ClusterImageSourcechangedThe 100 distinct pin images in phase 1 are re-decoded identically in both arms (700 each) — more distinct images than the capacity is ordinary bounded-LRU behaviour, not the regression. They are there to create the eviction pressure the measurement needs.
Microsoft.Maui.Controls.Core.UnitTestsMapTests: 108/108.