Skip to content

[leak scan] Fix handler collection retention memory leak - #38768

Merged
kubaflo merged 2 commits into
dotnet:inflight/currentfrom
Shalini-Ashokan:fix/38671-handler-collection-leak
Sep 24, 2026
Merged

kubaflo merged 2 commits into
dotnet:inflight/currentfrom
Shalini-Ashokan:fix/38671-handler-collection-leak

Conversation

@Shalini-Ashokan

Copy link
Copy Markdown
Contributor

Note

Are you waiting for the changes in this PR to be merged?
It would be very helpful if you could test the resulting artifacts from this PR and let us know in a comment if this change resolves your issue. Thank you!

Issue Details

AddHandler can cause IMauiHandlersCollection objects and their registered services to stay in memory, resulting in a memory leak.

Root Cause

A static ConcurrentDictionary keeps the handler collection as a strong reference, so it cannot be garbage-collected.

Description of Change

Replaced ConcurrentDictionary with ConditionalWeakTable in RegisteredHandlerServiceTypeSet to ensure that IMauiHandlersCollection instances can be garbage collected when no longer referenced, reducing the risk of memory leaks.

Validated the behavior in the following platforms

  • Android
  • Windows
  • iOS
  • Mac

Issues Fixed

Fixes #38671

Output ScreenShot

Before After
image image

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

Or

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

@dotnet-policy-service dotnet-policy-service Bot added the community ✨ Community Contribution label Sep 22, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Hey there @@Shalini-Ashokan! 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 dotnet-policy-service Bot added the partner/syncfusion Issues / PR's with Syncfusion collaboration label Sep 22, 2026
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).
There may be pipelines that require an authorized user to comment /azp run to run.

@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 Sep 22, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Note

🔍 /review started

AzDO build 15413657 is running for android.

The s/agent-review-in-progress label stays on this PR while the run is active. The final recommendation and outcome labels are posted only after Gate, expert review, and Deep UI tests finish.

@kubaflo

This comment has been minimized.

@github-actions

Copy link
Copy Markdown
Contributor

Tests Failure Analysis

@Shalini-Ashokan — test-failure analysis for commit 162c210.

Scope CI failures Commit 162c210


🧪 CI Analysis — click to expand
📊 maui-pr

No failures found.


🧪 maui-pr-devicetests

No results available.


🧪 maui-pr-uitests

No results available.


🧭 Follow-up — actions and refresh

Next action: Comment /azp run maui-pr-devicetests and /azp run maui-pr-uitests to collect current results for the missing pipelines.

Maintainers: comment /review tests to refresh this report.

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-gate-passed AI verified tests catch the bug (fail without fix, pass with fix) s/agent-fix-pr-picked AI could not beat the PR fix - PR is the best among all candidates 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 Sep 22, 2026
@kubaflo

kubaflo commented Sep 22, 2026

Copy link
Copy Markdown
Contributor

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).

Copilot AI lite review requested due to automatic review settings September 24, 2026 09:46

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot review overview

🔵 Needs a closer look

Weak-reference lifetime behavior warrants final human validation.

Review effort: Lite
Findings: None

What changed in this PR

Replaces the strong handler-collection cache with ConditionalWeakTable so unused collections can be garbage-collected.

Changes:

  • Uses weak-key storage for registered handler type sets.
  • Adds a GC-based regression test.
File Description
src/​Core/​src/​Hosting/​Internal/​RegisteredHandlerServiceTypeSet.cs Prevents static retention of handler collections.
src/​Core/​tests/​UnitTests/​Hosting/​RegisteredHandlerServiceTypeSetTests.cs Verifies collections can be garbage-collected.

@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 Sep 24, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Note

🔍 /review started

AzDO build 15445320 is running for android.

The s/agent-review-in-progress label stays on this PR while the run is active. The final recommendation and outcome labels are posted only after Gate, expert review, and Deep UI tests finish.

@kubaflo
kubaflo changed the base branch from main to inflight/current September 24, 2026 11:42
@kubaflo
kubaflo merged commit b1a6a69 into dotnet:inflight/current Sep 24, 2026
190 of 205 checks passed
@github-actions github-actions Bot added this to the .NET 10 SR12 milestone Sep 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.

AI Review Summary

@Shalini-Ashokan — new AI review results are available based on commit 162c210.

