Skip to content

[Android] Map: Keep the custom pin icon when a pin leaves a cluster - #37769

Merged
kubaflo merged 5 commits into
dotnet:net11.0from
kevin68:fix/android-map-cluster-pin-icon
Aug 27, 2026
Merged

kubaflo merged 5 commits into
dotnet:net11.0from
kevin68:fix/android-map-cluster-pin-icon

Conversation

@kevin68

@kevin68 kevin68 commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #37767

Description of Change

On Android, a Pin whose ImageSource is a rooted file path came back with the default red marker after leaving a cluster, then corrected itself on a later zoom.

That source loads through Glide, and LoadPinIconAsync released the image result with a using. ImageLoaderCallbackBase completes its TaskCompletionSource synchronously, so the continuation - and with it the Dispose - can run inside Glide's own target callback, where MauiCustomTarget.clear() calls Glide.clear() and Glide throws IllegalStateException: You can't start or clear loads in RequestListener or Target callbacks. Because the throw happened while disposing, it replaced the BitmapDescriptor that had already been built: LoadPinIconAsync returned null and AddPinAsync created the marker without an icon.

A Pin.ImageSource backed by a MauiImage never hit this - it resolves through the synchronous Context.GetDrawable path. The failure looked intermittent because a MarkerOptions reused from an earlier successful load masked it; a fresh handler (any change to the Pins collection disconnects them) unmasked it.

Fix: hand the release to the next turn of the main loop. By then the Glide callback has unwound, so the clear succeeds - the icon survives and the Glide entry is genuinely released instead of leaked, which is what the MauiCustomTarget TODO asks for. The release is still guarded and logged so that a service whose dispose action fails for another reason cannot discard an icon that was already built; the logger is resolved before the post, because an exception raised from a looper callback takes the process down rather than faulting a task.

Releasing for real exposes something the leak used to mask. Bitmap.createScaledBitmap hands an immutable source straight back when the image already fits - the 64x64 that Pin.ImageSource documents for Android - so the descriptor would be built over pixels the image result owns, and releasing that result lets them go. Hardware bitmaps, which Glide emits on API 26+, are the common immutable case here. This PR copies in that branch, retargeting Config.Hardware to Argb8888 since hardware pixels cannot be read back, and never falls back to the source: a failed copy means the default marker rather than a descriptor over foreign pixels. The sibling branch of the same method already guarded against the identity return (if (scaled != bitmap) bitmap.Dispose();), so this behaviour of the helper was known - the BitmapDrawable branch just never had to account for it while nothing released.

To be explicit about what fixes what: the deferred release alone restores the icon - verified on device before the copy existed. The copy is defensive, and belongs with the release because releasing for real is what makes a source-owned bitmap reachable by the descriptor at all.

A tighter fix exists one layer down - MauiCustomTarget.post() runs its runnable inline when already on the main looper, which is what puts clear() inside the callback in the first place, and Glide's own message suggests posting instead. That would make disposal safe for every C# caller rather than this one. It is deliberately out of scope here because it changes image loading for all of MAUI; happy to open it separately if maintainers prefer that direction.

The redundant-reload half of this work was split into its own PR to keep the bug fix and the caching behaviour separately reviewable.

Verification

Physical device (Samsung SM-X230, Android 15), clustering gallery using pins whose icon is a PNG written to FileSystem.CacheDirectory, handler instrumented at each boundary.

Three zoom-in/zoom-out cycles over 25 clustered custom pins:

before after
Glide IllegalStateException 29 0
icon loads discarded 29 0
markers created without their icon 0 (masked by a surviving MarkerOptions) 0
recycled-bitmap / canvas errors - 0

Re-run after the split, both alone and merged with the reload PR: no Glide asserts, no recycled-bitmap errors, no crashes, every de-clustered pin keeps its icon.

Issues Fixed

Fixes #37767

@kevin68
kevin68 temporarily deployed to copilot-pat-pool August 24, 2026 09:18 — with GitHub Actions Inactive
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
There may be pipelines that require an authorized user to comment /azp run to run.

@github-actions

Copy link
Copy Markdown
Contributor

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 37769

Or

  • Run remotely in PowerShell:
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 37769"

@dotnet-policy-service dotnet-policy-service Bot added the community ✨ Community Contribution label Aug 24, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

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.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

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.

@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Aug 24, 2026

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Expert Review — 5 findings

See inline comments for details.


// Resolved now rather than inside the post: the service provider can be gone by the time
// the release runs, and an exception thrown from a looper callback takes the process down.
var logger = mauiContext.Services.GetService<ILogger<MapHandler>>();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[moderate] Null Safety and Defensive Coding — ReleaseImageResult is invoked from the finally of LoadPinIconAsync, i.e. outside the catch (System.Exception ex) above it, and the first thing it does is resolve a service from mauiContext.Services. If the window/scoped IServiceProvider has already been disposed (window closing, handler disconnected while a pin image load is in flight), GetService<ILogger<MapHandler>>() throws ObjectDisposedException from the finally block. That exception cannot be caught by the method's own catch, so it discards the BitmapDescriptor that was already built successfully and faults the returned Task. Concrete scenario: AddPinAsync awaits LoadPinIconAsync and the fault propagates before Map.AddMarker(markerOptions) runs, so the pin is not added at all (the call site uses .FireAndForget(), so the failure is silent) — a missing pin rather than a missing icon. Resolve the logger inside a try/catch, or reuse a logger captured before the load so the release path cannot throw.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed — and you are right that this was the same failure I was fixing, one level up. ReleaseImageResult runs from the finally, outside the method's own catch, so an ObjectDisposedException from GetService would have replaced the descriptor that was already built. Worse than the original bug, in fact: AddPinAsync faults before Map.AddMarker, so the pin is missing rather than un-iconed, and .FireAndForget() swallows it.

The whole body of ReleaseImageResult is now inside a try/catch so nothing on that path can escape into the finally, with a comment saying why the swallow is deliberate there. The logger is still resolved before the post, so the posted runnable cannot throw into the looper either.

// the size Pin.ImageSource documents for Android. That bitmap belongs to the image
// source, and Glide returns it to its pool as soon as the result is released, so the
// descriptor must not be built over those pixels.
return source.Copy(source.GetConfig() ?? ABitmap.Config.Argb8888!, false) ?? sized;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[moderate] Image Handling / Logic and Correctness — the ?? sized fallback returns source. Inside this branch ReferenceEquals(sized, source) is already known to be true, so when Bitmap.Copy returns null (the documented failure mode: allocation failure / unsupported config) the method hands back exactly the bitmap the comment above says must not back the descriptor. The descriptor is then built over pixels the image result owns, and the deferred result.Dispose() lets Glide return them to its pool — reintroducing the recycled-pixel case this branch exists to prevent, and for the cluster path it is worse because _clusterIconCache keeps that descriptor for later markers. Returning null here would make LoadPinIconAsync fall back to the default marker instead. Separately, source.GetConfig() can be Bitmap.Config.Hardware on API 26+ (Glide emits hardware bitmaps, which are immutable and therefore the ones that actually reach this branch); Copy(Config.Hardware, false) yields another hardware bitmap whose pixels BitmapDescriptorFactory.FromBitmap cannot read. Mapping Hardware to Argb8888 here would cover that case.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Both fixed.

