Skip to content

Fix PathFigure memory leak with shared PathSegmentCollection - #38744

Merged
kubaflo merged 4 commits into
dotnet:inflight/currentfrom
devanathan-vaithiyanathan:fix-38718
Sep 24, 2026
Merged

kubaflo merged 4 commits into
dotnet:inflight/currentfrom
devanathan-vaithiyanathan:fix-38718

Conversation

@devanathan-vaithiyanathan

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

When multiple PathFigure instances use the same PathSegmentCollection, the CollectionChanged event subscription can keep the PathFigure instances alive even after they are no longer referenced.
This can prevent the PathFigure objects from being garbage collected and may result in increasing memory usage when this scenario occurs repeatedly.

Description of Change

  • Added WeakNotifyCollectionChangedProxy to manage PathSegmentCollection.CollectionChanged subscriptions using a weak reference.
  • Updated PathFigure finalization to unsubscribe the collection proxy when the PathFigure is finalized.
  • Updated the collection subscription and unsubscription logic to use the proxy.

Issues Fixed

Fixes #38718

Tested the behavior in the following platforms.

  • Android
  • Windows
  • iOS
  • Mac
Before After
Android
Before-38718.mov
Android
After-38718.mov

@dotnet-policy-service dotnet-policy-service Bot added the partner/syncfusion Issues / PR's with Syncfusion collaboration label Sep 21, 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.

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

Or

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

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

Copy link
Copy Markdown
Contributor

Note

🔍 /review started

AzDO build 15398323 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.

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 21, 2026
@kubaflo

This comment has been minimized.

@github-actions

This comment has been minimized.

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

@kubaflo

This comment has been minimized.

@github-actions

This comment has been minimized.

@sheiksyedm
sheiksyedm marked this pull request as ready for review September 24, 2026 11:16
Copilot AI lite review requested due to automatic review settings September 24, 2026 11:16

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

🟡 Changes recommended

Per-segment subscriptions leave the reported leak unresolved, and the regression test does not cover that scenario.

Get a fresh assessment by requesting another Copilot review.

Review effort: Lite
Findings: 1 Medium severity

Open (1)
What changed in this PR

Fixes PathFigure retention for shared PathSegmentCollection instances.

Changes:

  • Adds a weak collection-change proxy and finalizer cleanup.
  • Adds a GC-based regression test.
  • Retains strong per-segment property-change subscriptions.
File Summary
src/​Controls/​src/​Core/​Shapes/​PathFigure.cs Uses weak collection subscriptions, but per-segment subscriptions can still retain figures.
src/​Controls/​tests/​Core.UnitTests/​Shapes/​PathSharedResourcesMemoryLeakTests.cs Adds leak coverage, but does not test collections containing segments or prevent helper inlining.

[Fact]
public void SharedPathSegmentCollection_DoesNotKeepPathFigureAlive()
{
var sharedSegments = new PathSegmentCollection();
@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 15445870 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.

@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 — 2 findings

See inline comments for details.

Segments = new PathSegmentCollection();
}

~PathFigure() => _segmentsCollectionProxy.Unsubscribe();

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] Memory Leak Prevention — The finalizer only unsubscribes the collection-level weak proxy, but it never detaches PathSegment.PropertyChanged handlers tracked in _subscribedSegments. Concrete failure: if Segments contains one or more rooted segments (shared collection), each segment keeps a strong delegate to PathFigure, so PathFigure stays alive and this finalizer never runs.

[Fact]
public void SharedPathSegmentCollection_DoesNotKeepPathFigureAlive()
{
var sharedSegments = new PathSegmentCollection();

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 — This regression test uses an empty PathSegmentCollection, so it does not exercise the non-empty path where PathFigure subscribes to each PathSegment.PropertyChanged. Concrete gap: a shared collection with at least one segment can still retain PathFigure through segment event handlers, but this test would pass.

@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

@devanathan-vaithiyanathan — new AI review results are available based on commit 3c6b113.

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)
🧪 PathSharedResourcesMemoryLeakTests PathSharedResourcesMemoryLeakTests ✅ FAIL — 159s ✅ PASS — 123s
🔴 Without fix — 🧪 PathSharedResourcesMemoryLeakTests: FAIL ✅ · 159s

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

     at Microsoft.Maui.Controls.Core.UnitTests.Shapes.PathSharedResourcesMemoryLeakTests.SharedPathSegmentCollection_DoesNotKeepPathFigureAlive() in /_/src/Controls/tests/Core.UnitTests/Shapes/PathSharedResourcesMemoryLeakTests.cs:line 50
   at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)
   at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)