Gate Passed Confidence Low Platform Android


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

Gate Result: ✅ PASSED

Platform: ANDROID · Base: main · Merge base: 828569a8

Test Without Fix (expect FAIL) With Fix (expect PASS)
🧪 RegisteredHandlerServiceTypeSetTests RegisteredHandlerServiceTypeSetTests ✅ FAIL — 98s ✅ PASS — 81s
🔴 Without fix — 🧪 RegisteredHandlerServiceTypeSetTests: FAIL ✅ · 98s

Error-relevant lines (filtered from the build log):

     at Microsoft.Maui.UnitTesting.Hosting.RegisteredHandlerServiceTypeSetTests.RegisteredHandlerServiceCollectionCanBeCollected() in /_/src/Core/tests/UnitTests/Hosting/RegisteredHandlerServiceTypeSetTests.cs:line 156
   at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)
   at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)
🟢 With fix — 🧪 RegisteredHandlerServiceTypeSetTests: PASS ✅ · 81s

(no coded error found; showing last 1200 chars)

BaseViewStub)) [< 1 ms]
  Passed ResolveClosestApplicableServiceType(type: typeof(Microsoft.Maui.UnitTests.ViewStub), expectedImageSourceServiceType: typeof(Microsoft.Maui.UnitTests.IViewStub)) [< 1 ms]
  Passed ReturnsNullWhenNoMatchingHandlerServiceTypeIsRegistered [< 1 ms]
  Passed DoesNotResolveMoreDerivedTypes [< 1 ms]
  Passed ResolvesBaseInterfaceServiceType(baseInterfaceType: typeof(Microsoft.Maui.UnitTesting.Hosting.RegisteredHandlerServiceTypeSetTests+IMyDerivedViewStub)) [< 1 ms]
  Passed ResolvesBaseInterfaceServiceType(baseInterfaceType: typeof(Microsoft.Maui.UnitTests.IViewStub)) [< 1 ms]
  Passed ResolvesBaseInterfaceServiceType(baseInterfaceType: typeof(Microsoft.Maui.UnitTesting.Hosting.RegisteredHandlerServiceTypeSetTests+IMyBaseViewStub)) [< 1 ms]
  Passed ResolveCorrespondingHandlerServiceType [< 1 ms]
  Passed RegisteredHandlerServiceCollectionCanBeCollected [9 ms]
[xUnit.net 00:00:00.48]   Finished:    Microsoft.Maui.UnitTests
  Passed ResolvesToConcreteTypeOverInterfaceType [< 1 ms]
  Passed ResolvesToHandlerRegisteredUnderConcreteTypeDespiteAmbiguousInterfacesRegistered [< 1 ms]
Test Run Successful.
Total tests: 20
     Passed: 20
 Total time: 1.0844 Seconds
📁 Fix files reverted (1 files)
  • src/Core/src/Hosting/Internal/RegisteredHandlerServiceTypeSet.cs

📋 Pre-Flight — Context & Validation

Pre-Flight — PR #38768

Context

  • PR: #38768, [leak scan] Fix handler collection retention memory leak
  • Issue: #38671, [leak-scan] MauiHandlersCollectionExtensions.AddHandler — static mapping strongly retains transient collections
  • Requested platform: Android
  • Affected path: Platform-independent managed hosting code
  • Gate: Already passed. The regression test fails without the production fix and passes with it. Do not rerun gate verification and do not create or overwrite gate/content.md.

MauiHandlersCollectionExtensions.AddHandler routes registration through
RegisteredHandlerServiceTypeSet.GetInstance. On the baseline, that method stores every
IMauiHandlersCollection as a strong key in a process-wide
ConcurrentDictionary<IMauiHandlersCollection, RegisteredHandlerServiceTypeSet> with no
eviction path. A transient collection therefore retains its service descriptors, registered
instances, and factory closures for the process lifetime.

Submitted Fix

The PR replaces the strong-key ConcurrentDictionary with
ConditionalWeakTable<IMauiHandlersCollection, RegisteredHandlerServiceTypeSet> and changes
GetOrAdd to GetValue. It adds
RegisteredHandlerServiceCollectionCanBeCollected, which registers a handler through the real
AddHandler path, drops the collection behind a WeakReference, forces a full collection, and
asserts that the collection is no longer alive.