The ?? sized fallback was plainly wrong — inside that branch sized is source, so a failed Copy handed back exactly the bitmap the comment above says must not back the descriptor. It now returns null, which makes LoadPinIconAsync fall back to the default marker: a missing icon is recoverable, a descriptor over foreign pixels is not.

The hardware-bitmap case is handled too — GetConfig() is retargeted to Argb8888 when it is null or Config.Hardware, guarded by OperatingSystem.IsAndroidVersionAtLeast(26) so the enum field is not touched on older API levels. As you note, hardware bitmaps are immutable, which makes them the main way this branch is reached at all — see the reply on the reachability thread.

{
return ScaleBitmap(bitmapDrawable.Bitmap, 64, 64); // 64x64 pixels
var sized = ScaleBitmap(source, 64, 64); // 64x64 pixels
if (!ReferenceEquals(sized, source))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[moderate] Logic and Correctness — this guard assumes ScaleBitmap "hands the source instance straight back when the image already fits". ScaleBitmap calls Bitmap.createScaledBitmap, and AOSP's Bitmap.createBitmap(source, x, y, w, h, m, filter) returns source unchanged only when !source.isMutable() and the rect/matrix are identity. Bitmaps decoded by Glide are allocated from its BitmapPool and are mutable, so on the Glide path createScaledBitmap allocates a new bitmap even at exactly 64x64 and ReferenceEquals(sized, source) is false — the copy below never executes for the pooled-bitmap case the comment describes. The branch is reachable only for immutable sources (resource-decoded or hardware bitmaps). Please confirm against the original #37767 reproduction which of the two changes in this PR actually restores the icon; if the deferred release alone fixes it, this second change is defensive only and its stated rationale is inaccurate. If pooled-bitmap recycling really is in play, the identity test needs to be based on the pool/mutability, not on reference identity.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

You are right, and I have corrected the comment: my stated rationale was wrong.

AOSP createBitmap(source, x, y, w, h, m, filter) returns source only when !source.isMutable(), so a mutable pooled bitmap is never handed straight back and the branch is not reached for that case. It is reached for immutable sources — including the hardware bitmaps Glide emits on API 26+, which is also why the sibling comment now retargets Config.Hardware. The comment no longer claims the pooled-mutable story.

To answer your direct question: the deferred release alone restores the icon. I verified that on a physical device before the copy existed — three zoom cycles over 25 clustered pins backed by a rooted file path, 29 Glide IllegalStateException before, 0 after, every de-clustered pin keeping its icon. The copy is defensive only, and its purpose is narrower than I first wrote: releasing for real is what makes an immutable source-owned bitmap reachable by the descriptor at all, so the guard belongs with the release even though it is not what fixes #37767.

// Returns null on cancel/failure/no drawable.
static async Task<BitmapDescriptor?> LoadPinIconAsync(IImageSource imageSource, IMauiContext mauiContext, CancellationToken ct)
{
IImageSourceServiceResult<ADrawable>? result = null;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[moderate] Regression Prevention and Test Coverage — this PR fixes a regression (#37767, from #36235) with no accompanying test. The failure is a real ordering bug: ImageLoaderCallbackBase.OnComplete completes the TaskCompletionSource synchronously from inside MauiCustomTarget.onResourceReady, so the continuation after this await — including the old using disposal — runs inside Glide's own target callback, and MauiCustomTarget.clear() sees Looper.isCurrentThread() and calls Glide.clear() inline from that forbidden context. Nothing in the repo currently pins that ordering, so a future change to ImageLoaderCallbackBase (e.g. switching to TaskCreationOptions.RunContinuationsAsynchronously) or to MauiCustomTarget.post() can silently re-break or silently obsolete this workaround. Android MapTests are not compiled (Google Maps API key requirement), which is a legitimate limitation for a device test, but a non-device assertion is still available: a unit test over ImageLoaderCallbackBase/ImageSourceServiceResult asserting that the dispose action is not invoked on the callback's own stack would lock in the invariant this fix depends on. At minimum, record the manual repro steps and the verified before/after result in the PR description.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Acknowledged, and the manual repro plus the before/after numbers are in the PR description — device, image source type, gesture, and the instrumented counts for each run.

On the test itself: there is no seam I can reach. src/Core/maps/src/Properties/AssemblyInfo.cs exposes internals only to Microsoft.Maui.Controls.Core.UnitTests, which builds for $(_MauiDotNetTfm) and therefore never compiles MapHandler.Android.cs; and the Android MapTests are excluded for the Google Maps API key reason you mention. So neither the handler nor LoadPinIconAsync is reachable from a test project as things stand.

Your suggestion of pinning the ordering invariant in Core instead is the right shape and I agree it is the thing worth locking down — a change to ImageLoaderCallbackBase or MauiCustomTarget.post() silently obsoletes this workaround. That belongs in src/Core/tests/DeviceTests next to the image-source tests rather than in this PR, since it asserts Core behaviour rather than Maps behaviour. Happy to open it as a follow-up, or to fold it in here if you would rather it ship together.

{
// One handler for the whole type: the release below only needs to reach the next turn of the
// main loop, and allocating a Java Handler per image load would be pure waste.
static readonly AHandler s_mainHandler = new(Looper.MainLooper!);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[minor] Android Platform Specifics — new AHandler(Looper.MainLooper!) in a static field initializer moves construction into the MapHandler type initializer. If Looper.MainLooper is ever null on that path the ! suppression turns into an NRE inside the static constructor, which surfaces as a TypeInitializationException on every subsequent MapHandler member access rather than as a single failed icon release — a whole-map failure for a best-effort cleanup path. A lazily-initialized handler, or the existing Microsoft.Maui.ApplicationModel.MainThread dispatch helpers, would keep the failure scoped to the release itself. (The AHandler alias on line 23 is also inserted out of alphabetical order relative to the surrounding ABitmap/ABitmapDrawable aliases.)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed, and the alias is back in alphabetical order.

The handler is now created on first use with the same shape as MainThread.android.cs (static volatile field, re-created when the looper does not match), so a null MainLooper can no longer turn into a TypeInitializationException on every later MapHandler member access.

I did not take the MainThread helper route, though — MainThread.BeginInvokeOnMainThread runs the action inline when already on the main thread (MainThread.shared.cs:65), which is exactly the condition this fix exists to escape: the continuation is already on the main thread inside Glide's target callback, so an inline invoke would call Glide.clear() from the forbidden context again. The release specifically needs an unconditional post.

MauiBot

This comment was marked as outdated.

@MauiBot MauiBot added s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-fix-win AI found a better alternative fix than the PR s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review) and removed s/agent-review-in-progress AI review is currently running for this PR labels Aug 24, 2026

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

Could you please check the ai's suggestions?

@kevin68
kevin68 force-pushed the fix/android-map-cluster-pin-icon branch from a7e3fc7 to 188e37f Compare August 25, 2026 07:49
@kevin68

kevin68 commented Aug 25, 2026

Copy link
Copy Markdown
Contributor Author

Ran a before/after on device with a control build, so the numbers are comparative rather than absolute.

Method. Samsung SM-X230, Android 16 (API 36). Same device, same gesture sequence, same image both times: a 64x64 PNG written to FileSystem.CacheDirectory, so Pin.ImageSource is a rooted file path and resolves through Glide rather than the synchronous Context.GetDrawable branch a MauiImage name takes. Five un-clustered pins sharing that one image. Probes counted load attempts and MauiCustomTarget failures; the control is net11.0 at 78502a5, instrumented identically.

net11.0 (control) with this PR
Glide You can't start or clear loads 30 (over 15 load attempts) 0
Icons applied on the initial add none — 5 default red markers 5 custom icons
Icons after 6 recluster passes n/a still applied

Same pin positions in both runs, so the two screenshots differ only in the markers: red pins on the control, the custom icon with the fix.

One thing the control changed my mind about: the scope is wider than the title

I could not reproduce this as "the icon is lost when a pin leaves a cluster". On the control build the five pins come up as default red markers on the very first add, before any clustering has happened. Every one of the 15 load attempts threw and returned null.

That follows from the mechanism this PR already documents, and it is not specific to file paths either. PlatformInterop.loadImageFrom{File,Uri,Stream,Font}(Context, ...) all route through MauiCustomTarget (PlatformInterop.java:334), so on Android today no non-MauiImage Pin.ImageSource renders at all. The "intermittent" reading in the description looks like an artefact of a MarkerOptions that had been populated on some earlier path.

The part still unverified: AddClusterMarkerAsync calls the same LoadPinIconAsync, through _clusterIconCache. So a custom cluster image from a FontImageSource or UriImageSource should be failing the same way — and it fails silently, because icon ??= CreateClusterIcon(...) falls back to the default blue bubble with nothing visible to the user. I did not exercise that path, and nothing in the description or the review threads covers it. Worth one line of verification before merge, since it is the same fix.

Caveat on attribution. The measurements were taken with #37774 and #37770 also applied, because that is the state the three are intended to land in. The exception count and the icons rendering are attributable to this PR specifically — it is the only one that touches the Glide release path. Load counts are #37774's doing and I have kept them out of this table.

@MauiBot MauiBot removed the s/agent-review-in-progress AI review is currently running for this PR label Aug 25, 2026

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

Could you please check the latest suggestions?

Kévin Baumeyer and others added 4 commits August 26, 2026 14:13
A pin whose `Pin.ImageSource` is a rooted file path came back with the
default red marker after leaving a cluster, then corrected itself on a
later zoom.

That source loads through Glide, and `LoadPinIconAsync` released the
image result with a `using`. `ImageLoaderCallbackBase` completes its
`TaskCompletionSource` synchronously, so the continuation - and with it
the `Dispose` - can run inside Glide's own target callback, where
`MauiCustomTarget.clear()` calls `Glide.clear()` and Glide throws
`IllegalStateException: You can't start or clear loads in
RequestListener or Target callbacks`. Because the throw happened while
disposing, it replaced the `BitmapDescriptor` that had already been
built, `LoadPinIconAsync` returned null, and `AddPinAsync` created the
marker without an icon. A `Pin.ImageSource` backed by a MauiImage never
hit this: it resolves through the synchronous `Context.GetDrawable`
path. The failure looked intermittent because a `MarkerOptions` reused
from an earlier successful load masked it; a fresh handler - any change
to the `Pins` collection disconnects them - unmasked it.

Hand the release to the next turn of the main loop instead. By then the
Glide callback has unwound, so the clear succeeds: the icon survives
and the Glide entry is genuinely released rather than leaked, which is
what the TODO in `MauiCustomTarget` asks for. Guard the release anyway,
and log, so that a service whose dispose action fails for some other
reason still cannot discard an icon that was already built. The logger
is resolved before the post, because an exception raised from a looper
callback would take the process down rather than fault a task.

Releasing for real exposes something the leak used to mask. Glide takes
the bitmap back into its pool, while `DrawableToBitmap` handed the
descriptor whatever `ScaleBitmap` returned - and `CreateScaledBitmap`
returns the source instance unchanged when the image already fits,
which is precisely the 64x64 that `Pin.ImageSource` documents for
Android. Copy in that case, so a descriptor is never built over pooled
pixels. The sibling branch of the same method already guarded against
the identity return.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Three follow-ups from the second review pass.

Resolving a logger from a disposed scoped service provider throws, and the
catch in LoadPinIconAsync did it unguarded - the same failure ReleaseImageResult
was already hardened against, one line up. An exception escaping that catch
faults the task, so AddPinAsync never reaches Map.AddMarker and the pin is
missing rather than un-iconed; under FireAndForget it is silent. Both icon-path
catches now go through TryLogWarning.

The main-handler guard compared handler.Looper against Looper.MainLooper. That
is JNI peer reference equality on a process singleton the field is only ever
built from, so the branch can neither fire correctly nor be observed failing -
if peer identity were ever unstable it would silently allocate a handler per
icon load. Dropped to a plain null check.

Nothing on either side of the workaround said what it was working around.
MauiCustomTarget.post() and ImageLoaderCallbackBase now name the coupling, so
fixing either one does not leave this post as unexplained latency.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…t catch

Three of the five findings held up.

The Bitmap.Config comparison is gone rather than hardened. It compared JNI
peers of a Java enum, and peer identity is not something the binding
guarantees; a comparison that silently went false for a hardware bitmap would
have copied it as hardware, whose pixels BitmapDescriptorFactory cannot read -
landing on the default marker this PR exists to prevent. At 64x64 preserving a
narrower config saves a few KB, so the copy is now unconditionally Argb8888 and
the branch, the null check and the API-level guard all go with it.

The bitmap handed to FromBitmap is now recycled. Every DrawableToBitmap path
returns a bitmap this handler owns, so the release belongs at that single
point, which also closes the same pre-existing gap on the non-BitmapDrawable
branch. Verified on device that FromBitmap copies the pixels rather than
retaining the bitmap: custom pin icons still render, and survive six recluster
passes, with no recycled-bitmap errors.

ReleaseImageResult's catch no longer swallows in silence. Reaching it means the
Glide entry is leaked for the rest of the process, and a cleanup path that
fails invisibly is indistinguishable from one that works. It logs through
TryLogWarning, which cannot throw back into the catch it is called from.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The workaround moves out of the Maps handler and into MauiCustomTarget,
where the defect is: clear() is handed to the C# side from inside
onResourceReady, and Glide rejects a clear() issued from one of its own
target callbacks. Dropping the inline branch in post() makes disposal
safe for every Android image consumer instead of only this handler, and
removes the main-looper post, the cached handler field and the NOTE
comments that stood in for the fix.

The bitmap Recycle() goes with it. It rested on BitmapDescriptorFactory
.FromBitmap taking an eager pixel copy, which the Maps SDK does not
document; the descriptor outlives the call in the icon cache, so being
wrong means a recycled-bitmap crash on a later cluster pass. Releasing a
64x64 buffer a GC earlier does not buy that risk. It also sat inside the
try between building the descriptor and returning it, so a throw there
discarded an icon that was already built - the same rule the release path
follows.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@kevin68
kevin68 force-pushed the fix/android-map-cluster-pin-icon branch from 5b2ecdc to db0386f Compare August 26, 2026 12:15
@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Aug 26, 2026

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Expert Review — 3 findings

See inline comments for details.

// onResourceReady, and Glide rejects a clear() issued from one of its own target callbacks
// (SingleRequest.assertNotCallingCallbacks). A consumer disposing the result in its await
// continuation is still on that callback stack, so running here would throw.
new Handler(Looper.getMainLooper()).post(() -> {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[major] Null Safety and Defensive Coding — The body of this posted Runnable is unguarded, so any throw from Glide.with(context).clear(this) now surfaces on the main looper as an unhandled exception (process crash) instead of on the caller's stack.

Before this change, the main-thread case ran clear() inline, so a throw propagated back into the C# disposer and was caught there. This PR's companion guard in LoadPinIconAsync (try { result?.Dispose(); } catch { ... }, MapHandler.Android.cs:1032) can no longer observe anything raised here — post() returns immediately and the work runs on a later loop with no exception scope. Concrete scenario: the hosting Activity reports alive at the isContextDestroyed check but Glide.with(context) still rejects the retriever lookup (detached/finishing fragment host, non-Activity ContextWrapper chain) — previously logged and swallowed, now terminates the process during a routine image-result dispose.

Suggested: wrap the runnable body in try { ... } catch (Throwable t) { logger.v("clear() failed: " + resourceLogIdentifier); } so the deferred clear fails as quietly as the inline path did. Secondary (minor): hoist a private static final Handler MAIN_HANDLER = new Handler(Looper.getMainLooper()); — every dispose now allocates a Handler, whereas the removed fast path allocated none on the main thread (the common case).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed — and this one was mine to fix, it is a regression the last round introduced.

You traced it correctly: with the inline path, a throw from Glide.with(context).clear(this) came back up through dispose.Run() into the C# disposer, where the guarded result?.Dispose() logged and swallowed it. Posting the body moved it onto a later loop turn with no exception scope, so the same throw now reaches the looper unhandled. Trading a logged failure for a process kill during a routine dispose is not a trade, and your Glide.with() retriever-lookup scenario is a real way to get there — the isContextDestroyed check answers a different question than the retriever does.

The runnable body is wrapped in try/catch (Throwable) now, logging at the same verbose level as the context-destroyed skip just above it.

Secondary point taken too: MAIN_HANDLER is a private static final field, so a dispose allocates nothing. That is strictly better than what the fast path did, since the fast path only avoided the allocation on the main thread.

// binding guarantees - a comparison that silently went false for a hardware bitmap
// would copy it as hardware, and BitmapDescriptorFactory cannot read those pixels
// back, which lands on the default marker this PR exists to prevent.
return source.Copy(ABitmap.Config.Argb8888!, false);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[major] Regression Prevention and Test Coverage — Both halves of this fix ship without a regression test, and both are testable with existing infrastructure.

  1. The Java change is verifiable from src/Core/tests/DeviceTests/Services/ImageSource/ImageSourceServiceTests.Android.cs: ImageLoaderCallbackBase completes its TaskCompletionSource without RunContinuationsAsynchronously, so an await GetPlatformImageAsync(...) continuation resumes inline on Glide's onResourceReady stack — disposing the result there is exactly the SingleRequest.assertNotCallingCallbacks path being fixed. A test that awaits the result and disposes it in the continuation (no Task.Yield) fails before the MauiCustomTarget.clear() change and passes after, mirroring the existing LoadDrawableAsyncReturnsWithSameImageAndDoesNotHang precedent.

  2. This DrawableToBitmap branch only triggers when the source bitmap's largest dimension is exactly 64 (ScaleBitmap computes ratio == 1, and Bitmap.createScaledBitmap hands an immutable source straight back) — a narrow window that will silently regress if ScaleBitmap's target size or ratio math is later changed. A test asserting DrawableToBitmap never returns the drawable's own bitmap instance for a 64×N source pins the invariant.

Without either test, the next edit to ScaleBitmap or to the callback threading model re-opens "custom pin icon falls back to the default marker" with no signal.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Test added for (1). Pushing back on (2).

(1) — you are right, and the reason it is right now is that the fix moved. My "no seam" answer in the earlier rounds was about the Maps assembly, whose InternalsVisibleTo names only Microsoft.Maui.Controls.Core.UnitTests. That argument does not survive the fix landing in MauiCustomTarget, because Microsoft.Maui.Core.DeviceTests does have the access. Fair catch.

DisposingTheResultFromInsideTheLoadCallbackDoesNotThrow in ImageSourceServiceTests.Android.cs. One deliberate difference from the shape you sketched: rather than awaiting GetPlatformImageAsync and disposing in the continuation, it drives PlatformInterop.LoadImageFromFile with a callback that runs the dispose Runnable from inside onComplete. That is Glide's onResourceReady stack, deterministically, with nothing resting on whether the continuation happens to inline — which depends on the ambient SynchronizationContext and would make the test pass vacuously the day that changes, rather than fail. It also asserts the load succeeded, so a load that quietly failed cannot pass as "dispose did not throw".

(2) — this half still hits the wall the first half no longer does. DrawableToBitmap is a private static in MapHandler.Android.cs; the Maps assembly's only IVT target never compiles that file, and Core.DeviceTests has neither a ProjectReference to Maps nor an IVT from it. Wiring that up is new test infrastructure, not a test, and I would rather not smuggle it into a bug fix. Happy to open it separately if you want the invariant pinned.

One thing I will not overstate: I have not run the new test. No Android device is attached to my machine right now, so CI is its first execution. The behaviour it asserts is the one I measured on device in the earlier rounds (numbers and method), but that was through the Maps path, not through this test.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Correcting my own caveat from earlier in this thread: I said the test had never been executed and that CI would be its first run. A device freed up, so that is no longer true — here are the numbers.

Samsung SM-X230, Android 16. Three full Core.DeviceTests runs, ~3040 tests each.

build total failures DisposingTheResultFromInsideTheLoadCallbackDoesNotThrow
pristine base c127c3f350 29 not present
this PR 29 Pass
this PR with the MauiCustomTarget fix reverted 30 Fail

The only delta between the red and green runs is the new test, and it fails on the exact defect:

Assert.Null() Failure: Value is not null
Actual: Java.Lang.IllegalStateException: You can't start or clear loads in RequestListener
or Target callbacks. ... consider posting your into() or clear() calls to the main thread
using a Handler instead.
   at Java.Lang.IRunnableInvoker.Run()
   at ...ImageSourceServiceTests.DisposeInsideCallbackStub.OnComplete(...)

So it is a real regression test rather than one that passes vacuously — which was my worry with the await-continuation shape, and the reason I drove the callback directly instead.

One thing worth flagging, since it is in the same file as the new test. ReleasingImageSourceReturnsDifferentBitmap fails in the green run. It asserts that Dispose() released Glide's strong refs, so deferring clear() is exactly what could break it, and I did not want to hand-wave it. It fails identically on the pristine base: the 29 failures are the same tests on both sides (27 × Native View Bounding Box is not empty, SystemBarAppearanceDoesNotOverwriteDeveloperAppearance, and this one). Pre-existing on this device, not caused by the PR — but it is a real red test in main on Android and someone should probably look at it separately.

End-to-end on the Maps side, which is what the earlier rounds measured and what the using var bitmap change had never been through. A Pin.ImageSource on a rooted file path — the only route that reaches Glide/MauiCustomTarget; a MauiImage name like dotnet_bot.png resolves to a drawable resource and never exercises this code — then 20 recluster passes driven from code:

counter value
recluster passes 20
You can't start or clear loads 0
trying to use a recycled bitmap 0
Failed to load / release custom pin icon 0
FATAL / AndroidRuntime 0

Custom icons render on first add and still render after all 20 passes, including where the descriptor is served from _iconCache rather than rebuilt — which is the path the removed Recycle() would have broken and the one Dispose() has to stay correct on.

if (bitmap is null)
return null;

return BitmapDescriptorFactory.FromBitmap(bitmap);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[moderate] Memory Leak Prevention / Performance-Critical Path — The bitmap handed to BitmapDescriptorFactory.FromBitmap is never released on any path, and this PR adds a new allocation to the one branch that previously had none.

FromBitmap copies the pixels into the descriptor, so the local bitmap is dead the moment this line returns; nothing disposes it. Previously an already-64px source produced no new bitmap at all (ScaleBitmap returned the source); it now always allocates a 64×64 ARGB_8888 copy (~16KB native + a JNI peer) that lingers until GC. With clustering, GetIconAsync can drive many of these per recluster pass for sources that GetIconCacheKey cannot key (which bypass _iconCache and reload every time).

Suggested: using var bitmap = DrawableToBitmap(drawable); — or bitmap.Dispose() right after this call — so the peer is released deterministically once the descriptor owns the pixels. This is the correct place to fix it for all three DrawableToBitmap branches, not just the new copy path.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed, with one substitution: using var bitmap, so Dispose() rather than Recycle().

The distinction matters given the round you are replying to. I removed a Recycle() on this exact line last round because it depended on FromBitmap taking an eager pixel copy — undocumented, and wrong would mean a recycled-bitmap crash when _iconCache re-applies the descriptor on a later pass. Dispose() does not carry that: it drops the JNI peer and leaves the pixels to the Java GC, so if FromBitmap retained the source rather than copying it, the Java side still holds the reference and nothing is pulled out from under the descriptor. Correct either way, which the recycle was not.

You are also right that this is the place to fix it for all three paths rather than only the copy branch. The else path already disposed its intermediate (if (scaled != bitmap) bitmap.Dispose()); what leaked on every path was the bitmap actually returned, and that is what the using covers.

Worth noting the quantity is smaller than the framing: GetIconAsync reloads per pass only for sources GetIconCacheKey cannot key stably — streams, and URI sources that opted out of caching. Keyed sources decode once. Still a leak, still right to close.

MauiBot

This comment was marked as outdated.

@MauiBot MauiBot removed the s/agent-review-in-progress AI review is currently running for this PR label Aug 26, 2026

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

Could you please check the ai's suggestions?

…a test

Posting clear() took its body out of the disposer's stack, so a throw from
Glide.with(context).clear(this) would have reached the looper unhandled -
a crash where the inline path was logged and swallowed by the C# disposer.
The runnable body is guarded now, and the Handler is a process singleton so
a dispose no longer allocates one.

The load callback is a seam the Maps assembly never offered: the fix moved
into Core, so Core.DeviceTests can reach it. The test drives PlatformInterop
.LoadImageFromFile with a callback that runs the dispose Runnable from
inside onComplete - Glide's own callback stack, with no reliance on how an
await continuation happens to be scheduled - and asserts the load succeeded
so a silent load failure cannot pass as "dispose did not throw".

The icon bitmap is disposed once the descriptor owns the pixels, which
closes the leak on all three DrawableToBitmap paths rather than only the
copy this PR added. Disposed, not recycled: dropping the JNI peer leaves
the pixels to the Java GC, so it stays correct even if FromBitmap retains
the source instead of copying it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Aug 27, 2026

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Expert Review — 3 findings

See inline comments for details.

Glide
.with(context)
.clear(this);
} catch (Throwable t) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[major] Android Platform / Exception Handling — catch (Throwable t) swallows the failure and never records t: the only output is logger.v("clear() failed: " + resourceLogIdentifier), which (a) drops the exception type/stack entirely and (b) is gated on isVerboseLoggable, so it emits nothing in a normal build. Concrete scenario: Glide.with(context) throws for a context that is not yet reported destroyed (e.g. an Activity past onDestroy where isContextDestroyed returns false, or a non-Activity context whose RequestManager cannot be resolved). The posted runnable then returns silently, Glide.clear(this) is never reached, and the active Glide resource/cache entry stays retained for the life of the process with zero diagnostics — precisely the leak this clear() exists to prevent. This is worse than the pre-change behavior, where the throw propagated to the C# disposer that logged it. Catching Throwable also absorbs Errors such as OutOfMemoryError/StackOverflowError that should not be converted into a silent no-op. Narrow the catch to RuntimeException and include the throwable in the message (PlatformLogger only exposes v(String), so append t / t.toString(), or log at warn level via android.util.Log per the native-logging convention).


// Asserted so a load that quietly failed cannot pass this as "dispose did not throw".
Assert.True(loaded);
Assert.Null(disposeError);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[major] Regression Prevention / Test Coverage — This assertion cannot discriminate between a working fix and a permanently broken one. After the change, clear() does nothing but MAIN_HANDLER.post(...) and returns, so dispose.Run() is unconditionally non-throwing; disposeError is null by construction. Combined with the catch (Throwable) swallow inside the posted runnable (MauiCustomTarget.java:97), the deferred body could throw on every single invocation — or the runnable could never be posted at all — and this test would still be green. The test therefore locks in "dispose does not throw" but provides no coverage for the behavior that actually matters: that the resource is still released via the deferred path. Add an assertion that the deferred clear() completed successfully, e.g. after awaiting callback.Result, pump/yield to the main looper and then reuse the existing release-verification pattern (TryCollectFile, as in ReleasingImageSourceReturnsDifferentBitmap) to prove the Glide entry was actually cleared.

// reads it once the descriptor exists. Disposed rather than recycled: this drops
// the JNI peer and leaves the pixels to the Java GC, which stays correct even if
// FromBitmap retained the source rather than copying it. Recycling would not.
using var bitmap = DrawableToBitmap(drawable);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[moderate] Regression Prevention — The primary user-visible fix in this PR is the pin-icon bitmap ownership change (DrawableToBitmap now copies when ScaleBitmap hands the source back, and result disposal moved to a guarded finally so a failing release can no longer swap the built descriptor for the default marker), but no test covers it. The only test added exercises the Glide clear() deferral in ImageSourceServiceTests.Android.cs, which does not touch this code path at all. The exact regression being fixed here — an already-64x64 immutable BitmapDrawable whose pixels are owned by the image result, producing a descriptor over released pixels and falling back to the default marker — is silent at runtime and will regress undetected. Add a regression test asserting that DrawableToBitmap returns a bitmap not reference-equal to bitmapDrawable.Bitmap for an already-64x64 source, and that a BitmapDescriptor is still produced after the backing IImageSourceServiceResult has been disposed.

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

AI Review Summary

@kevin68 — new AI review results are available based on commit 54d8f7a.

Gate Passed Confidence Unknown Platform Android


🗂️ Review Sessions — click to expand
🚦 Gate — Test Before & After Fix

Gate Result: ✅ PASSED

Platform: ANDROID · Base: net11.0 · Merge base: a252136a

Test Without Fix (expect FAIL) With Fix (expect PASS)
📱 ImageSourceServiceTests (DisposingTheResultFromInsideTheLoadCallbackDoesNotThrow) ImageSourceServiceTests ✅ FAIL — 467s ✅ PASS — 311s
🔴 Without fix — 📱 ImageSourceServiceTests (DisposingTheResultFromInsideTheLoadCallbackDoesNotThrow): FAIL ✅ · 467s

(no coded error found; showing last 1200 chars)

"totalMemoryBytes": 8322990080
          },
          "target": {
            "kind": "emulator",
            "name": "sdk_gphone_x86_64",
            "identifier": "emulator-5554",
            "operatingSystem": "Android",
            "operatingSystemVersion": "11",
            "apiLevel": 30,
            "architecture": "x86_64",
            "supportedArchitectures": [
              "x86_64",
              "x86",
              "arm64-v8a",
              "armeabi-v7a",
              "armeabi"
            ],
            "manufacturer": "Google",
            "model": "sdk_gphone_x86_64",
            "productName": "sdk_gphone_x86_64",
            "buildFingerprint": "google/sdk_gphone_x86_64/generic_x86_64_arm64:11/RSR1.201211.001/7027799:user/release-keys",
            "cpuModel": "0",
            "cpuMaxFrequencyHertz": 2000,
            "totalMemoryBytes": 2077544448
          }
        }
      }
      <<XHARNESS_RESULT_END>>
info: Attempting to remove apk 'com.microsoft.maui.core.devicetests'..
info: Successfully uninstalled com.microsoft.maui.core.devicetests
XHarness exit code: 1 (TESTS_FAILED)
  Passed: 0
  Failed: 1
  Skipped: 0
  Total: 1
  Tests completed with exit code: 1
🟢 With fix — 📱 ImageSourceServiceTests (DisposingTheResultFromInsideTheLoadCallbackDoesNotThrow): PASS ✅ · 311s

(no coded error found; showing last 1200 chars)

591000,
            "totalMemoryBytes": 8322990080
          },
          "target": {
            "kind": "emulator",
            "name": "sdk_gphone_x86_64",
            "identifier": "emulator-5554",
            "operatingSystem": "Android",
            "operatingSystemVersion": "11",
            "apiLevel": 30,
            "architecture": "x86_64",
            "supportedArchitectures": [
              "x86_64",
              "x86",
              "arm64-v8a",
              "armeabi-v7a",
              "armeabi"
            ],
            "manufacturer": "Google",
            "model": "sdk_gphone_x86_64",
            "productName": "sdk_gphone_x86_64",
            "buildFingerprint": "google/sdk_gphone_x86_64/generic_x86_64_arm64:11/RSR1.201211.001/7027799:user/release-keys",
            "cpuModel": "0",
            "cpuMaxFrequencyHertz": 2000,
            "totalMemoryBytes": 2077544448
          }
        }
      }
      <<XHARNESS_RESULT_END>>