🟢 With fix — 🧪 PathSharedResourcesMemoryLeakTests: PASS ✅ · 123s
  Determining projects to restore...
  All projects are up-to-date for restore.
Test run for /home/vsts/work/1/s/artifacts/bin/Controls.Core.UnitTests/Debug/net10.0/Microsoft.Maui.Controls.Core.UnitTests.dll (.NETCoreApp,Version=v10.0)
VSTest version 18.0.2 (x64)
Starting test execution, please wait...
A total of 1 test files matched the specified pattern.
[xUnit.net 00:00:00.00] xUnit.net VSTest Adapter v2.8.2+699d445a1a (64-bit .NET 10.0.13)
[xUnit.net 00:00:00.37]   Discovering: Microsoft.Maui.Controls.Core.UnitTests
[xUnit.net 00:00:03.21]   Discovered:  Microsoft.Maui.Controls.Core.UnitTests
[xUnit.net 00:00:03.25]   Starting:    Microsoft.Maui.Controls.Core.UnitTests
[xUnit.net 00:00:03.52]   Finished:    Microsoft.Maui.Controls.Core.UnitTests
  Passed SharedGeometryAndTransform_DoNotKeepPathAlive [90 ms]
  Passed SharedRenderTransform_DoesNotKeepPathAlive [34 ms]
  Passed SharedPathSegmentCollection_DoesNotKeepPathFigureAlive [23 ms]
  Passed SharedPathGeometry_DoesNotKeepPathAlive [23 ms]
Test Run Successful.
Total tests: 4
     Passed: 4
 Total time: 4.3193 Seconds
📁 Fix files reverted (1 files)
  • src/Controls/src/Core/Shapes/PathFigure.cs

📋 Pre-Flight — Context & Validation

PR #38744 Pre-Flight

Context

  • PR: #38744, Fix PathFigure memory leak with shared PathSegmentCollection
  • Issue: #38718, [leak-scan] PathFigure.Segments — shared collection strongly retains path figure
  • Base / review head: origin/main at 828569a86489228dc66a7867173635a6fb4f27be / squashed review commit 70ef5a7c8069971acca0da983bb956b48a8bcb5f
  • Requested platform: Android. The defect is in managed Controls code and is platform-independent.

Problem

When a long-lived PathSegmentCollection is assigned to PathFigure.Segments, the collection retains the figure through:

PathSegmentCollection.CollectionChanged -> PathFigure.OnPathSegmentCollectionChanged -> PathFigure -> BindingContext

The original implementation removes the strong event subscription only when Segments is replaced. If the shared collection outlives the figure, the figure cannot become collectible.

PR Implementation

The PR changes src/Controls/src/Core/Shapes/PathFigure.cs to:

  • hold a WeakNotifyCollectionChangedProxy;
  • cache the NotifyCollectionChangedEventHandler;
  • subscribe and unsubscribe through the weak proxy;
  • add a finalizer that unsubscribes the proxy; and
  • route reset cleanup through UnsubscribeFromAllPathSegmentPropertyChanged().

It adds SharedPathSegmentCollection_DoesNotKeepPathFigureAlive to
src/Controls/tests/Core.UnitTests/Shapes/PathSharedResourcesMemoryLeakTests.cs.
The public API surface is unchanged.

Direct Diff Assessment

The production change is 11 insertions / 6 deletions in PathFigure.cs; the test adds 24 lines. Existing repository prior art uses the same weak collection proxy and finalizer pattern, including IndicatorView and GeometryGroup.ChildrenSubscriptions. An alternative candidate must therefore differ at the mechanism/root-cause level rather than merely moving the proxy calls.

Only src/Controls/src/Core/Shapes/PathFigure.cs is a gate-identified fix file and may be modified after EstablishBrokenBaseline.ps1; the added test file remains present to validate candidates.

Validation Scope

Gate already passed and must not be rerun:

  • without fix: SharedPathSegmentCollection_DoesNotKeepPathFigureAlive failed;
  • with PR fix: all four PathSharedResourcesMemoryLeakTests passed.

Allowed primary/regression command (the class filter includes the new leak test and the three mandatory adjacent shared-resource regressions):

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

No additional regression tests were supplied, and no full suite may be run.

Bounded Attempt Rules

Each candidate gets one implementation/test pass and at most one focused correction/retest. Every attempt must follow the try-fix skill, perform its inline expert self-review, capture artifacts and the final diff, then restore only with:

pwsh .github/scripts/EstablishBrokenBaseline.ps1 -Restore

Candidate 2 must consume candidate 1's recorded result and use a distinct mechanism without reopening or rerunning candidate 1.


🔬 Code Review — Deep Analysis

Code Review — PR #38744