Changed files:

  • src/Core/src/Hosting/Internal/RegisteredHandlerServiceTypeSet.cs
  • src/Core/tests/UnitTests/Hosting/RegisteredHandlerServiceTypeSetTests.cs

Bounded Validation

  • Primary regression: RegisteredHandlerServiceCollectionCanBeCollected

  • Mandatory regressions: The other handler registration/resolution tests in
    RegisteredHandlerServiceTypeSetTests

  • Only authorized test command:

    dotnet test src/Core/tests/UnitTests/Core.UnitTests.csproj --filter "FullyQualifiedName~RegisteredHandlerServiceTypeSetTests"

This class filter runs the leak regression and the existing resolution regressions together
(20 tests in the completed gate). Do not run a broader test suite, manually build, or run the
gate's before/after verification.

Try-Fix Boundary

Each candidate must establish and restore the broken baseline exclusively through
.github/scripts/EstablishBrokenBaseline.ps1, attempt one mechanism different from the PR's
ConditionalWeakTable, run the bounded command once, and may make at most one focused
correction followed by one retest. The implementation target is
src/Core/src/Hosting/Internal/RegisteredHandlerServiceTypeSet.cs; the submitted regression
test is read-only during alternative generation.

The dedicated expert review is deferred to STEP 5b. Each try-fix performs only the inline
self-review required by the try-fix skill.


🔬 Code Review — Deep Analysis

Code Review — PR #38768

Independent Assessment

What this changes: Replaces the process-wide strong-key cache of IMauiHandlersCollection instances with a ConditionalWeakTable, allowing a handler collection and its associated RegisteredHandlerServiceTypeSet to be reclaimed together. The added unit test registers a handler on a short-lived collection and verifies that the collection is no longer rooted after forced collection.

Inferred motivation: RegisteredHandlerServiceTypeSet.s_instances previously retained every collection passed to AddHandler for the lifetime of the process, indirectly retaining registered services and related state.

Approach Assessment

The weak-key association is the appropriate abstraction. The value does not reference its key, so ephemeron semantics allow both objects to be reclaimed. ConditionalWeakTable.GetValue preserves the required thread-safe key-to-value association; its callback may run more than once under contention, just as ConcurrentDictionary.GetOrAdd may invoke its value factory more than once, while only one value is associated with the key.

The GC regression test is focused and discriminative. Its no-inline helper prevents the collection local from remaining live in the test frame and exercises the public registration path that populates the static association.

Blast Radius Assessment

  • Runs for all handler registrations and handler-factory construction, but changes only cache lifetime semantics.
  • Does not add startup work, platform-specific behavior, or a new public API.
  • Replaces process-lifetime static retention with key-scoped static state; live collections continue to resolve the same per-collection type set.
  • No trim, NativeAOT, reflection, external-output, or handler lifecycle contract is changed.

Findings

No actionable inline findings. inline-findings.json contains an empty JSON array.

Failure-Mode Probing

  • Collection remains live: GetValue returns the same associated set, preserving registrations and factory lookup behavior.
  • Collection becomes unreachable: the table does not root the key, and the value has no back-reference to it, so both can be collected.
  • Concurrent first access: association creation remains thread-safe; duplicate factory invocations cannot expose a second value through the table.
  • Repeated registration/factory creation: all calls for the same live collection observe the associated set.

External Output Contract

Not applicable.

Verdict: NEEDS_DISCUSSION

Confidence: low

Summary: The submitted implementation is technically sound and the expert review found no code defect or discussion item. The conservative review verdict reflects unavailable authenticated required-check data, not a flaw in the patch; the trusted Gate supplied to this workflow passed.


🛠️ Try-Fix — Analysis & Comparison

STEP 5a — Bounded Try-Fix Aggregate

Candidate Status

# Model Approach Result Targeted tests Corrections Self-review
1 gpt-5.3-codex Lock-protected weak-reference registry with opportunistic compaction PASS 20/20 0 0 findings
2 gpt-5.6-sol Collection-owned implementation-instance service descriptor PASS 20/20 0 0 findings

The hard cap of two candidates has been reached. This aggregate was persisted after each
candidate.

Candidate 1 — Weak-Reference Registry

Candidate 1 replaced the baseline's static strong-key ConcurrentDictionary with a
process-wide, lock-protected list of registrations. Each registration strongly owns its
RegisteredHandlerServiceTypeSet but holds the associated IMauiHandlersCollection through
WeakReference<IMauiHandlersCollection>. GetInstance scans backward under the lock, removes
dead registrations, returns a live reference-identity match, or adds a new registration.