info: Attempting to remove apk 'com.microsoft.maui.core.devicetests'..
info: Successfully uninstalled com.microsoft.maui.core.devicetests
XHarness exit code: 0
  Passed: 1
  Failed: 0
  Skipped: 0
  Total: 1
  Tests completed successfully
📁 Fix files reverted (2 files)
  • src/Core/AndroidNative/maui/src/main/java/com/microsoft/maui/glide/MauiCustomTarget.java
  • src/Core/maps/src/Handlers/Map/MapHandler.Android.cs

📋 Pre-Flight — Context & Validation

Issue: #37767 - [Android] Map: custom pin icon lost when a pin leaves a cluster (rooted file path / Glide)
PR: #37769 - [Android] Map: Keep the custom pin icon when a pin leaves a cluster
Base: net11.0
Platform: Android
Files Changed: 2 implementation, 1 device test

Problem

A clustered Android map pin whose ImageSource is a rooted file path can return with the default marker after leaving a cluster. The rooted path loads through Glide. ImageLoaderCallbackBase completes synchronously, so LoadPinIconAsync can resume and dispose the image result while still inside Glide's onResourceReady callback. MauiCustomTarget.clear() then calls Glide.clear(), which throws IllegalStateException; that disposal exception replaces the already-created BitmapDescriptor, and the map falls back to a marker without the custom icon.