Independent Assessment

What this changes: PathFigure replaces its direct PathSegmentCollection.CollectionChanged subscription with WeakNotifyCollectionChangedProxy, caches the forwarding delegate, unsubscribes the proxy during collection replacement and finalization, and reuses the existing helper when processing collection resets. The added regression test verifies collection of a figure assigned an empty, rooted PathSegmentCollection.

Inferred motivation: A long-lived shared collection previously rooted PathFigure through its CollectionChanged invocation list.

Reconciliation with PR Narrative

The description accurately identifies and fixes the collection-level retention edge, but its broader claim that shared PathSegmentCollection usage no longer keeps a figure alive is incomplete. For every non-empty collection, PathFigure still subscribes its instance method directly to each contained PathSegment.PropertyChanged event.

Prior Review Reconciliation

Prior finding Source Status Evidence
The regression uses an empty collection and misses direct PathSegment.PropertyChanged retention Copilot inline review at PathSharedResourcesMemoryLeakTests.cs:42 ❌ Unresolved The current test still constructs new PathSegmentCollection() with no segment, while SubscribeToPathSegmentPropertyChanged remains a strong instance subscription.

An earlier top-level MauiBot review reported no actionable defect, but it did not trace the rooted non-empty collection path. The later inline finding and this expert review independently identify the same unresolved gap.

Blast Radius Assessment

  • Runs for all instances: The weak collection proxy applies to every PathFigure; the unresolved strong segment subscription applies whenever Segments is non-empty.
  • Startup impact: None; the code runs when a figure initializes or its segment collection changes.
  • Static/shared state: No new static state.
  • Public API: Unchanged.

CI Status

  • Required-check result: Undetermined. gh pr checks --required was unavailable because the CLI is unauthenticated; the public check-runs API shows current-head activity and successful jobs but does not identify the branch's required-check set.
  • Trusted Gate: Passed for the submitted empty-collection regression (fails without the PR fix and passes with it).
  • Classification: The Gate validates only the collection-level edge and cannot disprove the non-empty collection leak.

Findings

❌ Error — Non-empty shared collections still retain PathFigure

src/Controls/src/Core/Shapes/PathFigure.cs:29 finalizes only _segmentsCollectionProxy. A rooted non-empty collection retains each segment, and each segment's PropertyChanged invocation list strongly retains PathFigure.OnPathSegmentPropertyChanged. The resulting path is:

shared PathSegmentCollection -> PathSegment -> PropertyChanged delegate -> PathFigure

Because that path keeps the figure alive, its finalizer cannot run and cannot clean up the segment subscriptions.

❌ Error — Regression test exercises only the already-fixed edge

src/Controls/tests/Core.UnitTests/Shapes/PathSharedResourcesMemoryLeakTests.cs:42 uses an empty collection. It proves the weak CollectionChanged proxy breaks the direct collection-to-figure edge, but it never enters the loop that subscribes to PathSegment.PropertyChanged; adding a segment reproduces the still-live retention path.

Failure-Mode Probing

  • Rooted empty collection: The PR succeeds; the proxy holds the instance delegate weakly.
  • Rooted collection containing one or more segments: The figure remains rooted by the segment event delegate, so the advertised leak guarantee fails.
  • Several figures sharing the same non-empty collection: Each segment accumulates a strong handler for every figure; dropping application references does not make those figures collectible.
  • Replacing or clearing Segments while the figure is live: Existing cleanup removes segment handlers, so this path remains coherent.
  • Finalization without a later collection mutation: The collection proxy can be detached, but segment handlers cannot be detached because they prevent finalization in the first place.

External Output Contract

Not applicable.

Verdict: NEEDS_CHANGES

Confidence: low

Summary: The submitted PR fixes the empty-collection retention path but leaves a concrete non-empty shared-collection leak and tests only the narrower passing case. The defect is established by the event-reference graph; confidence is capped only because required-check status could not be determined through the available unauthenticated tooling.


🛠️ Try-Fix — Analysis & Comparison

PR #38744 Alternative Fix Candidates

Bound: At most two sequential candidates.
Validation: dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --filter "FullyQualifiedName~PathSharedResourcesMemoryLeakTests" only.
Gate: Previously passed; not rerun.

Candidate 1 - Static weak-observer hub

Model: gpt-5.3-codex
Result: Pass (4 passed, 0 failed, 0 skipped)
Artifact directory: CustomAgentLogsTmp/PRState/38744/PRAgent/try-fix/attempt-1
Detailed report: CustomAgentLogsTmp/PRState/38744/PRAgent/try-fix-1/content.md
Inline expert self-review: 0 findings
Restore: EstablishBrokenBaseline.ps1 -Restore reported Restored True.