This is mechanism-level different from the submitted PR: it uses explicit weak references,
locking, and opportunistic cleanup rather than ConditionalWeakTable ephemeron semantics.
Once external owners release a collection, the registry cannot keep the collection alive; a
later lookup prunes the dead registration.

Changed file: src/Core/src/Hosting/Internal/RegisteredHandlerServiceTypeSet.cs

Validation command:

dotnet test src/Core/tests/UnitTests/Core.UnitTests.csproj --filter "FullyQualifiedName~RegisteredHandlerServiceTypeSetTests"

Result: PASS on the first run: 20 passed, 0 failed, 0 skipped. No correction or retest was
needed. The inline expert self-review recorded zero findings.

Captured diff:

diff --git a/src/Core/src/Hosting/Internal/RegisteredHandlerServiceTypeSet.cs b/src/Core/src/Hosting/Internal/RegisteredHandlerServiceTypeSet.cs
index ae3b0d0e64..28e2fb2765 100644
--- a/src/Core/src/Hosting/Internal/RegisteredHandlerServiceTypeSet.cs
+++ b/src/Core/src/Hosting/Internal/RegisteredHandlerServiceTypeSet.cs
@@ -1,5 +1,4 @@
 using System;
-using System.Collections.Concurrent;
 using System.Collections.Generic;
 using System.Diagnostics;
 
@@ -7,10 +6,33 @@ namespace Microsoft.Maui.Hosting.Internal
 {
 	internal sealed class RegisteredHandlerServiceTypeSet
 	{
-		private static readonly ConcurrentDictionary<IMauiHandlersCollection, RegisteredHandlerServiceTypeSet> s_instances = new();
+		private static readonly object s_instanceLock = new();
+		private static readonly List<CollectionRegistration> s_instances = new();
 
-		internal static RegisteredHandlerServiceTypeSet GetInstance(IMauiHandlersCollection collection) =>
-			s_instances.GetOrAdd(collection, static _ => new RegisteredHandlerServiceTypeSet());
+		internal static RegisteredHandlerServiceTypeSet GetInstance(IMauiHandlersCollection collection)
+		{
+			lock (s_instanceLock)
+			{
+				for (var i = s_instances.Count - 1; i >= 0; i--)
+				{
+					var registration = s_instances[i];
+					if (!registration.TryGetCollection(out var registeredCollection))
+					{
+						s_instances.RemoveAt(i);
+						continue;
+					}
+
+					if (ReferenceEquals(collection, registeredCollection))
+					{
+						return registration.ServiceTypeSet;
+					}
+				}
+
+				var serviceTypeSet = new RegisteredHandlerServiceTypeSet();
+				s_instances.Add(new CollectionRegistration(collection, serviceTypeSet));
+				return serviceTypeSet;
+			}
+		}
 
 		private readonly HashSet<Type> _concreteHandlerServiceTypeSet = new();
 		private readonly HashSet<Type> _interfaceHandlerServiceTypeSet = new();
@@ -73,5 +95,21 @@ namespace Microsoft.Maui.Hosting.Internal
 
 			return bestVirtualViewHandlerServiceType;
 		}
+
+		private sealed class CollectionRegistration
+		{
+			private readonly WeakReference<IMauiHandlersCollection> _collection;
+
+			public CollectionRegistration(IMauiHandlersCollection collection, RegisteredHandlerServiceTypeSet serviceTypeSet)
+			{
+				_collection = new WeakReference<IMauiHandlersCollection>(collection);
+				ServiceTypeSet = serviceTypeSet;
+			}
+
+			public RegisteredHandlerServiceTypeSet ServiceTypeSet { get; }
+
+			public bool TryGetCollection(out IMauiHandlersCollection? collection) =>
+				_collection.TryGetTarget(out collection);
+		}
 	}
 }

The required restore command was executed and the production worktree is back at the clean PR
head. Candidate 1's detailed narrative and artifacts are in
../try-fix-1/content.md and attempt-1/.

Candidate 2 — Collection-Owned Service Descriptor