Existing PR Fix

  • MauiCustomTarget.java always posts Glide.clear(this) to the main looper instead of running inline on the main thread, and catches failures in the posted callback.
  • MapHandler.Android.cs explicitly disposes the image result in finally, shields that disposal from replacing a successfully created descriptor, owns/disposes the converted bitmap, and copies identity-scaled source bitmaps before releasing the image result.
  • ImageSourceServiceTests.Android.cs adds a device test that disposes the result from inside the Glide load callback.
  • The PR narrative says the global MauiCustomTarget.post() change was out of scope, but the materialized diff does apply that global always-post behavior; candidates must compare against the code, not that stale sentence.

Changed Files

  • Implementation: src/Core/AndroidNative/maui/src/main/java/com/microsoft/maui/glide/MauiCustomTarget.java
  • Implementation: src/Core/maps/src/Handlers/Map/MapHandler.Android.cs
  • Device test: src/Core/tests/DeviceTests/Services/ImageSource/ImageSourceServiceTests.Android.cs

Validation Contract

Primary test:
pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Core -Platform android -TestFilter "ImageSourceServiceTests"

The gate already proved the new test fails without the PR fix and passes with it; do not rerun gate verification. The regression cross-reference was clean and supplied no additional mandatory regression tests. Do not run a full suite.