Approach

Replace each figure's direct collection subscription with a static
ConditionalWeakTable<PathSegmentCollection, SegmentCollectionObservers>.
Each shared collection holds one static CollectionChanged handler. Its
observer list contains only WeakReference<PathFigure> entries and dispatches
collection changes to live figures, pruning dead entries as it goes.

Mechanism-level difference

The PR uses a per-instance WeakNotifyCollectionChangedProxy, cached instance
delegate, and finalizer. Candidate 1 instead removes the instance event target
at the publisher: the collection strongly references only a static handler,
while the dispatch table weakly references figures. It therefore does not rely
on the PR's proxy or finalizer lifecycle.

Changed file

  • src/Controls/src/Core/Shapes/PathFigure.cs

Captured diff

diff --git a/src/Controls/src/Core/Shapes/PathFigure.cs b/src/Controls/src/Core/Shapes/PathFigure.cs
index 622e5aa204..aca0aa4a5a 100644
--- a/src/Controls/src/Core/Shapes/PathFigure.cs
+++ b/src/Controls/src/Core/Shapes/PathFigure.cs
@@ -3,6 +3,7 @@ using System;
 using System.Collections.Specialized;
 using System.Collections.Generic;
 using System.ComponentModel;
+using System.Runtime.CompilerServices;
 using Microsoft.Maui.Controls.Internals;
 using Microsoft.Maui.Graphics;
 