Candidate 2 removed the process-wide association entirely. GetInstance first calls
IMauiHandlersCollection.TryGetService for the internal
RegisteredHandlerServiceTypeSet type. If the collection already contains an
implementation-instance descriptor for that type, it returns that set. Otherwise, it creates a
set and adds it to the collection as a singleton ServiceDescriptor.

This mechanism differs from both earlier options:

  • Unlike the submitted PR, it does not keep a process-wide weak-key ephemeron table.
  • Unlike candidate 1, it has no weak reference, global registry, lock, identity scan,
    compaction, hash bucket, or cleanup path.

The collection itself owns the descriptor and registration set, and the set has no reference
back to the collection. When external owners release the collection, that entire graph becomes
unreachable together. Repeated calls while the collection is live recover the same set through
the collection's existing service metadata.

Changed file: src/Core/src/Hosting/Internal/RegisteredHandlerServiceTypeSet.cs

Validation command:

dotnet test src/Core/tests/UnitTests/Core.UnitTests.csproj --filter "FullyQualifiedName~RegisteredHandlerServiceTypeSetTests"

Result: PASS on the first run: 20 passed, 0 failed, 0 skipped. No correction or retest was
needed. The inline expert self-review recorded zero findings.

Captured diff:

diff --git a/src/Core/src/Hosting/Internal/RegisteredHandlerServiceTypeSet.cs b/src/Core/src/Hosting/Internal/RegisteredHandlerServiceTypeSet.cs
index ae3b0d0e64..d2ae36a2da 100644
--- a/src/Core/src/Hosting/Internal/RegisteredHandlerServiceTypeSet.cs
+++ b/src/Core/src/Hosting/Internal/RegisteredHandlerServiceTypeSet.cs
@@ -1,16 +1,24 @@
 using System;
-using System.Collections.Concurrent;
 using System.Collections.Generic;
 using System.Diagnostics;