Gate Result

✅ PASSED — DisposingTheResultFromInsideTheLoadCallbackDoesNotThrow failed without the fix and passed with the fix.

Constraints for Alternatives

  • Modify only files permitted by .github/.baseline-state.json after EstablishBrokenBaseline.ps1 runs.
  • Produce a mechanism-level alternative to the PR's unconditional main-looper post.
  • Preserve safe image-result release and avoid letting cleanup errors discard a descriptor already created.
  • One implementation/test pass, with at most one focused correction and retest.

Expert Review

Deferred to STEP 5b as required. No separate expert-review agent was launched in this phase.


🔬 Code Review — Deep Analysis

Expert PR Evaluation

Initial verdict: NEEDS_CHANGES

The submitted fix correctly breaks the re-entrant onResourceReady -> continuation -> Dispose -> Glide.clear call chain and protects an already-created BitmapDescriptor from disposal failures. The bitmap-ownership change is also directionally sound: an identity result from CreateScaledBitmap is copied before the image-service result is released.

Actionable findings

  1. Major — deferred cleanup failures are silently swallowed. MauiCustomTarget.clear() catches Throwable, drops the exception, and logs only a message at verbose level. A failure in the posted body can therefore retain the Glide resource with no normal-build diagnostic, while also suppressing fatal Error subclasses.
  2. Major — the new device test is non-discriminating for deferred cleanup. It proves only that dispose.Run() returns after enqueueing. The posted body could fail or never clear the target and the test would still pass; it needs to verify that the Glide entry is actually released.
  3. Moderate — the map bitmap-ownership behavior has no direct regression test. The added test never exercises LoadPinIconAsync or DrawableToBitmap, so the already-sized immutable-bitmap copy and descriptor lifetime remain unprotected.