@@ -14,6 +15,8 @@ namespace Microsoft.Maui.Controls.Shapes
 	[ContentProperty("Segments")]
 	public sealed class PathFigure : BindableObject, IAnimatable
 	{
+		static readonly ConditionalWeakTable<PathSegmentCollection, SegmentCollectionObservers> s_segmentCollectionObservers = new();
+
 		readonly List<PathSegment> _subscribedSegments = new();
 
@@ -98,14 +101,14 @@ namespace Microsoft.Maui.Controls.Shapes
 		void UpdatePathSegmentCollection(PathSegmentCollection oldCollection, PathSegmentCollection newCollection)
 		{
-			oldCollection?.CollectionChanged -= OnPathSegmentCollectionChanged;
+			UnsubscribeFromSegmentCollection(oldCollection);
 
 			UnsubscribeFromAllPathSegmentPropertyChanged();
 
 			if (newCollection == null)
 				return;
 
-			newCollection.CollectionChanged += OnPathSegmentCollectionChanged;
+			SubscribeToSegmentCollection(newCollection);
 
 			foreach (var newPathSegment in newCollection)
 			{
@@ -198,5 +201,99 @@ namespace Microsoft.Maui.Controls.Shapes
 		{
 			InvalidatePathSegmentRequested?.Invoke(this, EventArgs.Empty);
 		}
+
+		void SubscribeToSegmentCollection(PathSegmentCollection collection)
+		{
+			var observers = s_segmentCollectionObservers.GetValue(collection, CreateSegmentCollectionObservers);
+			observers.Add(this);
+		}
+
+		void UnsubscribeFromSegmentCollection(PathSegmentCollection collection)
+		{
+			if (collection == null)
+				return;
+
+			if (!s_segmentCollectionObservers.TryGetValue(collection, out var observers))
+				return;
+
+			if (observers.Remove(this))
+			{
+				collection.CollectionChanged -= OnAnySegmentCollectionChanged;
+				s_segmentCollectionObservers.Remove(collection);
+			}
+		}
+
+		static SegmentCollectionObservers CreateSegmentCollectionObservers(PathSegmentCollection collection)
+		{
+			collection.CollectionChanged += OnAnySegmentCollectionChanged;
+			return new SegmentCollectionObservers();
+		}
+
+		static void OnAnySegmentCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
+		{
+			if (sender is not PathSegmentCollection segments)
+				return;
+
+			if (!s_segmentCollectionObservers.TryGetValue(segments, out var observers))
+				return;
+
+			if (observers.NotifyAll(segments, e))
+			{
+				segments.CollectionChanged -= OnAnySegmentCollectionChanged;
+				s_segmentCollectionObservers.Remove(segments);
+			}
+		}
+
+		sealed class SegmentCollectionObservers
+		{
+			readonly List<WeakReference<PathFigure>> _observers = new();
+
+			public void Add(PathFigure figure)
+			{
+				for (int i = _observers.Count - 1; i >= 0; i--)
+				{
+					if (!_observers[i].TryGetTarget(out var existingFigure))
+					{
+						_observers.RemoveAt(i);
+						continue;
+					}
+
+					if (ReferenceEquals(existingFigure, figure))
+						return;
+				}
+
+				_observers.Add(new WeakReference<PathFigure>(figure));
+			}
+
+			public bool Remove(PathFigure figure)
+			{
+				for (int i = _observers.Count - 1; i >= 0; i--)
+				{
+					if (!_observers[i].TryGetTarget(out var existingFigure) || ReferenceEquals(existingFigure, figure))
+						_observers.RemoveAt(i);
+				}
+
+				return _observers.Count == 0;
+			}
+
+			public bool NotifyAll(object sender, NotifyCollectionChangedEventArgs e)
+			{
+				for (int i = _observers.Count - 1; i >= 0; i--)
+				{
+					if (_observers[i].TryGetTarget(out var figure))
+						figure.OnPathSegmentCollectionChanged(sender, e);
+					else
+						_observers.RemoveAt(i);
+				}
+
+				return _observers.Count == 0;
+			}
+		}
 	}
 }

Test result and analysis

The one allowed test execution passed all four
PathSharedResourcesMemoryLeakTests. The new leak regression passed because a
long-lived collection has no strong path to a figure. The three existing
shared geometry/transform regression tests also passed. No correction or
retest was needed.

Candidate 2

Model: gpt-5.6-sol
Result: Blocked (no implementation; tests not run)
Artifact directory: CustomAgentLogsTmp/PRState/38744/PRAgent/try-fix/attempt-2
Detailed report: CustomAgentLogsTmp/PRState/38744/PRAgent/try-fix-2/content.md
Inline expert self-review: 0 findings
Restore: EstablishBrokenBaseline.ps1 -Restore reported Restored True.

Approach considered

Use deterministic lifecycle cleanup rather than a weak event edge: retain the
ordinary CollectionChanged subscription only if an owner detach/dispose
boundary can reliably remove it.

Why blocked

PathFigure has no deterministic detach or disposal signal. Implementing one
requires changing an owner such as PathGeometry or changing
PathSegmentCollection, both outside the baseline allow-list. The alternatives
available within PathFigure.cs are not valid distinct candidates:

  • a weak closure, another weak-event helper, or WeakEventManager merely
    repackages the PR's weak-proxy mechanism;
  • a differently keyed static registry repeats Candidate 1's weak-observer hub;
  • cloning or ceasing to observe the assigned collection breaks shared-resource
    identity, mutation propagation, segment subscriptions, and invalidation.

No production diff was created. The allowed test was not run because, with no
candidate implementation, that would only execute the known-failing broken
baseline and repeat the prohibited gate verification.

Aggregate Result

Two candidates were attempted in the required order. Candidate 1 is a tested,
passing alternative with a distinct static weak-observer topology. Candidate 2
is honestly blocked by the one-file modification boundary rather than
duplicating either weak-edge design. The original PR fix and Candidate 1 remain
the two viable implementations represented by this phase.


📝 PR Finalize — Recommended Title & Description

Assessment: ✏️ Recommend updating — the current metadata overstates the submitted fix as covering shared collections generally and omits the added regression test and Reset cleanup.

Recommended title

PathFigure: Use a weak PathSegmentCollection change subscription

Recommended description

### Issue Details

When multiple `PathFigure` instances use the same `PathSegmentCollection`, the collection's `CollectionChanged` event subscription can keep those figures alive after they are otherwise no longer referenced. This can prevent garbage collection and increase memory usage when the scenario occurs repeatedly.

### Description of Change

- Added `WeakNotifyCollectionChangedProxy` to manage `PathSegmentCollection.CollectionChanged` subscriptions through a weak reference.
- Updated `PathFigure` finalization to unsubscribe the collection proxy.
- Updated collection subscription and unsubscription logic to use the proxy.
- Reused `UnsubscribeFromAllPathSegmentPropertyChanged()` when handling collection Reset notifications.
- Added `SharedPathSegmentCollection_DoesNotKeepPathFigureAlive` to `PathSharedResourcesMemoryLeakTests` to cover the collection-level retention path.

### Issues Fixed

Fixes #38718

**Tested the behavior in the following platforms.**
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac

| Before  | After  |
|---------|--------|
| **Android**<br> <video src="https://github.com/user-attachments/assets/c3a742a8-a8c8-4cec-a5d4-b2340fbe179a" width="300" height="600"> | **Android**<br> <video src="https://github.com/user-attachments/assets/f00c73ee-25ae-42f6-a0ad-23a5efd407d3" width="300" height="600"> |

🏁 Report — Final Recommendation

⚠️ Final Recommendation: REQUEST CHANGES

Winner: pr-plus-reviewer. The submitted PR correctly removes the direct PathSegmentCollection.CollectionChanged -> PathFigure retention edge, but it leaves the equally concrete PathSegment.PropertyChanged -> PathFigure edge whenever the shared collection is non-empty. The winning candidate extends the PR's existing weak-proxy pattern to the contained segments and is the only candidate validated with a non-empty shared collection.

Comparative ranking

Rank Candidate Implementation result Targeted validation Correctness and tradeoffs
1 pr-plus-reviewer Complete Pass: 4/4, run once with the regression strengthened to contain a LineSegment Fixes both collection-level and segment-level retention using repository-standard weak proxies. Preserves synchronous invalidation, duplicate-subscription avoidance, replacement, Reset, Add, and Remove behavior.
2 pr Complete but incomplete fix Trusted Gate Pass: 4/4 with the submitted empty-collection regression Small and idiomatic for the direct collection edge, but a rooted non-empty collection still retains the figure through each segment's strong PropertyChanged handler. The test cannot see that path.
3 try-fix-1 Complete alternative Pass: 4/4 with the same empty-collection regression Its static ConditionalWeakTable observer hub also breaks only the collection-level edge. It leaves the segment-level leak untouched while adding substantially more static dispatch and bookkeeping than the PR.
4 try-fix-2 Blocked; no diff Not run Correctly determined that deterministic cleanup cannot be implemented safely within PathFigure without a lifecycle boundary, but produced no candidate implementation.

Expert findings against the submitted PR

  1. Blocking — non-empty collections still leak. A rooted collection retains its segments; each segment strongly retains PathFigure.OnPathSegmentPropertyChanged. Because this path keeps the figure alive, the submitted PathFigure finalizer never gets an opportunity to remove those handlers.
  2. Blocking — the regression is under-specified. The test constructs an empty PathSegmentCollection, so it validates only the collection proxy and never executes the segment subscription loop.

The required raw inline findings are stored in inline-findings.json, and the initial independent evaluation is stored in expert-pr-eval/content.md.

Why pr-plus-reviewer wins

The candidate is a surgical continuation of the submitted design rather than a replacement architecture. WeakNotifyPropertyChangedProxy is existing Controls infrastructure and already has adjacent Shapes prior art in GeometryGroup. The strengthened test simultaneously protects the original collection-level fix and the previously missed segment-level edge. Its single required validation run passed all four focused memory-leak regressions from the correct sandbox.

Required PR change

Apply pr-plus-reviewer/reviewer.patch to the submitted PR. Until the segment subscriptions and regression input are updated, the PR's advertised shared-collection leak guarantee is not met.


📱 UI Tests — Shape

Detected UI test categories: Shape

✅ Deep UI tests — 61 passed, 0 failed across 1 category on platform-pool agent (replaces in-process counts above).

🧪 UI Test Execution Results (deep, platform pool)

Category Tests Snapshot diffs
Shape 61/61 ✓ —
📎 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 submitted PR fixes only the collection-level event edge, while pr-plus-reviewer also weakens the segment-level PropertyChanged subscriptions that retain PathFigure for non-empty shared collections. Its strengthened focused regression and all three adjacent tests passed in the required sandbox.

Address the actionable findings in this review before merging.

@MauiBot MauiBot added s/agent-fix-win AI found a better alternative fix than the PR and removed s/agent-fix-pr-picked AI could not beat the PR fix - PR is the best among all candidates s/agent-review-in-progress AI review is currently running for this PR labels Sep 24, 2026
@kubaflo

This comment has been minimized.

@github-actions

Copy link
Copy Markdown
Contributor

Tests Failure Analysis

@devanathan-vaithiyanathan — test-failure analysis for commit 3c6b113.

Scope CI failures Commit 3c6b113


🧪 CI Analysis — click to expand
📊 maui-pr

No failures found.


🧪 maui-pr-devicetests

🧪 maui-pr-uitests
  • 🟢 Likely unrelated — Android SafeArea failures repeat the same assertions on main; this PR changes only PathFigure collection subscriptions.
  • 🟢 Likely unrelated — recurring visual deltas in Android navigation and Windows text color / uppercase match target-branch results exactly.
  • 🟢 Likely unrelated — Mac layout and Shell leak failures recur with the same reasons on main.
  • 🟢 Likely unrelated — Controls Entry failed DNS resolution for dev.azure.com, an external infrastructure error.
  • 🟡 Needs human investigation — the iOS inset assertion and remaining canceled/exit-code-only UI legs lack comparable platform-specific diagnostics; inspect or rerun those legs.

🧭 Follow-up — actions and refresh

Next action: Rerun the incomplete device work items and unresolved UI legs; investigate only if the same failures persist with complete diagnostics.

Maintainers: comment /review tests to refresh this report.

@kubaflo
kubaflo changed the base branch from main to inflight/current September 24, 2026 17:21
@kubaflo
kubaflo merged commit a140ff6 into dotnet:inflight/current Sep 24, 2026
194 of 207 checks passed
@github-actions github-actions Bot added this to the .NET 10 SR12 milestone 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!

### Issue Details
When multiple PathFigure instances use the same PathSegmentCollection,
the CollectionChanged event subscription can keep the PathFigure
instances alive even after they are no longer referenced.
This can prevent the PathFigure objects from being garbage collected and
may result in increasing memory usage when this scenario occurs
repeatedly.

### Description of Change

<!-- Enter description of the fix in this section -->
* Added WeakNotifyCollectionChangedProxy to manage
PathSegmentCollection.CollectionChanged subscriptions using a weak
reference.
* Updated PathFigure finalization to unsubscribe the collection proxy
when the PathFigure is finalized.
* Updated the collection subscription and unsubscription logic to use
the proxy.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

Fixes #38718 

<!--
Are you targeting main? All PRs should target the main branch unless
otherwise noted.
-->

 **Tested the behavior in the following platforms.**
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac

| Before  | After  |
|---------|--------|
| **Android**<br> <video
src="https://github.com/user-attachments/assets/c3a742a8-a8c8-4cec-a5d4-b2340fbe179a"
width="300" height="600"> | **Android**<br> <video
src="https://github.com/user-attachments/assets/f00c73ee-25ae-42f6-a0ad-23a5efd407d3"
width="300" height="600"> |
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!

### Issue Details
When multiple PathFigure instances use the same PathSegmentCollection,
the CollectionChanged event subscription can keep the PathFigure
instances alive even after they are no longer referenced.
This can prevent the PathFigure objects from being garbage collected and
may result in increasing memory usage when this scenario occurs
repeatedly.

### Description of Change

<!-- Enter description of the fix in this section -->
* Added WeakNotifyCollectionChangedProxy to manage
PathSegmentCollection.CollectionChanged subscriptions using a weak
reference.
* Updated PathFigure finalization to unsubscribe the collection proxy
when the PathFigure is finalized.
* Updated the collection subscription and unsubscription logic to use
the proxy.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

Fixes #38718 

<!--
Are you targeting main? All PRs should target the main branch unless
otherwise noted.
-->

 **Tested the behavior in the following platforms.**
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac

| Before  | After  |
|---------|--------|
| **Android**<br> <video
src="https://github.com/user-attachments/assets/c3a742a8-a8c8-4cec-a5d4-b2340fbe179a"
width="300" height="600"> | **Android**<br> <video
src="https://github.com/user-attachments/assets/f00c73ee-25ae-42f6-a0ad-23a5efd407d3"
width="300" height="600"> |
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!

### Issue Details
When multiple PathFigure instances use the same PathSegmentCollection,
the CollectionChanged event subscription can keep the PathFigure
instances alive even after they are no longer referenced.
This can prevent the PathFigure objects from being garbage collected and
may result in increasing memory usage when this scenario occurs
repeatedly.

### Description of Change

<!-- Enter description of the fix in this section -->
* Added WeakNotifyCollectionChangedProxy to manage
PathSegmentCollection.CollectionChanged subscriptions using a weak
reference.
* Updated PathFigure finalization to unsubscribe the collection proxy
when the PathFigure is finalized.
* Updated the collection subscription and unsubscription logic to use
the proxy.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

Fixes #38718 

<!--
Are you targeting main? All PRs should target the main branch unless
otherwise noted.
-->

 **Tested the behavior in the following platforms.**
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac

| Before  | After  |
|---------|--------|
| **Android**<br> <video
src="https://github.com/user-attachments/assets/c3a742a8-a8c8-4cec-a5d4-b2340fbe179a"
width="300" height="600"> | **Android**<br> <video
src="https://github.com/user-attachments/assets/f00c73ee-25ae-42f6-a0ad-23a5efd407d3"
width="300" height="600"> |
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!

### Issue Details
When multiple PathFigure instances use the same PathSegmentCollection,
the CollectionChanged event subscription can keep the PathFigure
instances alive even after they are no longer referenced.
This can prevent the PathFigure objects from being garbage collected and
may result in increasing memory usage when this scenario occurs
repeatedly.

### Description of Change

<!-- Enter description of the fix in this section -->
* Added WeakNotifyCollectionChangedProxy to manage
PathSegmentCollection.CollectionChanged subscriptions using a weak
reference.
* Updated PathFigure finalization to unsubscribe the collection proxy
when the PathFigure is finalized.
* Updated the collection subscription and unsubscription logic to use
the proxy.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

Fixes #38718 

<!--
Are you targeting main? All PRs should target the main branch unless
otherwise noted.
-->

 **Tested the behavior in the following platforms.**
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac

| Before  | After  |
|---------|--------|
| **Android**<br> <video
src="https://github.com/user-attachments/assets/c3a742a8-a8c8-4cec-a5d4-b2340fbe179a"
width="300" height="600"> | **Android**<br> <video
src="https://github.com/user-attachments/assets/f00c73ee-25ae-42f6-a0ad-23a5efd407d3"
width="300" height="600"> |
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!

### Issue Details
When multiple PathFigure instances use the same PathSegmentCollection,
the CollectionChanged event subscription can keep the PathFigure
instances alive even after they are no longer referenced.
This can prevent the PathFigure objects from being garbage collected and
may result in increasing memory usage when this scenario occurs
repeatedly.

### Description of Change

<!-- Enter description of the fix in this section -->
* Added WeakNotifyCollectionChangedProxy to manage
PathSegmentCollection.CollectionChanged subscriptions using a weak
reference.
* Updated PathFigure finalization to unsubscribe the collection proxy
when the PathFigure is finalized.
* Updated the collection subscription and unsubscription logic to use
the proxy.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

Fixes #38718 

<!--
Are you targeting main? All PRs should target the main branch unless
otherwise noted.
-->

 **Tested the behavior in the following platforms.**
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac

| Before  | After  |
|---------|--------|
| **Android**<br> <video
src="https://github.com/user-attachments/assets/c3a742a8-a8c8-4cec-a5d4-b2340fbe179a"
width="300" height="600"> | **Android**<br> <video
src="https://github.com/user-attachments/assets/f00c73ee-25ae-42f6-a0ad-23a5efd407d3"
width="300" height="600"> |
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!

### Issue Details
When multiple PathFigure instances use the same PathSegmentCollection,
the CollectionChanged event subscription can keep the PathFigure
instances alive even after they are no longer referenced.
This can prevent the PathFigure objects from being garbage collected and
may result in increasing memory usage when this scenario occurs
repeatedly.

### Description of Change

<!-- Enter description of the fix in this section -->
* Added WeakNotifyCollectionChangedProxy to manage
PathSegmentCollection.CollectionChanged subscriptions using a weak
reference.
* Updated PathFigure finalization to unsubscribe the collection proxy
when the PathFigure is finalized.
* Updated the collection subscription and unsubscription logic to use
the proxy.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

Fixes #38718 

<!--
Are you targeting main? All PRs should target the main branch unless
otherwise noted.
-->

 **Tested the behavior in the following platforms.**
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac

| Before  | After  |
|---------|--------|
| **Android**<br> <video
src="https://github.com/user-attachments/assets/c3a742a8-a8c8-4cec-a5d4-b2340fbe179a"
width="300" height="600"> | **Android**<br> <video
src="https://github.com/user-attachments/assets/f00c73ee-25ae-42f6-a0ad-23a5efd407d3"
width="300" height="600"> |
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!

### Issue Details
When multiple PathFigure instances use the same PathSegmentCollection,
the CollectionChanged event subscription can keep the PathFigure
instances alive even after they are no longer referenced.
This can prevent the PathFigure objects from being garbage collected and
may result in increasing memory usage when this scenario occurs
repeatedly.

### Description of Change

<!-- Enter description of the fix in this section -->
* Added WeakNotifyCollectionChangedProxy to manage
PathSegmentCollection.CollectionChanged subscriptions using a weak
reference.
* Updated PathFigure finalization to unsubscribe the collection proxy
when the PathFigure is finalized.
* Updated the collection subscription and unsubscription logic to use
the proxy.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

Fixes #38718 

<!--
Are you targeting main? All PRs should target the main branch unless
otherwise noted.
-->

 **Tested the behavior in the following platforms.**
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac

| Before  | After  |
|---------|--------|
| **Android**<br> <video
src="https://github.com/user-attachments/assets/c3a742a8-a8c8-4cec-a5d4-b2340fbe179a"
width="300" height="600"> | **Android**<br> <video
src="https://github.com/user-attachments/assets/f00c73ee-25ae-42f6-a0ad-23a5efd407d3"
width="300" height="600"> |
@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 — 3c6b113a Deployed Sep 21, 2026 by devanathan-vaithiyanathan via conclusion #2000
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

area-drawing Shapes, Borders, Shadows, Graphics, BoxView, custom drawing 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-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.

[leak-scan] PathFigure.Segments — shared collection strongly retains path figure

5 participants