+using Microsoft.Extensions.DependencyInjection;
 
 namespace Microsoft.Maui.Hosting.Internal
 {
 	internal sealed class RegisteredHandlerServiceTypeSet
 	{
-		private static readonly ConcurrentDictionary<IMauiHandlersCollection, RegisteredHandlerServiceTypeSet> s_instances = new();
+		internal static RegisteredHandlerServiceTypeSet GetInstance(IMauiHandlersCollection collection)
+		{
+			if (collection.TryGetService(typeof(RegisteredHandlerServiceTypeSet), out var descriptor)
+				&& descriptor?.ImplementationInstance is RegisteredHandlerServiceTypeSet registeredServiceTypes)
+			{
+				return registeredServiceTypes;
+			}
 
-		internal static RegisteredHandlerServiceTypeSet GetInstance(IMauiHandlersCollection collection) =>
-			s_instances.GetOrAdd(collection, static _ => new RegisteredHandlerServiceTypeSet());
+			var newRegisteredServiceTypes = new RegisteredHandlerServiceTypeSet();
+			collection.Add(ServiceDescriptor.Singleton(typeof(RegisteredHandlerServiceTypeSet), newRegisteredServiceTypes));
+			return newRegisteredServiceTypes;
+		}
 
 		private readonly HashSet<Type> _concreteHandlerServiceTypeSet = new();
 		private readonly HashSet<Type> _interfaceHandlerServiceTypeSet = new();

The exact restore command completed with Restored True; the production worktree matches the
clean PR head. Candidate 2's detailed narrative and artifacts are in
../try-fix-2/content.md and attempt-2/.

Bounded Comparison

Both alternatives satisfy the leak regression and preserve all 19 existing resolution
regressions in the authorized class filter:

Mechanism Process-wide state Additional behavior surface
Submitted PR ConditionalWeakTable with weak keys Runtime-provided identity, concurrency, and lifetime semantics
Candidate 1 Locked list of explicit weak registrations Custom scanning, pruning, synchronization, and list growth between lookups
Candidate 2 None Adds an internal service descriptor to each handler collection

Candidate 1 proves an explicit weak registry can fix the retention, but carries substantially
more custom lifetime and synchronization logic than the submitted PR. Candidate 2 has simpler
ownership and no global cleanup machinery, but changes the contents observable through the
handler collection's service metadata. This STEP 5a aggregate records alternatives and test
evidence only; the dedicated STEP 5b expert pass owns final selection.


📝 PR Finalize — Recommended Title & Description

Assessment: ✏️ Recommend updating — the description is accurate and detailed, but the title uses a workflow label rather than the repository's platform/component format and the description omits the submitted regression test.

Recommended title

[Core] Hosting: Allow handler collections to be garbage collected

Recommended description

### Issue Details

`AddHandler` can cause `IMauiHandlersCollection` objects and their registered services to stay in memory, resulting in a memory leak.

### Root Cause

`RegisteredHandlerServiceTypeSet` used a static `ConcurrentDictionary` that held each handler collection as a strong key, preventing transient collections from being garbage-collected.

### Description of Change

Replaced the `ConcurrentDictionary<IMauiHandlersCollection, RegisteredHandlerServiceTypeSet>` with a `ConditionalWeakTable<IMauiHandlersCollection, RegisteredHandlerServiceTypeSet>`. This preserves one registered-handler service-type set per live collection without keeping the collection alive after its other references are released.

Added `RegisteredHandlerServiceCollectionCanBeCollected` to exercise the real `AddHandler` path and verify that a registered `MauiHandlersCollection` can be garbage-collected.

Validated the behavior on the following platforms:

- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac

### Issues Fixed

Fixes #38671

### Output Screenshot

| Before | After |
|--|--|
| <img width="700" height="284" alt="image" src="https://github.com/user-attachments/assets/d31d91b4-02a3-4317-8f45-dfda2ade95a0" /> | <img width="700" height="284" alt="image" src="https://github.com/user-attachments/assets/cd5d50a3-3808-4630-80b2-c9e5237593e8" /> |

🏁 Report — Final Recommendation

✅ Final Recommendation: APPROVE

Winner: pr

The submitted PR is the best candidate. It fixes the strong-root retention with the framework primitive designed for identity-based weak-key associations, preserves one registration set per live handler collection, and adds a focused regression test. The trusted Gate passed: the test fails without the production fix and passes with it. The single expert review found no actionable code issue or discussion item in the implementation.

pr-plus-reviewer is byte-for-byte equivalent to pr because the expert produced no actionable feedback. It therefore offers no refinement to prefer over the submitted change.

Comparative Ranking

Rank Candidate Mechanism Regression evidence Assessment
1 pr ConditionalWeakTable<IMauiHandlersCollection, RegisteredHandlerServiceTypeSet> Trusted Gate passed; targeted class contains 20 tests Winner. Minimal, idiomatic, thread-safe weak association with runtime-managed cleanup and no observable collection mutation.
2 pr-plus-reviewer Identical to pr; empty reviewer patch Relies on the same passed Gate because no code changed Equally correct, but not a distinct improvement and therefore not preferable to the submitted PR.
3 try-fix-2 Stores the type set as an implementation-instance service descriptor in each collection 20/20 targeted tests passed Removes global state, but mutates service metadata with an internal descriptor and uses a non-atomic lookup-then-add sequence. That expands observable behavior and concurrency risk without improving the fix.
4 try-fix-1 Lock-protected global list of weak references with opportunistic compaction 20/20 targeted tests passed Fixes collection retention, but adds custom locking, linear scans, stale entries retained until a later lookup, and manual cleanup logic that ConditionalWeakTable already implements more safely.

Correctness and Lifetime Comparison

  • pr: The static table does not root its key. Its value contains only registered Type sets and no back-reference to the collection, so the collection and associated set become collectible together. A live collection consistently retrieves its associated set.
  • pr-plus-reviewer: Same behavior as pr; reviewer.patch is empty.
  • try-fix-1: The weak reference permits collection, but the static registry strongly retains each value and dead registration object until another lookup performs compaction. Correct for the tested leak, but needlessly retains auxiliary state and serializes every lookup.
  • try-fix-2: Collection ownership gives the desired lifetime, but adding an internal service descriptor changes collection contents and concurrent first access can create/add more than one set. The targeted tests do not cover that expanded contract.

Test and Review Evidence

No candidate failed regression tests, so the failed-test ranking rule does not alter the ordering. Both try-fix candidates passed 20/20 tests on their first permitted run. The raw PR passed the trusted fail-without/pass-with gate, and the expert review produced [] in inline-findings.json. The expert's conservative NEEDS_DISCUSSION label was solely due to unavailable authenticated required-check data; it identified no implementation defect. For this comparative workflow, the explicitly supplied trusted Gate permits approval.

Platform Note

Although Android was the requested test platform, the changed cache and registration path are platform-independent managed hosting code. The focused Core unit-test class directly covers the lifetime fix and existing handler-service resolution behavior without requiring an Android-specific implementation change.


📱 UI Tests — Button,Label,Layout

Detected UI test categories: Button,Label,Layout

✅ Deep UI tests — 422 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 104/106 (2 skipped) ✓ —
Label 123/125 (2 skipped) ✓ —
Layout 195/198 (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.

@MauiBot MauiBot removed the s/agent-review-in-progress AI review is currently running for this PR label Sep 24, 2026
kubaflo pushed a commit that referenced this pull request Sep 27, 2026
<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->


### Issue Details
AddHandler can cause IMauiHandlersCollection objects and their
registered services to stay in memory, resulting in a memory leak.

### Root Cause
A static ConcurrentDictionary keeps the handler collection as a strong
reference, so it cannot be garbage-collected.

### Description of Change

Replaced ConcurrentDictionary with ConditionalWeakTable in
RegisteredHandlerServiceTypeSet to ensure that IMauiHandlersCollection
instances can be garbage collected when no longer referenced, reducing
the risk of memory leaks.

Validated the behavior in the following platforms
 
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac
 
### Issues Fixed
  
Fixes #38671 

### Output  ScreenShot

|Before|After|
|--|--|
| <img width="700" height="284" alt="image"
src="https://github.com/user-attachments/assets/d31d91b4-02a3-4317-8f45-dfda2ade95a0"
/> | <img width="700" height="284" alt="image"
src="https://github.com/user-attachments/assets/cd5d50a3-3808-4630-80b2-c9e5237593e8"
/> |
kubaflo pushed a commit that referenced this pull request Oct 3, 2026
<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->


### Issue Details
AddHandler can cause IMauiHandlersCollection objects and their
registered services to stay in memory, resulting in a memory leak.

### Root Cause
A static ConcurrentDictionary keeps the handler collection as a strong
reference, so it cannot be garbage-collected.

### Description of Change

Replaced ConcurrentDictionary with ConditionalWeakTable in
RegisteredHandlerServiceTypeSet to ensure that IMauiHandlersCollection
instances can be garbage collected when no longer referenced, reducing
the risk of memory leaks.

Validated the behavior in the following platforms
 
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac
 
### Issues Fixed
  
Fixes #38671 

### Output  ScreenShot

|Before|After|
|--|--|
| <img width="700" height="284" alt="image"
src="https://github.com/user-attachments/assets/d31d91b4-02a3-4317-8f45-dfda2ade95a0"
/> | <img width="700" height="284" alt="image"
src="https://github.com/user-attachments/assets/cd5d50a3-3808-4630-80b2-c9e5237593e8"
/> |
kubaflo pushed a commit that referenced this pull request Oct 6, 2026
<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->


### Issue Details
AddHandler can cause IMauiHandlersCollection objects and their
registered services to stay in memory, resulting in a memory leak.

### Root Cause
A static ConcurrentDictionary keeps the handler collection as a strong
reference, so it cannot be garbage-collected.

### Description of Change

Replaced ConcurrentDictionary with ConditionalWeakTable in
RegisteredHandlerServiceTypeSet to ensure that IMauiHandlersCollection
instances can be garbage collected when no longer referenced, reducing
the risk of memory leaks.

Validated the behavior in the following platforms
 
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac
 
### Issues Fixed
  
Fixes #38671 

### Output  ScreenShot

|Before|After|
|--|--|
| <img width="700" height="284" alt="image"
src="https://github.com/user-attachments/assets/d31d91b4-02a3-4317-8f45-dfda2ade95a0"
/> | <img width="700" height="284" alt="image"
src="https://github.com/user-attachments/assets/cd5d50a3-3808-4630-80b2-c9e5237593e8"
/> |
kubaflo pushed a commit that referenced this pull request Oct 13, 2026
<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->


### Issue Details
AddHandler can cause IMauiHandlersCollection objects and their
registered services to stay in memory, resulting in a memory leak.

### Root Cause
A static ConcurrentDictionary keeps the handler collection as a strong
reference, so it cannot be garbage-collected.

### Description of Change

Replaced ConcurrentDictionary with ConditionalWeakTable in
RegisteredHandlerServiceTypeSet to ensure that IMauiHandlersCollection
instances can be garbage collected when no longer referenced, reducing
the risk of memory leaks.

Validated the behavior in the following platforms
 
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac
 
### Issues Fixed
  
Fixes #38671 

### Output  ScreenShot

|Before|After|
|--|--|
| <img width="700" height="284" alt="image"
src="https://github.com/user-attachments/assets/d31d91b4-02a3-4317-8f45-dfda2ade95a0"
/> | <img width="700" height="284" alt="image"
src="https://github.com/user-attachments/assets/cd5d50a3-3808-4630-80b2-c9e5237593e8"
/> |
kubaflo pushed a commit that referenced this pull request Oct 14, 2026
<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->


### Issue Details
AddHandler can cause IMauiHandlersCollection objects and their
registered services to stay in memory, resulting in a memory leak.

### Root Cause
A static ConcurrentDictionary keeps the handler collection as a strong
reference, so it cannot be garbage-collected.

### Description of Change

Replaced ConcurrentDictionary with ConditionalWeakTable in
RegisteredHandlerServiceTypeSet to ensure that IMauiHandlersCollection
instances can be garbage collected when no longer referenced, reducing
the risk of memory leaks.

Validated the behavior in the following platforms
 
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac
 
### Issues Fixed
  
Fixes #38671 

### Output  ScreenShot

|Before|After|
|--|--|
| <img width="700" height="284" alt="image"
src="https://github.com/user-attachments/assets/d31d91b4-02a3-4317-8f45-dfda2ade95a0"
/> | <img width="700" height="284" alt="image"
src="https://github.com/user-attachments/assets/cd5d50a3-3808-4630-80b2-c9e5237593e8"
/> |
kubaflo pushed a commit that referenced this pull request Oct 18, 2026
<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->


### Issue Details
AddHandler can cause IMauiHandlersCollection objects and their
registered services to stay in memory, resulting in a memory leak.

### Root Cause
A static ConcurrentDictionary keeps the handler collection as a strong
reference, so it cannot be garbage-collected.

### Description of Change

Replaced ConcurrentDictionary with ConditionalWeakTable in
RegisteredHandlerServiceTypeSet to ensure that IMauiHandlersCollection
instances can be garbage collected when no longer referenced, reducing
the risk of memory leaks.

Validated the behavior in the following platforms
 
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac
 
### Issues Fixed
  
Fixes #38671 

### Output  ScreenShot

|Before|After|
|--|--|
| <img width="700" height="284" alt="image"
src="https://github.com/user-attachments/assets/d31d91b4-02a3-4317-8f45-dfda2ade95a0"
/> | <img width="700" height="284" alt="image"
src="https://github.com/user-attachments/assets/cd5d50a3-3808-4630-80b2-c9e5237593e8"
/> |
kubaflo pushed a commit that referenced this pull request Oct 21, 2026
<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->


### Issue Details
AddHandler can cause IMauiHandlersCollection objects and their
registered services to stay in memory, resulting in a memory leak.

### Root Cause
A static ConcurrentDictionary keeps the handler collection as a strong
reference, so it cannot be garbage-collected.

### Description of Change

Replaced ConcurrentDictionary with ConditionalWeakTable in
RegisteredHandlerServiceTypeSet to ensure that IMauiHandlersCollection
instances can be garbage collected when no longer referenced, reducing
the risk of memory leaks.

Validated the behavior in the following platforms
 
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac
 
### Issues Fixed
  
Fixes #38671 

### Output  ScreenShot

|Before|After|
|--|--|
| <img width="700" height="284" alt="image"
src="https://github.com/user-attachments/assets/d31d91b4-02a3-4317-8f45-dfda2ade95a0"
/> | <img width="700" height="284" alt="image"
src="https://github.com/user-attachments/assets/cd5d50a3-3808-4630-80b2-c9e5237593e8"
/> |
@github-actions github-actions Bot locked and limited conversation to collaborators Oct 25, 2026

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — 162c210c Deployed Sep 22, 2026 by Shalini-Ashokan via conclusion #2011
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

community ✨ Community Contribution partner/syncfusion Issues / PR's with Syncfusion collaboration s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-fix-pr-picked AI could not beat the PR fix - PR is the best among all candidates 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.

[leak-scan] MauiHandlersCollectionExtensions.AddHandler — static mapping strongly retains transient collections

4 participants