The trusted Gate passed, but it covers only the callback-stack exception. These findings should be addressed together in a single candidate refinement rather than by weakening the resource release.


🛠️ Try-Fix — Analysis & Comparison

Fix Candidates

# Model / Source Approach Test Result Files Changed Notes
1 claude-opus-5 / try-fix Make ImageLoaderCallbackBase<T> use RunContinuationsAsynchronously, preventing the await continuation and disposal from running on Glide's callback stack. ⚠️ BLOCKED — primary test not run None Baseline script rejected the pre-existing harness-dirty tree; the proposed file is also outside the baseline allow-list.
2 gpt-5.6-sol / try-fix Post successful callback.onComplete delivery to a later main-looper turn, leaving cleanup synchronous after Glide's callback unwinds. ⚠️ BLOCKED — primary test not run None Baseline script rejected the same pre-existing harness-dirty tree; no baseline allow-list was created.
PR PR #37769 Unconditionally post MauiCustomTarget.clear() to the main looper, harden result disposal, and copy source-owned identity-scaled bitmaps. ✅ PASSED (Gate) 2 implementation files Original PR; gate test fails without and passes with fix.

Candidate 1 Narrative

Approach: Change ImageLoaderCallbackBase<T>'s TaskCompletionSource to use TaskCreationOptions.RunContinuationsAsynchronously.

Prior approach avoided: The PR defers and hardens clear() itself with an unconditional main-looper post and broad Throwable catch. Candidate 1 instead targets the synchronous continuation that causes consumer disposal to execute re-entrantly.

Mechanism-level difference: The failure chain is onResourceReady → onComplete → SetResult → inline continuation → Dispose → Glide.clear. The PR cuts the final link by delaying clear; Candidate 1 would cut the middle link by queuing the continuation, allowing Glide's callback stack to unwind before any consumer code or disposal executes.

Result: ⚠️ BLOCKED. EstablishBrokenBaseline.ps1 refused to create baseline state because numerous pre-existing tracked harness files are modified. No source file was edited and the exact primary device test was not run. Independently, the proposed src/Core/src/ImageSources/Android/ImageLoaderCallback.cs is outside the PR-derived RevertedFiles boundary and therefore read-only under the try-fix contract.

Diff: Empty.

Self-review: 0 findings; empty final diff.

Failure analysis: There is no contract-compliant way to clean or bypass the harness changes, and no baseline state means no edit allow-list. Retrying the same approach would block identically. Candidate 2 must avoid RunContinuationsAsynchronously and must not revisit Candidate 1.

Candidate 2 Narrative

Approach: In MauiCustomTarget.onResourceReady, post successful callback.onComplete delivery to the main looper, after Glide exits its target callback, while retaining the baseline conditional/inline clear() behavior.

Prior approaches avoided: The PR defers the clear operation itself and broadly catches failures in that asynchronous cleanup. Candidate 1 instead makes C# task continuations asynchronous. Candidate 2 changes neither cleanup scheduling nor C# continuation scheduling; it delays delivery of the successful image result.

Mechanism-level difference: The PR permits onComplete, synchronous continuation, and disposal to remain nested inside Glide and delays only the final clear. Candidate 2 moves the start of that consumer chain outside SingleRequest.onResourceReady; synchronous disposal may then call the baseline clear helper inline on a later looper turn, when Glide's callback assertion is inactive.

Result: ⚠️ BLOCKED. EstablishBrokenBaseline.ps1 again rejected 49 pre-existing dirty tracked harness paths and created no .github/.baseline-state.json or RevertedFiles allow-list. No source file was edited, and the exact primary device test was not run because it would only exercise the unchanged PR state.

Diff: Empty.

Self-review: 0 findings; empty final diff. The design was considered against Android, async/threading, lifecycle, memory, and image-handling concerns, but has no empirical validation.

Failure analysis: This is the same environmental baseline blocker, not evidence for or against Candidate 2. The exact restore command completed with the accepted no-state/no-edit result, Restored False.

Cross-Pollination

Skipped by execution contract.

Exhausted: Yes — the bounded two-candidate limit was reached; neither candidate could be implemented or tested.
Selected Fix: PR #37769's submitted fix — it is the only empirically validated option because Gate passed. Candidate 1 and Candidate 2 remain unvalidated design alternatives and cannot outrank the passing PR.


📝 PR Finalize — Recommended Title & Description

Assessment: ✏️ Recommend updating — the title is precise, but the description says the global MauiCustomTarget always-post change is out of scope even though it is present in the submitted PR HEAD, and it inaccurately describes where deferred-clear logging occurs.

Recommended title

[Android] Map: Keep the custom pin icon when a pin leaves a cluster

Recommended description

Fixes #37767

### Description of Change

On Android, a `Pin` whose `ImageSource` is a **rooted file path** came back with the default red marker after leaving a cluster, then corrected itself on a later zoom.

That source loads through Glide, and `LoadPinIconAsync` released the image result with a `using`. `ImageLoaderCallbackBase` completes its `TaskCompletionSource` synchronously, so the continuation - and with it the `Dispose` - can run inside Glide's own target callback, where `MauiCustomTarget.clear()` calls `Glide.clear()` and Glide throws `IllegalStateException: You can't start or clear loads in RequestListener or Target callbacks`. Because the throw happened while disposing, it replaced the `BitmapDescriptor` that had already been built: `LoadPinIconAsync` returned `null` and `AddPinAsync` created the marker without an icon.

A `Pin.ImageSource` backed by a MauiImage never hit this - it resolves through the synchronous `Context.GetDrawable` path. The failure looked intermittent because a `MarkerOptions` reused from an earlier successful load masked it; a fresh handler (any change to the `Pins` collection disconnects them) unmasked it.

**Fix:** `MauiCustomTarget.clear()` now always posts `Glide.clear(this)` to the next turn of the main looper instead of running inline when already on the main thread. By then the Glide callback has unwound, so the clear succeeds and the Glide entry is genuinely released instead of leaked, which is what the existing `MauiCustomTarget` TODO asks for. Because failures now occur outside the caller's stack, the posted runnable catches them itself and emits a verbose diagnostic when enabled.

`LoadPinIconAsync` also releases the image result from a guarded `finally`. A service whose dispose action fails cannot replace a `BitmapDescriptor` that was already built, and logger-resolution failures cannot prevent `AddPinAsync` from creating the marker.

**Releasing for real exposes something the leak used to mask.** `Bitmap.createScaledBitmap` hands an *immutable* source straight back when the image already fits - the 64x64 that `Pin.ImageSource` documents for Android - so the descriptor would be built over pixels the image result owns, and releasing that result lets them go. Hardware bitmaps, which Glide emits on API 26+, are the common immutable case here. This PR copies in that branch, retargeting `Config.Hardware` to `Argb8888` since hardware pixels cannot be read back, and never falls back to the source: a failed copy means the default marker rather than a descriptor over foreign pixels. The sibling branch of the same method already guarded against the identity return (`if (scaled != bitmap) bitmap.Dispose();`), so this behavior of the helper was known - the `BitmapDrawable` branch just never had to account for it while nothing released.

The converted bitmap is disposed after `BitmapDescriptorFactory.FromBitmap` creates the descriptor. This drops the JNI peer without calling `Bitmap.recycle()`, so cached descriptors are not made to reference explicitly recycled pixels.

To be explicit about what fixes what: **the deferred release alone restores the icon** - verified on device before the copy existed. The copy is defensive, and belongs with the release because releasing for real is what makes a source-owned bitmap reachable by the descriptor at all.

This PR applies the scheduling fix in `MauiCustomTarget` rather than only in the Map handler. That makes context-based Glide result disposal safe for every C# consumer whose await continuation resumes inside `onResourceReady`; it does not alter `MauiCustomViewTarget` result delivery.

The redundant-reload half of this work was split into its own PR to keep the bug fix and the caching behavior separately reviewable.

### Verification

Added the Android Core device test `ImageSourceServiceTests.DisposingTheResultFromInsideTheLoadCallbackDoesNotThrow`, which disposes the result from inside Glide's load callback. The trusted gate verified that the test fails without the fix and passes with it.

Physical device (Samsung SM-X230, Android 15), clustering gallery using pins whose icon is a PNG written to `FileSystem.CacheDirectory`, handler instrumented at each boundary.

Three zoom-in/zoom-out cycles over 25 clustered custom pins:

| | before | after |
|---|---|---|
| Glide `IllegalStateException` | 29 | 0 |
| icon loads discarded | 29 | 0 |
| markers created without their icon | 0 (masked by a surviving `MarkerOptions`) | 0 |
| recycled-bitmap / canvas errors | - | 0 |

Re-run after the split, both alone and merged with the reload PR: no Glide asserts, no recycled-bitmap errors, no crashes, every de-clustered pin keeps its icon.

### Issues Fixed

Fixes #37767

🏁 Report — Final Recommendation

⚠️ Final Recommendation: REQUEST CHANGES

Winner: pr-plus-reviewer.

The submitted PR has the only trusted Gate-proven base mechanism, and the consolidated reviewer refinement preserves it while addressing the expert review's two major weaknesses: silent deferred cleanup failure and a non-discriminating release test. It also adds direct coverage for the identity-scaled bitmap ownership branch. Because these improvements are not in the submitted PR HEAD, the PR still needs changes.

Candidate comparison

Rank Candidate Evidence Assessment
1 pr-plus-reviewer Required Core build succeeded; strengthened image-source regression passed; overall command failed only on unrelated SwitchHandlerTests.ThumbColorUpdatesCorrectly after the runner ignored the requested class filter. Map ownership test compiled/runtime validation remains unconfirmed because no second validation was run after the failure. Best mechanism and coverage. Narrows the Java catch, records cleanup/post failures, proves deferred release, and adds a discriminating ownership test without changing the PR's successful fix strategy.
2 pr Trusted Gate passed: the original regression fails without the fix and passes with it. Fixes the reported callback-stack failure, but expert review found that catch (Throwable) suppresses fatal errors and normally hides cleanup failures; the added test proves only enqueueing, and the bitmap ownership branch lacks direct coverage.
3 try-fix-1 Blocked; no diff and primary test not run. RunContinuationsAsynchronously is a plausible broader fix to continuation re-entrancy, but it was neither implemented nor validated and targets a file outside the STEP 5a allow-list.
4 try-fix-2 Blocked; no diff and primary test not run. Deferring successful callback delivery is mechanically distinct, but it was neither implemented nor validated and changes result-delivery timing globally.

No candidate failed the targeted regression: the raw PR Gate passed, and the strengthened pr-plus-reviewer regression passed. The pr-plus-reviewer command's nonzero exit came from an unrelated Switch rendering assertion in the unexpectedly unfiltered assembly run, so it is recorded as validation uncertainty rather than a regression failure.

Expert and prior-review reconciliation

  • Prior immediate-Recycle() concerns are obsolete at current HEAD: the PR now disposes only the JNI peer after descriptor creation rather than recycling pixels.
  • The prior unguarded-post crash was addressed at current HEAD, but the replacement broad Throwable swallow created the current expert finding; pr-plus-reviewer narrows and diagnoses that path.
  • The prior missing-test finding is only partially addressed in the raw PR. pr-plus-reviewer makes the Glide test release-sensitive and adds the missing identity-copy test.
  • Required-check status could not be collected with gh because the CLI is unauthenticated. The supplied trusted Gate result is the authoritative regression evidence for this comparison.

Comparative confidence: medium. The Android-specific mechanism is well traced and the relevant strengthened regression passed, but the new map ownership test was not executed and required-check status was unavailable.


📱 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 — reviewer changes required

The reviewer-enhanced candidate identified changes that are not yet in the submitted PR.

Why: The reviewer refinement preserves the Gate-proven PR mechanism while narrowing and diagnosing deferred cleanup failures and adding discriminating release and bitmap-ownership coverage. Its strengthened image-source regression passed; the overall run failed only on an unrelated Switch rendering test after filtering was ignored, leaving the added map test unexecuted.

Address the actionable findings in this review before merging.

@MauiBot MauiBot added s/agent-gate-passed AI verified tests catch the bug (fail without fix, pass with fix) and removed s/agent-review-in-progress AI review is currently running for this PR labels Aug 27, 2026
@kubaflo
kubaflo merged commit c6a05f2 into dotnet:net11.0 Aug 27, 2026
10 of 11 checks passed
@github-actions github-actions Bot added this to the .NET 11.0-preview7 milestone Aug 27, 2026
@github-actions github-actions Bot locked and limited conversation to collaborators Oct 9, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

area-controls-map Map / Maps community ✨ Community Contribution platform/android s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-fix-win AI found a better alternative fix than the PR s/agent-gate-passed AI verified tests catch the bug (fail without fix, pass with fix) s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants