Skip to content

[leak-fix] Fix TableView.Root memory leak (Fixes #36355) - #36513

Merged
kubaflo merged 11 commits into
inflight/currentfrom
leak-fix/issue-36355-155a29deb8a54c3d
Jul 16, 2026
Merged

kubaflo merged 11 commits into
inflight/currentfrom
leak-fix/issue-36355-155a29deb8a54c3d

Conversation

@github-actions

@github-actions github-actions Bot commented Jul 11, 2026 •

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!

Note

🔍 AI-generated PR. This fix and its regression tests were produced by the Memory Leak Fixer workflow. Please review carefully before merging.

Fixes #36355

Problem

A long-lived or shared TableRoot kept its owning TableView alive. TableSectionModel subscribed instance handlers directly to collection, section, and property-change events on the root, so those strong subscriptions retained the TableView. Reassigning Root was the only teardown path. A shared TableSection could also retain a dropped TableRoot through the root's direct section event handlers.

Fix

TableRoot now owns a WeakEventManager and exposes internal weak notification surfaces for root collection changes, child-section collection changes, and title changes. TableSectionModel subscribes directly to those weak events and explicitly moves its subscriptions when Root changes.

Section collection/property notifications now use weak proxies owned by a private finalizable subscription helper. TableRoot retains the handler delegates while alive, duplicate sections share one subscription, and the private holder always unsubscribes remaining proxies when finalized. Keeping finalization on the private holder avoids adding a tracked TableRoot.~TableRoot() public API entry. This prevents both a shared root retaining a dropped TableView and a shared section retaining a dropped TableRoot.

Regression tests

TableViewUnitTests covers:

  • setter and constructor assignment with a shared TableRoot
  • collection of a dropped TableView while the root remains alive
  • root collection, section collection, root-title, and section-title notifications after forced GC for both assignment paths
  • complete detachment from the old root and attachment to the replacement root for both constructor and property-setter initial assignment paths
  • section indexer replacement detaches the old section and subscribes the replacement section
  • a rooted/shared TableSection does not retain a dropped TableRoot

The focused TableViewUnitTests suite passes with 16 tests on net10.0.

Scope

Managed cross-platform change under src/Controls. No public API additions.

Generated by Memory Leak Fixer

A long-lived or shared TableRoot kept its owning TableView alive because
TableSectionModel and the TableView.Root setter subscribed instance
handlers (targeting the TableView) directly to the TableRoot's
CollectionChanged, SectionCollectionChanged, and PropertyChanged events.
Those subscriptions rooted the TableView from the shared TableRoot with no
teardown path other than reassigning Root.

Route all three subscriptions through weak event proxies
(WeakNotifyCollectionChangedProxy, WeakNotifyPropertyChangedProxy, and a
new WeakSectionCollectionChangedProxy) owned by TableSectionModel, with a
finalizer that unsubscribes. This also removes a duplicate
SectionCollectionChanged subscription that previously fired twice.

Generated by the Memory Leak Fixer agentic workflow.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@github-actions github-actions Bot added agentic-workflows perf/memory-leak 💦 Memory usage grows / objects live forever (sub: perf) labels Jul 11, 2026
@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 Jul 11, 2026
@MauiBot MauiBot added 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) labels Jul 11, 2026
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 Jul 11, 2026
@kubaflo

kubaflo commented Jul 11, 2026

Copy link
Copy Markdown
Contributor

🔍 AI-generated update (GitHub Copilot CLI, on behalf of @kubaflo)

@MauiBot No unresolved actionable code suggestions were found at the current head. Requesting a fresh improved-reviewer pass.

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

This comment has been minimized.

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

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: bbcdaa9d-d75a-4e3b-b375-cf827a689644
@github-actions

Copy link
Copy Markdown
Contributor Author

🚀 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 -- 36513

Or

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

@kubaflo

kubaflo commented Jul 11, 2026

Copy link
Copy Markdown
Contributor

🔍 AI-generated update (GitHub Copilot CLI, on behalf of @kubaflo)

@MauiBot All three findings are addressed in 978337fccf: both root-assignment paths are covered, all three proxy instances are verified collectible, and constructor ModelChanged forwarding is locked down. The PR description is current and the focused suite passes. Ready for re-review.

@kubaflo

This comment has been minimized.

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 Jul 11, 2026
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: bbcdaa9d-d75a-4e3b-b375-cf827a689644
@kubaflo

kubaflo commented Jul 11, 2026

Copy link
Copy Markdown
Contributor

🔍 AI-generated update (GitHub Copilot CLI, on behalf of @kubaflo)

@MauiBot The stale-proxy cleanup warning was already addressed in 978337fccf. The remaining behavior-retention suggestion is now covered in fdb59de111: all three weak-event channels are verified after GC for constructor and setter roots, and root replacement verifies complete old-source detachment. The description is current. Ready for re-review.

@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 Jul 11, 2026
MauiBot

This comment was marked as outdated.

@kubaflo

kubaflo commented Jul 12, 2026

Copy link
Copy Markdown
Contributor

🔍 AI-generated response (GitHub Copilot CLI, on behalf of @kubaflo)

@MauiBot The latest review found no current code issues. The live description and head fdb59de111 already cover proxy cleanup, after-GC delivery for all three event channels, and old-root detachment on replacement. No no-op commit or duplicate trigger was posted.

@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

@github-actions[bot] — new AI review results are available based on this last commit: 8eaa3d4. To request a fresh review after new comments or commits, comment /review rerun.

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: 0395a53b

Test Without Fix (expect FAIL) With Fix (expect PASS)
🧪 TableViewUnitTests TableViewUnitTests ✅ FAIL — 136s ✅ PASS — 126s
🔴 Without fix — 🧪 TableViewUnitTests: FAIL ✅ · 136s

(truncated to last 15,000 chars)

rols.Xaml.csproj (in 688 ms).
  Restored /home/vsts/work/1/s/src/TestUtils/src/TestUtils/TestUtils.csproj (in 6 ms).
  Restored /home/vsts/work/1/s/src/Graphics/src/Graphics/Graphics.csproj (in 12 ms).
  Restored /home/vsts/work/1/s/src/Essentials/src/Essentials.csproj (in 27 ms).
  Restored /home/vsts/work/1/s/src/Core/maps/src/Maps.csproj (in 33 ms).
  Restored /home/vsts/work/1/s/src/Core/src/Core.csproj (in 66 ms).
  1 of 10 projects are up-to-date for restore.
  ##vso[build.updatebuildnumber]10.0.100-ci+azdo.14646868
  Graphics -> /home/vsts/work/1/s/artifacts/bin/Graphics/Debug/net10.0/Microsoft.Maui.Graphics.dll
  ##vso[build.updatebuildnumber]10.0.100-ci+azdo.14646868
  Essentials -> /home/vsts/work/1/s/artifacts/bin/Essentials/Debug/net10.0/Microsoft.Maui.Essentials.dll
  ##vso[build.updatebuildnumber]10.0.100-ci+azdo.14646868
  Core -> /home/vsts/work/1/s/artifacts/bin/Core/Debug/net10.0/Microsoft.Maui.dll
  Controls.BindingSourceGen -> /home/vsts/work/1/s/artifacts/bin/Controls.BindingSourceGen/Debug/netstandard2.0/Microsoft.Maui.Controls.BindingSourceGen.dll
  ##vso[build.updatebuildnumber]10.0.100-ci+azdo.14646868
  ##vso[build.updatebuildnumber]10.0.100-ci+azdo.14646868
  Controls.Core -> /home/vsts/work/1/s/artifacts/bin/Controls.Core/Debug/net10.0/Microsoft.Maui.Controls.dll
  ##vso[build.updatebuildnumber]10.0.100-ci+azdo.14646868
  Controls.Xaml -> /home/vsts/work/1/s/artifacts/bin/Controls.Xaml/Debug/net10.0/Microsoft.Maui.Controls.Xaml.dll
  Maps -> /home/vsts/work/1/s/artifacts/bin/Maps/Debug/net10.0/Microsoft.Maui.Maps.dll
  ##vso[build.updatebuildnumber]10.0.100-ci+azdo.14646868
  Controls.Maps -> /home/vsts/work/1/s/artifacts/bin/Controls.Maps/Debug/net10.0/Microsoft.Maui.Controls.Maps.dll
  TestUtils -> /home/vsts/work/1/s/artifacts/bin/TestUtils/Debug/netstandard2.0/Microsoft.Maui.TestUtils.dll
  Controls.Core.UnitTests -> /home/vsts/work/1/s/artifacts/bin/Controls.Core.UnitTests/Debug/net10.0/Microsoft.Maui.Controls.Core.UnitTests.dll
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.1 (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.0)
[xUnit.net 00:00:00.24]   Discovering: Microsoft.Maui.Controls.Core.UnitTests
[xUnit.net 00:00:02.54]   Discovered:  Microsoft.Maui.Controls.Core.UnitTests
[xUnit.net 00:00:02.57]   Starting:    Microsoft.Maui.Controls.Core.UnitTests
[xUnit.net 00:00:02.82]     RootChangesStillRaiseModelChangedAfterGc(useConstructor: True) [FAIL]
[xUnit.net 00:00:02.84]       Assert.Equal() Failure: Values differ
[xUnit.net 00:00:02.84]       Expected: 4
[xUnit.net 00:00:02.84]       Actual:   2
[xUnit.net 00:00:02.84]       Stack Trace:
[xUnit.net 00:00:02.84]         /_/src/Controls/tests/Core.UnitTests/TableViewUnitTests.cs(173,0): at Microsoft.Maui.Controls.Core.UnitTests.TableViewUnitTests.RootChangesStillRaiseModelChangedAfterGc(Boolean useConstructor)
[xUnit.net 00:00:02.84]         --- End of stack trace from previous location ---
[xUnit.net 00:00:02.85]     RootChangesStillRaiseModelChangedAfterGc(useConstructor: False) [FAIL]
[xUnit.net 00:00:02.85]       Assert.Equal() Failure: Values differ
[xUnit.net 00:00:02.85]       Expected: 4
[xUnit.net 00:00:02.85]       Actual:   5
[xUnit.net 00:00:02.85]       Stack Trace:
[xUnit.net 00:00:02.85]         /_/src/Controls/tests/Core.UnitTests/TableViewUnitTests.cs(173,0): at Microsoft.Maui.Controls.Core.UnitTests.TableViewUnitTests.RootChangesStillRaiseModelChangedAfterGc(Boolean useConstructor)
[xUnit.net 00:00:02.85]         --- End of stack trace from previous location ---
  Passed BindingsContextChainsToModel [50 ms]
  Failed RootChangesStillRaiseModelChangedAfterGc(useConstructor: True) [92 ms]
  Error Message:
   Assert.Equal() Failure: Values differ
Expected: 4
Actual:   2
  Stack Trace:
     at Microsoft.Maui.Controls.Core.UnitTests.TableViewUnitTests.RootChangesStillRaiseModelChangedAfterGc(Boolean useConstructor) in /_/src/Controls/tests/Core.UnitTests/TableViewUnitTests.cs:line 173
--- End of stack trace from previous location ---
  Failed RootChangesStillRaiseModelChangedAfterGc(useConstructor: False) [41 ms]
  Error Message:
   Assert.Equal() Failure: Values differ
Expected: 4
Actual:   5
  Stack Trace:
     at Microsoft.Maui.Controls.Core.UnitTests.TableViewUnitTests.RootChangesStillRaiseModelChangedAfterGc(Boolean useConstructor) in /_/src/Controls/tests/Core.UnitTests/TableViewUnitTests.cs:line 173
--- End of stack trace from previous location ---
[xUnit.net 00:00:04.72]       TableView should not be alive!
[xUnit.net 00:00:04.72]     RootedTableRootDoesNotLeakTableView(useConstructor: True) [FAIL]
[xUnit.net 00:00:04.72]       Stack Trace:
[xUnit.net 00:00:04.72]         /_/src/Controls/tests/Core.UnitTests/TableViewUnitTests.cs(127,0): at Microsoft.Maui.Controls.Core.UnitTests.TableViewUnitTests.RootedTableRootDoesNotLeakTableView(Boolean useConstructor)
[xUnit.net 00:00:04.72]         --- End of stack trace from previous location ---
  Failed RootedTableRootDoesNotLeakTableView(useConstructor: True) [1 s]
  Error Message:
   TableView should not be alive!
  Stack Trace:
     at Microsoft.Maui.Controls.Core.UnitTests.TableViewUnitTests.RootedTableRootDoesNotLeakTableView(Boolean useConstructor) in /_/src/Controls/tests/Core.UnitTests/TableViewUnitTests.cs:line 127
--- End of stack trace from previous location ---
[xUnit.net 00:00:06.09]     RootedTableRootDoesNotLeakTableView(useConstructor: False) [FAIL]
[xUnit.net 00:00:06.09]       TableView should not be alive!
[xUnit.net 00:00:06.09]       Stack Trace:
[xUnit.net 00:00:06.09]         /_/src/Controls/tests/Core.UnitTests/TableViewUnitTests.cs(127,0): at Microsoft.Maui.Controls.Core.UnitTests.TableViewUnitTests.RootedTableRootDoesNotLeakTableView(Boolean useConstructor)
[xUnit.net 00:00:06.09]         --- End of stack trace from previous location ---
[xUnit.net 00:00:06.10]     ReplacingSectionMovesEventSubscriptions [FAIL]
[xUnit.net 00:00:06.10]       Assert.Equal() Failure: Values differ
[xUnit.net 00:00:06.10]       Expected: 2
[xUnit.net 00:00:06.10]       Actual:   1
[xUnit.net 00:00:06.10]       Stack Trace:
[xUnit.net 00:00:06.10]         /_/src/Controls/tests/Core.UnitTests/TableViewUnitTests.cs(253,0): at Microsoft.Maui.Controls.Core.UnitTests.TableViewUnitTests.ReplacingSectionMovesEventSubscriptions()
[xUnit.net 00:00:06.10]            at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)
[xUnit.net 00:00:06.10]            at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)
[xUnit.net 00:00:06.12]     ClearMovesSectionEventSubscriptions [FAIL]
[xUnit.net 00:00:06.12]       Assert.Equal() Failure: Values differ
[xUnit.net 00:00:06.12]       Expected: 0
[xUnit.net 00:00:06.12]       Actual:   1
[xUnit.net 00:00:06.12]       Stack Trace:
[xUnit.net 00:00:06.12]         /_/src/Controls/tests/Core.UnitTests/TableViewUnitTests.cs(221,0): at Microsoft.Maui.Controls.Core.UnitTests.TableViewUnitTests.ClearMovesSectionEventSubscriptions()
[xUnit.net 00:00:06.12]            at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)
[xUnit.net 00:00:06.12]            at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)
[xUnit.net 00:00:07.54]     RootedTableSectionDoesNotLeakTableRoot [FAIL]
[xUnit.net 00:00:07.54]       TableRoot should not be alive!
[xUnit.net 00:00:07.54]       Stack Trace:
[xUnit.net 00:00:07.54]         /_/src/Controls/tests/Core.UnitTests/TableViewUnitTests.cs(150,0): at Microsoft.Maui.Controls.Core.UnitTests.TableViewUnitTests.RootedTableSectionDoesNotLeakTableRoot()
[xUnit.net 00:00:07.54]         --- End of stack trace from previous location ---
[xUnit.net 00:00:07.54]     RootReplacementMovesEventSubscriptions(useConstructor: True) [FAIL]
[xUnit.net 00:00:07.54]       Assert.Equal() Failure: Values differ
[xUnit.net 00:00:07.54]       Expected: 3
[xUnit.net 00:00:07.54]       Actual:   4
[xUnit.net 00:00:07.54]       Stack Trace:
[xUnit.net 00:00:07.54]         /_/src/Controls/tests/Core.UnitTests/TableViewUnitTests.cs(203,0): at Microsoft.Maui.Controls.Core.UnitTests.TableViewUnitTests.RootReplacementMovesEventSubscriptions(Boolean useConstructor)
[xUnit.net 00:00:07.54]            at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)
[xUnit.net 00:00:07.54]            at System.Reflection.MethodBaseInvoker.InvokeDirectByRefWithFewArgs(Object obj, Span`1 copyOfArgs, BindingFlags invokeAttr)
  Failed RootedTableRootDoesNotLeakTableView(useConstructor: False) [1 s]
  Error Message:
   TableView should not be alive!
  Stack Trace:
     at Microsoft.Maui.Controls.Core.UnitTests.TableViewUnitTests.RootedTableRootDoesNotLeakTableView(Boolean useConstructor) in /_/src/Controls/tests/Core.UnitTests/TableViewUnitTests.cs:line 127
--- End of stack trace from previous location ---
  Passed TestModelChanged [< 1 ms]
  Failed ReplacingSectionMovesEventSubscriptions [3 ms]
  Error Message:
   Assert.Equal() Failure: Values differ
Expected: 2
Actual:   1
  Stack Trace:
     at Microsoft.Maui.Controls.Core.UnitTests.TableViewUnitTests.ReplacingSectionMovesEventSubscriptions() in /_/src/Controls/tests/Core.UnitTests/TableViewUnitTests.cs:line 253
   at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)
   at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)
  Passed ParentsViewCells [17 ms]
  Passed ParentsAddedViewCells [< 1 ms]
  Failed ClearMovesSectionEventSubscriptions [1 ms]
  Error Message:
   Assert.Equal() Failure: Values differ
Expected: 0
Actual:   1
  Stack Trace:
     at Microsoft.Maui.Controls.Core.UnitTests.TableViewUnitTests.ClearMovesSectionEventSubscriptions() in /_/src/Controls/tests/Core.UnitTests/TableViewUnitTests.cs:line 221
   at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)
   at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)
  Passed TestConstructor [4 ms]
  Failed RootedTableSectionDoesNotLeakTableRoot [1 s]
  Error Message:
   TableRoot should not be alive!
  Stack Trace:
     at Microsoft.Maui.Controls.Core.UnitTests.TableViewUnitTests.RootedTableSectionDoesNotLeakTableRoot() in /_/src/Controls/tests/Core.UnitTests/TableViewUnitTests.cs:line 150
--- End of stack trace from previous location ---
  Failed RootReplacementMovesEventSubscriptions(useConstructor: True) [< 1 ms]
  Error Message:
   Assert.Equal() Failure: Values differ
Expected: 3
Actual:   4
  Stack Trace:
     at Microsoft.Maui.Controls.Core.UnitTests.TableViewUnitTests.RootReplacementMovesEventSubscriptions(Boolean useConstructor) in /_/src/Controls/tests/Core.UnitTests/TableViewUnitTests.cs:line 203
   at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)
   at System.Reflection.MethodBaseInvoker.InvokeDirectByRefWithFewArgs(Object obj, Span`1 copyOfArgs, BindingFlags invokeAttr)
[xUnit.net 00:00:07.54]       Assert.Equal() Failure: Values differ
[xUnit.net 00:00:07.54]       Expected: 3
[xUnit.net 00:00:07.54]       Actual:   4
[xUnit.net 00:00:07.54]       Stack Trace:
[xUnit.net 00:00:07.54]         /_/src/Controls/tests/Core.UnitTests/TableViewUnitTests.cs(203,0): at Microsoft.Maui.Controls.Core.UnitTests.TableViewUnitTests.RootReplacementMovesEventSubscriptions(Boolean useConstructor)
[xUnit.net 00:00:07.54]            at InvokeStub_TableViewUnitTests.RootReplacementMovesEventSubscriptions(Object, Span`1)
[xUnit.net 00:00:07.54]            at System.Reflection.MethodBaseInvoker.InvokeWithOneArg(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
[xUnit.net 00:00:07.54]     RootReplacementMovesEventSubscriptions(useConstructor: False) [FAIL]
[xUnit.net 00:00:07.57]     DuplicateSectionsShareSubscriptionUntilLastRemoval [FAIL]
[xUnit.net 00:00:07.57]       Assert.Equal() Failure: Values differ
[xUnit.net 00:00:07.57]       Expected: 2
[xUnit.net 00:00:07.57]       Actual:   1
[xUnit.net 00:00:07.57]       Stack Trace:
[xUnit.net 00:00:07.57]         /_/src/Controls/tests/Core.UnitTests/TableViewUnitTests.cs(275,0): at Microsoft.Maui.Controls.Core.UnitTests.TableViewUnitTests.DuplicateSectionsShareSubscriptionUntilLastRemoval()
[xUnit.net 00:00:07.57]            at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)
[xUnit.net 00:00:07.57]            at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)
[xUnit.net 00:00:09.02]     ClearedSectionDoesNotRetainTableRoot [FAIL]
[xUnit.net 00:00:09.02]       TableRoot should not be alive!
[xUnit.net 00:00:09.02]       Stack Trace:
[xUnit.net 00:00:09.02]         /_/src/Controls/tests/Core.UnitTests/TableViewUnitTests.cs(140,0): at Microsoft.Maui.Controls.Core.UnitTests.TableViewUnitTests.ClearedSectionDoesNotRetainTableRoot()
[xUnit.net 00:00:09.02]         --- End of stack trace from previous location ---
[xUnit.net 00:00:09.04]   Finished:    Microsoft.Maui.Controls.Core.UnitTests
  Failed RootReplacementMovesEventSubscriptions(useConstructor: False) [2 ms]
  Error Message:
   Assert.Equal() Failure: Values differ
Expected: 3
Actual:   4
  Stack Trace:
     at Microsoft.Maui.Controls.Core.UnitTests.TableViewUnitTests.RootReplacementMovesEventSubscriptions(Boolean useConstructor) in /_/src/Controls/tests/Core.UnitTests/TableViewUnitTests.cs:line 203
   at InvokeStub_TableViewUnitTests.RootReplacementMovesEventSubscriptions(Object, Span`1)
   at System.Reflection.MethodBaseInvoker.InvokeWithOneArg(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
  Failed DuplicateSectionsShareSubscriptionUntilLastRemoval [5 ms]
  Error Message:
   Assert.Equal() Failure: Values differ
Expected: 2
Actual:   1
  Stack Trace:
     at Microsoft.Maui.Controls.Core.UnitTests.TableViewUnitTests.DuplicateSectionsShareSubscriptionUntilLastRemoval() in /_/src/Controls/tests/Core.UnitTests/TableViewUnitTests.cs:line 275
   at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)
   at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)
  Failed ClearedSectionDoesNotRetainTableRoot [1 s]
  Error Message:
   TableRoot should not be alive!
  Stack Trace:
     at Microsoft.Maui.Controls.Core.UnitTests.TableViewUnitTests.ClearedSectionDoesNotRetainTableRoot() in /_/src/Controls/tests/Core.UnitTests/TableViewUnitTests.cs:line 140
--- End of stack trace from previous location ---

Test Run Failed.
Total tests: 16
     Passed: 5
     Failed: 11
 Total time: 9.8890 Seconds

🟢 With fix — 🧪 TableViewUnitTests: PASS ✅ · 126s
  Determining projects to restore...
  All projects are up-to-date for restore.
  ##vso[build.updatebuildnumber]10.0.100-ci+azdo.14646868
  Graphics -> /home/vsts/work/1/s/artifacts/bin/Graphics/Debug/net10.0/Microsoft.Maui.Graphics.dll
  ##vso[build.updatebuildnumber]10.0.100-ci+azdo.14646868
  Essentials -> /home/vsts/work/1/s/artifacts/bin/Essentials/Debug/net10.0/Microsoft.Maui.Essentials.dll
  ##vso[build.updatebuildnumber]10.0.100-ci+azdo.14646868
  Core -> /home/vsts/work/1/s/artifacts/bin/Core/Debug/net10.0/Microsoft.Maui.dll
  Controls.BindingSourceGen -> /home/vsts/work/1/s/artifacts/bin/Controls.BindingSourceGen/Debug/netstandard2.0/Microsoft.Maui.Controls.BindingSourceGen.dll
  ##vso[build.updatebuildnumber]10.0.100-ci+azdo.14646868
  ##vso[build.updatebuildnumber]10.0.100-ci+azdo.14646868
  Maps -> /home/vsts/work/1/s/artifacts/bin/Maps/Debug/net10.0/Microsoft.Maui.Maps.dll
  Controls.Core -> /home/vsts/work/1/s/artifacts/bin/Controls.Core/Debug/net10.0/Microsoft.Maui.Controls.dll
  ##vso[build.updatebuildnumber]10.0.100-ci+azdo.14646868
  Controls.Xaml -> /home/vsts/work/1/s/artifacts/bin/Controls.Xaml/Debug/net10.0/Microsoft.Maui.Controls.Xaml.dll
  ##vso[build.updatebuildnumber]10.0.100-ci+azdo.14646868
  Controls.Maps -> /home/vsts/work/1/s/artifacts/bin/Controls.Maps/Debug/net10.0/Microsoft.Maui.Controls.Maps.dll
  TestUtils -> /home/vsts/work/1/s/artifacts/bin/TestUtils/Debug/netstandard2.0/Microsoft.Maui.TestUtils.dll
  Controls.Core.UnitTests -> /home/vsts/work/1/s/artifacts/bin/Controls.Core.UnitTests/Debug/net10.0/Microsoft.Maui.Controls.Core.UnitTests.dll
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.1 (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.0)
[xUnit.net 00:00:00.42]   Discovering: Microsoft.Maui.Controls.Core.UnitTests
[xUnit.net 00:00:03.12]   Discovered:  Microsoft.Maui.Controls.Core.UnitTests
[xUnit.net 00:00:03.15]   Starting:    Microsoft.Maui.Controls.Core.UnitTests
  Passed BindingsContextChainsToModel [59 ms]
  Passed RootChangesStillRaiseModelChangedAfterGc(useConstructor: True) [90 ms]
  Passed RootChangesStillRaiseModelChangedAfterGc(useConstructor: False) [59 ms]
  Passed RootedTableRootDoesNotLeakTableView(useConstructor: True) [93 ms]
  Passed RootedTableRootDoesNotLeakTableView(useConstructor: False) [84 ms]
  Passed TestModelChanged [< 1 ms]
  Passed ReplacingSectionMovesEventSubscriptions [3 ms]
  Passed ParentsViewCells [26 ms]
  Passed ParentsAddedViewCells [< 1 ms]
[xUnit.net 00:00:03.85]   Finished:    Microsoft.Maui.Controls.Core.UnitTests
  Passed ClearMovesSectionEventSubscriptions [3 ms]
  Passed TestConstructor [7 ms]
  Passed RootedTableSectionDoesNotLeakTableRoot [93 ms]
  Passed RootReplacementMovesEventSubscriptions(useConstructor: True) [< 1 ms]
  Passed RootReplacementMovesEventSubscriptions(useConstructor: False) [3 ms]
  Passed DuplicateSectionsShareSubscriptionUntilLastRemoval [1 ms]
  Passed ClearedSectionDoesNotRetainTableRoot [44 ms]

Test Run Successful.
Total tests: 16
     Passed: 16
 Total time: 4.9421 Seconds

📁 Fix files reverted (2 files)
  • src/Controls/src/Core/TableView/TableRoot.cs
  • src/Controls/src/Core/TableView/TableView.cs

📱 UI Tests — TableView

Detected UI test categories: TableView

[!WARNING]
No UI test results were produced for the detected categories. The platform-pool run
returned no results — most often because the PR build failed (see the Gate section) or
the deep UI test stage was skipped. Fix the build/gate issues and comment /review rerun
to get UI test results.


📋 Pre-Flight — Context & Validation

Issue: #36355 - [leak-scan] TableView.Root: shared TableRoot strongly roots the TableView via SectionCollectionChanged/PropertyChanged
PR: #36513 - [leak-fix] Fix TableView.Root memory leak (Fixes #36355)
Platforms Affected: Managed cross-platform src/Controls; test platform requested: android
Files Changed: 2 implementation, 1 test

Key Findings

  • The issue reports a managed retention path where a long-lived/shared TableRoot keeps a dropped TableView alive through strong SectionCollectionChanged and PropertyChanged subscriptions; a shared TableSection can similarly retain a dropped TableRoot if section event handlers are strong.
  • The PR's current fix moves root-to-table notifications to TableRoot-owned weak event surfaces and section-to-root notifications to weak proxies owned by a private finalizable subscription holder.
  • Prior inline reviews raised concerns about constructor coverage, reset/clear cleanup, duplicate sections, shared section retention, and finalizer complexity; the current head has tests/changes addressing those comments.
  • Gate result supplied by the caller: ✅ PASSED — regression tests fail without the fix and pass with the PR fix. Gate was not re-run.
  • GitHub CLI is unauthenticated in this environment, so PR/issue context was gathered from public REST endpoints and the checked-out PR branch.

Code Review Summary

Verdict: NEEDS_DISCUSSION
Confidence: low
Errors: 0 | Warnings: 0 | Suggestions: 0

Key code review findings:

  • ℹ Independent code review found no current actionable implementation findings.
  • ℹ CI status is undetermined here because authenticated gh pr checks --required is unavailable; this caps the code-review verdict confidence.

Fix Candidates

# Source Approach Test Result Files Changed Notes
PR PR #36513 TableRoot publishes weak root events; section subscriptions use weak proxies with tracked cleanup for reset/replacement/duplicates ✅ PASSED (Gate) TableRoot.cs, TableView.cs, TableViewUnitTests.cs Original PR

🔬 Code Review — Deep Analysis

Code Review — PR #36513

Independent Assessment

What this changes: Replaces strong TableRoot/TableSection event subscriptions with weak-event/proxy-based subscriptions to avoid retaining dropped TableView/TableRoot instances, and adds regression tests.
Inferred motivation: Fix memory leaks when shared/long-lived TableRoot or TableSection outlives the view/root that subscribed to it.

Reconciliation with PR Narrative

Author claims: Fixes TableView.Root leak, adds weak notification surfaces and tests.
Agreement/disagreement: Matches the code. No disagreement found.

Prior Review Reconciliation

Prior ❌ Error Finding Source Status Evidence
Shared TableSection retained dropped TableRoot via strong delegates MauiBot inline [major] ✅ Fixed Current TableRoot uses WeakNotifyCollectionChangedProxy / WeakNotifyPropertyChangedProxy; RootedTableSectionDoesNotLeakTableRoot covers it.
Leak test did not validate prior proxy cleanup path MauiBot inline [major] 🔄 Obsolete / ✅ Fixed Current root→table path uses WeakEventManager; tests cover GC and post-GC notifications.

Blast Radius Assessment

  • Runs for all instances: yes — all TableView roots use the new weak event path.
  • Startup impact: no.
  • Static/shared state: no.

CI Status

  • Required-check result: pending / undetermined.
  • Classification: gh pr checks --required unavailable due auth; focused local test evidence from prior gate is available.
  • Action taken: confidence capped low.

Findings

No ❌ Error, ⚠️ Warning, or 💡 Suggestion findings.

Failure-Mode Probing

  • Shared root outlives dropped TableView: weak root events no longer strongly retain the table.
  • Shared section outlives dropped TableRoot: weak proxies avoid section-to-root retention.
  • Root replacement: TableSectionModel.Root removes weak handlers from the old root and applies them to the new root.
  • Reset/clear/duplicate sections: subscription tracking handles reset and keeps duplicate section subscription until last removal.

Verdict: NEEDS_DISCUSSION

Confidence: low, because required CI is undetermined in this unauthenticated environment.
Summary: The code review found no actionable defects. Per the skill rules, this cannot be LGTM until required CI is complete and green.


🛠️ Fix — Analysis & Comparison

Fix Candidates

# Source Approach Test Result Files Changed Notes
1 try-fix-1 Model-owned weak section observation; TableRoot becomes a plain collection and TableSectionModel owns weak root/section proxies ✅ PASS TableRoot.cs, TableView.cs Not better: drops existing TableRoot.PropertyChanged forwarding for child TableSection.Title changes
2 try-fix-2 Section-scoped weak observer broker with weak root entries; keeps PR root-to-table weak event boundary ✅ PASS TableRoot.cs Not better: adds static broker/shared registry, locks, weak-list pruning, and broader lifecycle complexity
3 try-fix-3 Minimal weak parent in TableSectionModel; leaves TableRoot child-section subscriptions unchanged ❌ FAIL TableView.cs Incomplete: section-to-root leak, reset/clear stale handlers, and duplicate-section failures remain
PR PR #36513 TableRoot weak root events plus private holder-owned weak section proxies with reset/replacement/duplicate tracking ✅ PASSED (Gate) TableRoot.cs, TableView.cs, TableViewUnitTests.cs Original PR; selected

Candidate Details

try-fix-1

Approach: Model-owned weak section observation

Move root and section observation into TableSectionModel. TableRoot becomes a plain collection; TableSectionModel owns weak proxies to the current root and its sections, tracking reset/replacement/duplicates itself.

Different from PR: The PR makes TableRoot the weak event publisher for root notifications and stores section weak proxies in TableRoot. This candidate keeps all observation in the TableView model layer.

Test Results

Result: Pass

Command: dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --filter FullyQualifiedName~TableViewUnitTests --logger "console;verbosity=normal"

Focused result: 16/16 TableViewUnitTests passed on net10.0 in the isolated worktree.

Failure Analysis / Expert Review

Although the regression suite passes, this candidate is not demonstrably better than the PR. By removing child-section aggregation from TableRoot, it stops preserving the existing behavior where TableRoot.PropertyChanged is raised with TitleProperty when a child TableSection.Title changes. TableView still updates because the model observes sections directly, but external/internal observers of TableRoot.PropertyChanged would see a behavior change not required by the leak fix.

Diff

diff --git a/src/Controls/src/Core/TableView/TableRoot.cs b/src/Controls/src/Core/TableView/TableRoot.cs
index 7fc19ab1f9..bf7f395441 100644
--- a/src/Controls/src/Core/TableView/TableRoot.cs
+++ b/src/Controls/src/Core/TableView/TableRoot.cs
@@ -1,8 +1,4 @@
 #nullable disable
-using System;
-using System.Collections.Specialized;
-using System.ComponentModel;
-
 namespace Microsoft.Maui.Controls
 {
 	/// <summary>
@@ -26,45 +22,8 @@ namespace Microsoft.Maui.Controls
 			SetupEvents();
 		}
 
-		internal event EventHandler<ChildCollectionChangedEventArgs> SectionCollectionChanged;
-
-		void ChildCollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs)
-		{
-			EventHandler<ChildCollectionChangedEventArgs> handler = SectionCollectionChanged;
-			if (handler != null)
-				handler(this, new ChildCollectionChangedEventArgs(notifyCollectionChangedEventArgs));
-		}
-
-		void ChildPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs)
-		{
-			if (propertyChangedEventArgs.PropertyName == TitleProperty.PropertyName)
-			{
-				OnPropertyChanged(TitleProperty.PropertyName);
-			}
-		}
-
 		void SetupEvents()
 		{
-			CollectionChanged += (sender, args) =>
-			{
-				if (args.NewItems != null)
-				{
-					foreach (TableSection section in args.NewItems)
-					{
-						section.CollectionChanged += ChildCollectionChanged;
-						section.PropertyChanged += ChildPropertyChanged;
-					}
-				}
-
-				if (args.OldItems != null)
-				{
-					foreach (TableSection section in args.OldItems)
-					{
-						section.CollectionChanged -= ChildCollectionChanged;
-						section.PropertyChanged -= ChildPropertyChanged;
-					}
-				}
-			};
 		}
 	}
 }
\ No newline at end of file
diff --git a/src/Controls/src/Core/TableView/TableView.cs b/src/Controls/src/Core/TableView/TableView.cs
index b13cf38801..43903a5c5d 100644
--- a/src/Controls/src/Core/TableView/TableView.cs
+++ b/src/Controls/src/Core/TableView/TableView.cs
@@ -87,8 +87,6 @@ namespace Microsoft.Maui.Controls
 			{
 				if (_tableModel.Root != null)
 				{
-					_tableModel.Root.SectionCollectionChanged -= OnSectionCollectionChanged;
-					_tableModel.Root.PropertyChanged -= OnTableModelRootPropertyChanged;
 					VisualDiagnostics.OnChildRemoved(this, _tableModel.Root, 0);
 				}
 				_tableModel.Root = value ?? new TableRoot();
@@ -96,8 +94,6 @@ namespace Microsoft.Maui.Controls
 				SetInheritedBindingContext(_tableModel.Root, BindingContext);
 
 				Root.SelectMany(r => r).ForEach(cell => cell.Parent = this);
-				_tableModel.Root.SectionCollectionChanged += OnSectionCollectionChanged;
-				_tableModel.Root.PropertyChanged += OnTableModelRootPropertyChanged;
 				OnModelChanged();
 			}
 		}
@@ -192,7 +188,14 @@ namespace Microsoft.Maui.Controls
 			static readonly BindableProperty PathProperty = BindableProperty.Create("Path", typeof(Tuple<int, int>), typeof(Cell), null);
 
 			readonly TableView _parent;
+			readonly List<SectionSubscription> _sectionSubscriptions = new();
 			TableRoot _root;
+			WeakNotifyCollectionChangedProxy _rootCollectionChangedProxy;
+			WeakNotifyPropertyChangedProxy _rootPropertyChangedProxy;
+			NotifyCollectionChangedEventHandler _rootCollectionChangedHandler;
+			PropertyChangedEventHandler _rootPropertyChangedHandler;
+			NotifyCollectionChangedEventHandler _sectionCollectionChangedHandler;
+			PropertyChangedEventHandler _sectionPropertyChangedHandler;
 
 			public TableSectionModel(TableView tableParent, TableRoot tableRoot)
 			{
@@ -200,6 +203,11 @@ namespace Microsoft.Maui.Controls
 				Root = tableRoot ?? new TableRoot();

#### try-fix-2
## Approach: Section-scoped weak observer broker

Preserve `TableRoot` as the owner of child-section aggregation, including public `PropertyChanged` forwarding for child section title changes, but replace each section-to-root weak proxy pair with a shared section observer that stores weak references to observing roots.

**Different from PR:** The PR stores weak proxies per root-section subscription in a private holder. This candidate uses one broker/observer per `TableSection` and weak root entries, while keeping the PR root-to-TableView weak event boundary.

## Test Results

**Result:** Pass

Command: `dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --filter FullyQualifiedName~TableViewUnitTests --logger "console;verbosity=normal"`

Focused result: 16/16 `TableViewUnitTests` passed on `net10.0` in the isolated worktree.

## Failure Analysis / Expert Review

This candidate preserves `TableRoot` child-section aggregation semantics better than Candidate 1 and passes the focused regression suite. It is still not demonstrably better than the PR: the static `ConditionalWeakTable` broker, weak-root list pruning, locking, and per-section observer lifecycle are more complex than the PR-local private subscription holder. The PR fix keeps ownership localized to each `TableRoot`, whereas this candidate adds shared registry behavior and more edge cases around multiple roots observing the same section.

## Diff

```diff
diff --git a/src/Controls/src/Core/TableView/TableRoot.cs b/src/Controls/src/Core/TableView/TableRoot.cs
index dd929e58f3..d84e97b849 100644
--- a/src/Controls/src/Core/TableView/TableRoot.cs
+++ b/src/Controls/src/Core/TableView/TableRoot.cs
@@ -3,6 +3,7 @@ using System;
 using System.Collections.Generic;
 using System.Collections.Specialized;
 using System.ComponentModel;
+using System.Runtime.CompilerServices;
 using Microsoft.Maui;
 
 namespace Microsoft.Maui.Controls
@@ -105,7 +106,7 @@ namespace Microsoft.Maui.Controls
 
 		void SubscribeToSection(TableSection section)
 		{
-			var subscriptions = _sectionSubscriptions ??= new SectionSubscriptions();
+			var subscriptions = _sectionSubscriptions ??= new SectionSubscriptions(this);
 			if (subscriptions.Contains(section))
 				return;
 
@@ -125,9 +126,12 @@ namespace Microsoft.Maui.Controls
 		sealed class SectionSubscriptions
 		{
 			readonly List<SectionSubscription> _subscriptions = new();
+			readonly TableRoot _owner;
 
-			// Keep finalization private so TableRoot does not gain a public API finalizer entry.
-			~SectionSubscriptions() => UnsubscribeAll();
+			public SectionSubscriptions(TableRoot owner)
+			{
+				_owner = owner;
+			}
 
 			public bool Contains(TableSection source)
 			{
@@ -142,7 +146,7 @@ namespace Microsoft.Maui.Controls
 
 			public void Add(TableSection source, NotifyCollectionChangedEventHandler collectionChangedHandler, PropertyChangedEventHandler propertyChangedHandler)
 			{
-				_subscriptions.Add(new SectionSubscription(source, collectionChangedHandler, propertyChangedHandler));
+				_subscriptions.Add(new SectionSubscription(_owner, source));
 			}
 
 			public void Remove(TableSection source)
@@ -171,24 +175,142 @@ namespace Microsoft.Maui.Controls
 
 		sealed class SectionSubscription
 		{
-			readonly WeakNotifyCollectionChangedProxy _collectionChangedProxy;
-			readonly WeakNotifyPropertyChangedProxy _propertyChangedProxy;
+			readonly TableRoot _owner;
+			readonly TableSection _source;
 
-			public SectionSubscription(TableSection source, NotifyCollectionChangedEventHandler collectionChangedHandler, PropertyChangedEventHandler propertyChangedHandler)
+			public SectionSubscription(TableRoot owner, TableSection source)
 			{
-				_collectionChangedProxy = new WeakNotifyCollectionChangedProxy(source, collectionChangedHandler);
-				_propertyChangedProxy = new WeakNotifyPropertyChangedProxy(source, propertyChangedHandler);
+				_owner = owner;
+				_source = source;
+				SectionObserverBroker.Add(source, owner);
 			}
 
 			public bool IsSubscribedTo(TableSection source)
 			{
-				return _collectionChangedProxy.TryGetSource(out var proxySource) && ReferenceEquals(proxySource, source);
+				return ReferenceEquals(_source, source);
 			}
 
 			public void Unsubscribe()
 			{
-				_collectionChangedProxy.Unsubscribe();
-				_propertyChangedProxy.Unsubscribe();
+				SectionObserverBroker.Remove(_source, _owner);
+			}
+		}
+
+		static class SectionObserverBroker
+		{
+			static readonly ConditionalWeakTable<TableSection, SectionObservation> Observations = new();
+
+			public static void Add(TableSection section, TableRoot root)
+			{
+				Observations.GetValue(section, static source => new SectionObservation(source)).Add(root);
+			}
+
+			public static void Remove(TableSection section, TableRoot root)
+			{
+				if (Observations.TryGetValue(section, out var observation))
+					observation.RemoveDeadOrMatching(root);
+			}
+
+			sealed class SectionObservation
+			{
+				readonly TableSection _section;
+				readonly List<WeakReference<TableRoot>> _roots = new();
+				bool _subscribed;
+

#### try-fix-3
## Approach: Minimal weak parent in TableSectionModel

Keep `TableRoot` section aggregation as-is, but change `TableSectionModel` to be the root event subscriber and hold its parent `TableView` weakly. Root events should no longer retain the table; dead models unsubscribe on finalization or when callbacks find the parent gone.

**Different from PR:** This does not add weak events to `TableRoot` and does not change section-to-root subscriptions. It only breaks the model-to-view edge.

## Test Results

**Result:** Fail

Command: `dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --filter FullyQualifiedName~TableViewUnitTests --logger "console;verbosity=normal"`

Focused result: 12 passed, 4 failed.

Failures:
- `ClearMovesSectionEventSubscriptions`: expected 0, actual 2 after clearing a section; stale section handlers still notify the old root/table.
- `RootedTableSectionDoesNotLeakTableRoot`: shared section still retains dropped `TableRoot`.
- `DuplicateSectionsShareSubscriptionUntilLastRemoval`: duplicate section received double notifications after one removal.
- `ClearedSectionDoesNotRetainTableRoot`: cleared section still retains dropped `TableRoot`.

## Failure Analysis

The weak-parent approach breaks the direct `TableRoot` to `TableView` retention path, so shared-root leak tests pass. It deliberately leaves `TableRoot` subscribing to child sections with strong instance delegates and keeps baseline add/remove handling, so reset/clear, duplicate-section, and shared-section leak regressions remain. This confirms that a complete fix must address both root-to-table and section-to-root edges.

## Diff

```diff
diff --git a/src/Controls/src/Core/TableView/TableView.cs b/src/Controls/src/Core/TableView/TableView.cs
index b13cf38801..f5f6839ec6 100644
--- a/src/Controls/src/Core/TableView/TableView.cs
+++ b/src/Controls/src/Core/TableView/TableView.cs
@@ -87,8 +87,6 @@ namespace Microsoft.Maui.Controls
 			{
 				if (_tableModel.Root != null)
 				{
-					_tableModel.Root.SectionCollectionChanged -= OnSectionCollectionChanged;
-					_tableModel.Root.PropertyChanged -= OnTableModelRootPropertyChanged;
 					VisualDiagnostics.OnChildRemoved(this, _tableModel.Root, 0);
 				}
 				_tableModel.Root = value ?? new TableRoot();
@@ -96,8 +94,6 @@ namespace Microsoft.Maui.Controls
 				SetInheritedBindingContext(_tableModel.Root, BindingContext);
 
 				Root.SelectMany(r => r).ForEach(cell => cell.Parent = this);
-				_tableModel.Root.SectionCollectionChanged += OnSectionCollectionChanged;
-				_tableModel.Root.PropertyChanged += OnTableModelRootPropertyChanged;
 				OnModelChanged();
 			}
 		}
@@ -191,12 +187,12 @@ namespace Microsoft.Maui.Controls
 		{
 			static readonly BindableProperty PathProperty = BindableProperty.Create("Path", typeof(Tuple<int, int>), typeof(Cell), null);
 
-			readonly TableView _parent;
+			readonly WeakReference<TableView> _parent;
 			TableRoot _root;
 
 			public TableSectionModel(TableView tableParent, TableRoot tableRoot)
 			{
-				_parent = tableParent;
+				_parent = new WeakReference<TableView>(tableParent);
 				Root = tableRoot ?? new TableRoot();
 			}
 
@@ -263,8 +259,9 @@ namespace Microsoft.Maui.Controls
 
 			void ApplyEvents(TableRoot tableRoot)
 			{
-				tableRoot.CollectionChanged += _parent.CollectionChanged;
-				tableRoot.SectionCollectionChanged += _parent.OnSectionCollectionChanged;
+				tableRoot.CollectionChanged += OnRootCollectionChanged;
+				tableRoot.SectionCollectionChanged += OnRootSectionCollectionChanged;
+				tableRoot.PropertyChanged += OnRootPropertyChanged;
 			}
 
 			void RemoveEvents(TableRoot tableRoot)
@@ -272,8 +269,33 @@ namespace Microsoft.Maui.Controls
 				if (tableRoot == null)
 					return;
 
-				tableRoot.CollectionChanged -= _parent.CollectionChanged;
-				tableRoot.SectionCollectionChanged -= _parent.OnSectionCollectionChanged;
+				tableRoot.CollectionChanged -= OnRootCollectionChanged;
+				tableRoot.SectionCollectionChanged -= OnRootSectionCollectionChanged;
+				tableRoot.PropertyChanged -= OnRootPropertyChanged;
+			}
+
+			void OnRootCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
+			{
+				if (_parent.TryGetTarget(out var parent))
+					parent.CollectionChanged(sender, e);
+				else
+					RemoveEvents(_root);
+			}
+
+			void OnRootSectionCollectionChanged(object sender, ChildCollectionChangedEventArgs e)
+			{
+				if (_parent.TryGetTarget(out var parent))
+					parent.OnSectionCollectionChanged(sender, e);
+				else
+					RemoveEvents(_root);
+			}
+
+			void OnRootPropertyChanged(object sender, PropertyChangedEventArgs e)
+			{
+				if (_parent.TryGetTarget(out var parent))
+					parent.OnTableModelRootPropertyChanged(sender, e);
+				else
+					RemoveEvents(_root);
 			}
 
 			static void SetPath(Cell item, Tuple<int, int> index)

Cross-Pollination

Model/Reviewer Round New Ideas? Details
maui-expert-reviewer 1 Yes Proposed model-owned observation, weak relay/broker, minimal weak-parent, broader TableSectionBase weak infrastructure, and lifecycle detach.
maui-expert-reviewer 2 Yes After Candidate 1, proposed section-scoped weak observer broker to preserve TableRoot aggregation semantics.
maui-expert-reviewer 3 No After three tested candidates, confirmed no remaining materially different approach is likely better than the PR.

Exhausted: Yes
Selected Fix: PR #36513 — it is the only approach that passes the focused gate while preserving existing aggregation semantics and keeping the weak-subscription complexity private/localized instead of moving it into broader model ownership or shared broker infrastructure.


🏁 Report — Final Recommendation

Comparative Report — PR #36513

Candidates

Rank Candidate Regression result Assessment
1 pr ✅ Passed gate Best balance of correctness, behavior preservation, and localized complexity. Fixes both root-to-table and section-to-root retention while preserving TableRoot child-section aggregation semantics.
1 pr-plus-reviewer ✅ Same as PR Expert reviewer produced no actionable findings, so this candidate is identical to pr.
3 try-fix-2 ✅ Passed focused tests Preserves aggregation semantics, but adds a static ConditionalWeakTable broker/shared registry, locking, weak-root pruning, and broader lifecycle complexity. Not better than the PR-local subscription holder.
4 try-fix-1 ✅ Passed focused tests Moves observation into TableSectionModel, but drops existing TableRoot.PropertyChanged forwarding for child TableSection.Title changes. That is an unnecessary behavior change.
5 try-fix-3 ❌ Failed focused tests Incomplete. It only weakens the model-to-view edge and leaves section-to-root leaks, reset/clear stale handlers, and duplicate-section behavior failures. Per ranking rule, failed candidates rank below passing candidates.

Key comparison

try-fix-3 is eliminated because it failed the regression suite. try-fix-1 and try-fix-2 passed the focused tests, but each introduces avoidable tradeoffs: try-fix-1 changes observable TableRoot aggregation behavior, while try-fix-2 introduces shared/static broker complexity. The PR fix keeps ownership localized to TableRoot, preserves existing aggregation semantics, and directly covers duplicate sections, reset/replacement, shared-root retention, and shared-section retention.

The expert reviewer produced no actionable findings, so pr-plus-reviewer does not differ from pr. The winning candidate is therefore the raw PR fix as submitted.

Winner

Winner: pr

Rationale: The PR fix is the highest-ranked passing candidate because it fully addresses the leak paths while preserving existing behavior and avoiding the extra static/shared lifecycle complexity of the strongest alternative.


🧭 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 Jul 14, 2026
@kubaflo

kubaflo commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

🔍 AI-generated review follow-up (GitHub Copilot CLI, on behalf of @kubaflo)

@MauiBot Review 4690847401 found no errors, warnings, or suggestions on current head 8eaa3d42529, confirmed the prior reset/duplicate/shared-section/finalizer concerns are addressed, and selected the submitted private SectionSubscriptions holder as the best fix after testing three alternatives. No code change is needed. Ready for re-review.

@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added s/agent-review-in-progress AI review is currently running for this PR and removed s/agent-review-in-progress AI review is currently running for this PR labels Jul 14, 2026
kubaflo pushed a commit that referenced this pull request Jul 14, 2026
…ories, not just build failures

Extends the deep build-failed rendering (9896b61) to close a second silent
gap. A category whose HostApp BUILDS successfully but whose test run is then
hard-killed (per-category time-budget exhaustion, an emulator/Appium hang, or a
crash) writes NO .trx — so it is absent from $byCat AND is not a build failure
(build-output.log shows 'Build and deploy completed'). Before this change such a
category vanished entirely from the deep summary even though the stage was
honestly amber, leaving the reviewer with no explanation.

Observed on build 14646868 (#36513, android): the TableView category built in
9 min, started 'dotnet test', then ran 41 min and was hard-killed at the 50-min
budget (exit 124) with 0 TRX. TableView is normally a fast 25-test category
(green on earlier builds 14632923/14633282), so this was an infra hang, not
test volume — correctly caught by honest-amber, but silently missing from the
summary block.

Fix: the trx-less category scan now also classifies categories whose
build-output.log shows the build completed / the test run started ('Build and
deploy completed', 'Running UI tests with category', 'Executing: dotnet test')
as $interruptedCats, and renders an honest note ('built and started but
produced no results — interrupted; usually an infrastructure flake; re-run')
in both the mixed path and the all-empty standalone path. Additive/guarded; the
build-failed path is unchanged (elseif). Adds no ${{ }} to the 28KB block.

Validated: whole-file YAML parse OK; no ${{ }}-bearing block exceeds 21000;
9-case standalone test against the REAL 14646868 TableView artifact (interrupted)
and 14647102 Picker artifact (build-failed) + a clean synthetic run — all green.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 15d2af20-e4ab-4e88-9011-cfbd83513bc0
@kubaflo

kubaflo commented Jul 15, 2026

Copy link
Copy Markdown
Contributor

/azp run

@azure-pipelines

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

@kubaflo

kubaflo commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

🔍 AI-generated merge-readiness analysis (GitHub Copilot CLI, on behalf of @kubaflo)

Good for merge from the automated review/CI perspective. All failures are proven unrelated to the TableView.Root changes:

No PR-attributable failure remains. This PR is still a draft, so it must be marked ready for review before GitHub can merge it.

@kubaflo

This comment has been minimized.

@github-actions

Copy link
Copy Markdown
Contributor Author

Tests Failure Analysis

@kubaflo — test-failure review results are available based on commit 8eaa3d4.
To request a fresh review after new comments, commits, or CI runs, comment /review tests.

Overall Not ready Failures 24 Regressed vs base 2 Baseline 2 on base

Test Failure Review: Not ready - click to expand

Overall verdict: Not ready. Two build legs are deterministic regressions versus main (red on the PR, green on all 5 recent base builds sampled per definition), and the remaining 22 failures — a missing build-task import, 11 unexplained Controls UITest build legs, flaky CollectionView timeouts, a cancelled macOS leg, and 7 unconfirmed device-test checks — could not be attributed deterministically, so none can be dismissed as pre-existing.

  • ✗ PR-related — Build/artifact legs regressed vs base (~2 legs): DeviceTestsWindows (Windows) - build error and the publish-artifacts leg are red on the PR but green across all 5 recent main builds; both surface as infra-style errors (PowerShell exit 1, file-upload retry failure), so confirm whether they are genuinely PR-induced.
  • i Uncertain — Missing build-task import & unexplained build legs (~13 legs): Build Microsoft.Maui.sln fails with MSB4024 (missing Microsoft.Maui.Core.After.targets, demoted by ci-scan [ci-scan] Recurring: Build macOS (Debug) agent abandoned mid-build in maui-pr #36115) and 11 Controls UITest build legs produced no extractable failure.
  • i Uncertain — Flaky CollectionView UITest timeouts (~15 tests): header/scroll UITests time out, flagged flaky-on-base and linked to [ci-scan] Recurring: Android API 30 emulator fails to boot in maui-pr-uitests — all Controls (API 30) legs blocked #36489; e.g. VerifyHeaderViewWhenHeaderTemplateView.
  • i Uncertain — Aborted/unverified checks (~8 checks): the macOS Controls CollectionView UITest leg was CANCELLED and 7 green device-test checks could not be positively confirmed Failed==0 (XHarness exits 0 even on failure).
  • i Uncertain — Assertion & provisioning failures (~2): ThumbImageSourceSizeIsCorrect size assertion (expected 18, actual 100) and the Android SDK platform-tools;35.0.2 provisioning error.

Coverage: 162 checks · 154 passing · 8 failing · 0 pending · 0 inaccessible · 1 unmapped · 11 unexplained build legs · 0 unaccounted failing checks · 1 aborted failing checks · 0 canceled-build checks · 7 device-test unverified · 22 unattributed · 2 regressed-vs-base. Deterministic ceiling: Not ready — 2 legs are red on the PR but green on all sampled base builds.

Builds (this PR): maui-pr 1511362, maui-pr-devicetests 1511376, maui-pr-uitests 1511369. Base sampling (main, 5 recent builds per definition): 1503430, 1503431, 1503618.

Recommended action

Needs human investigation before merge: confirm whether the two regressed-vs-base build/artifact legs are PR-induced or infra flakes, and re-run the cancelled macOS UITest and unconfirmed device-test checks to clear the ceiling.

@kubaflo

kubaflo commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

🔍 AI-generated follow-up analysis (GitHub Copilot CLI, on behalf of @kubaflo)

The /review tests deterministic-regression classification is unsupported; no failure is proven PR-caused.

No TableView code change is required. The draft remains good for merge from the automated code/CI perspective.

@kubaflo
kubaflo marked this pull request as ready for review July 16, 2026 12:43
Copilot AI review requested due to automatic review settings July 16, 2026 12:43
@kubaflo
kubaflo changed the base branch from main to inflight/current July 16, 2026 12:43
@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
kubaflo merged commit adef19a into inflight/current Jul 16, 2026
150 of 164 checks passed
@kubaflo
kubaflo deleted the leak-fix/issue-36355-155a29deb8a54c3d branch July 16, 2026 12:44
@github-actions github-actions Bot added this to the .NET 10 SR10 milestone Jul 16, 2026

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.

Pull request overview

Fixes a managed memory leak in TableView.Root when a TableRoot (or TableSection) is shared/long-lived by switching TableView’s root/section event wiring to weak-event patterns and ensuring section event proxies are unsubscribed when the owning root is collected.

Changes:

  • Updated TableView’s internal model to subscribe to TableRoot change notifications via new internal weak events instead of strong CLR events.
  • Enhanced TableRoot to publish weak notification surfaces (root collection, child section collection, and title changes) and to manage section subscriptions via weak proxies with a finalizer-backed cleanup path.
  • Added unit tests covering GC/leak scenarios and verifying model change notifications and subscription migration behavior.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated no comments.

File Description
src/Controls/tests/Core.UnitTests/TableViewUnitTests.cs Adds regression coverage for the shared-root/shared-section leak and validates event behavior after GC and root/section replacement.
src/Controls/src/Core/TableView/TableView.cs Switches TableView’s internal root wiring to TableRoot’s new weak events to avoid rooting dropped TableView instances.
src/Controls/src/Core/TableView/TableRoot.cs Introduces internal weak events and weak proxy-based section subscriptions (with finalizer cleanup) to prevent roots/sections from retaining each other.

kubaflo pushed a commit that referenced this pull request Jul 16, 2026
… on RS0016

The gate recompiles the MAUI product (Controls.Core, ...) from source via the
unit/XAML test project's P2P references, re-running the PublicAPI analyzer under
the repo-wide TreatWarningsAsErrors=true. A leak-fix PR that adds a finalizer
(e.g. #36605 ~SwipeView()) surfaces RS0016/RS0017 as a build-breaking ERROR
during the revert -> build -> restore -> build cycle, so the with-fix build fails
to compile and the gate reports a false FAILED — even though the PR's own maui-pr
build (a REQUIRED check that separately enforces PublicAPI bookkeeping) is green.

Many in-flight PRs are leak fixes that add finalizers (#36575, #36566, #36547,
#36531, #36526, #36521, #36513, ...), so ALL of them hit this false-FAILED.

Fix: pass -p:TreatWarningsAsErrors=false to the gate's unit/XAML dotnet test and
clean-rebuild-retry invocations, matching the deep stage's existing mitigation in
Build-AndDeploy.ps1. The gate verifies TEST BEHAVIOR, not API bookkeeping; genuine
CS-level compile ERRORS still fail the build. The UITest/device path already routes
through Build-AndDeploy.ps1 and was already covered.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 15d2af20-e4ab-4e88-9011-cfbd83513bc0
kubaflo added a commit that referenced this pull request Jul 22, 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!

> [!NOTE]
> 🔍 **AI-generated PR.** This fix and its regression tests were produced
by the Memory Leak Fixer workflow. Please review carefully before
merging.

Fixes #36355

## Problem

A long-lived or shared `TableRoot` kept its owning `TableView` alive.
`TableSectionModel` subscribed instance handlers directly to collection,
section, and property-change events on the root, so those strong
subscriptions retained the `TableView`. Reassigning `Root` was the only
teardown path. A shared `TableSection` could also retain a dropped
`TableRoot` through the root's direct section event handlers.

## Fix

`TableRoot` now owns a `WeakEventManager` and exposes internal weak
notification surfaces for root collection changes, child-section
collection changes, and title changes. `TableSectionModel` subscribes
directly to those weak events and explicitly moves its subscriptions
when `Root` changes.

Section collection/property notifications now use weak proxies owned by
a private finalizable subscription helper. `TableRoot` retains the
handler delegates while alive, duplicate sections share one
subscription, and the private holder always unsubscribes remaining
proxies when finalized. Keeping finalization on the private holder
avoids adding a tracked `TableRoot.~TableRoot()` public API entry. This
prevents both a shared root retaining a dropped `TableView` and a shared
section retaining a dropped `TableRoot`.

## Regression tests

`TableViewUnitTests` covers:

- setter and constructor assignment with a shared `TableRoot`
- collection of a dropped `TableView` while the root remains alive
- root collection, section collection, root-title, and section-title
notifications after forced GC for both assignment paths
- complete detachment from the old root and attachment to the
replacement root for both constructor and property-setter initial
assignment paths
- section indexer replacement detaches the old section and subscribes
the replacement section
- a rooted/shared `TableSection` does not retain a dropped `TableRoot`

The focused `TableViewUnitTests` suite passes with 16 tests on
`net10.0`.

## Scope

Managed cross-platform change under `src/Controls`. No public API
additions.

> Generated by [Memory Leak
Fixer](https://github.com/dotnet/maui/actions/runs/29133575104)

<!-- gh-aw-agentic-workflow: Memory Leak Fixer, engine: copilot,
version: 1.0.63, model: claude-opus-4.8, id: 29133575104, workflow_id:
leak-fixer, run: https://github.com/dotnet/maui/actions/runs/29133575104
-->

<!-- gh-aw-workflow-id: leak-fixer -->
<!-- gh-aw-workflow-call-id: dotnet/maui/leak-fixer -->

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
kubaflo added a commit that referenced this pull request Jul 28, 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!

> [!NOTE]
> 🔍 **AI-generated PR.** This fix and its regression tests were produced
by the Memory Leak Fixer workflow. Please review carefully before
merging.

Fixes #36355

## Problem

A long-lived or shared `TableRoot` kept its owning `TableView` alive.
`TableSectionModel` subscribed instance handlers directly to collection,
section, and property-change events on the root, so those strong
subscriptions retained the `TableView`. Reassigning `Root` was the only
teardown path. A shared `TableSection` could also retain a dropped
`TableRoot` through the root's direct section event handlers.

## Fix

`TableRoot` now owns a `WeakEventManager` and exposes internal weak
notification surfaces for root collection changes, child-section
collection changes, and title changes. `TableSectionModel` subscribes
directly to those weak events and explicitly moves its subscriptions
when `Root` changes.

Section collection/property notifications now use weak proxies owned by
a private finalizable subscription helper. `TableRoot` retains the
handler delegates while alive, duplicate sections share one
subscription, and the private holder always unsubscribes remaining
proxies when finalized. Keeping finalization on the private holder
avoids adding a tracked `TableRoot.~TableRoot()` public API entry. This
prevents both a shared root retaining a dropped `TableView` and a shared
section retaining a dropped `TableRoot`.

## Regression tests

`TableViewUnitTests` covers:

- setter and constructor assignment with a shared `TableRoot`
- collection of a dropped `TableView` while the root remains alive
- root collection, section collection, root-title, and section-title
notifications after forced GC for both assignment paths
- complete detachment from the old root and attachment to the
replacement root for both constructor and property-setter initial
assignment paths
- section indexer replacement detaches the old section and subscribes
the replacement section
- a rooted/shared `TableSection` does not retain a dropped `TableRoot`

The focused `TableViewUnitTests` suite passes with 16 tests on
`net10.0`.

## Scope

Managed cross-platform change under `src/Controls`. No public API
additions.

> Generated by [Memory Leak
Fixer](https://github.com/dotnet/maui/actions/runs/29133575104)

<!-- gh-aw-agentic-workflow: Memory Leak Fixer, engine: copilot,
version: 1.0.63, model: claude-opus-4.8, id: 29133575104, workflow_id:
leak-fixer, run: https://github.com/dotnet/maui/actions/runs/29133575104
-->

<!-- gh-aw-workflow-id: leak-fixer -->
<!-- gh-aw-workflow-call-id: dotnet/maui/leak-fixer -->

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
kubaflo added a commit that referenced this pull request Jul 29, 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!

> [!NOTE]
> 🔍 **AI-generated PR.** This fix and its regression tests were produced
by the Memory Leak Fixer workflow. Please review carefully before
merging.

Fixes #36355

## Problem

A long-lived or shared `TableRoot` kept its owning `TableView` alive.
`TableSectionModel` subscribed instance handlers directly to collection,
section, and property-change events on the root, so those strong
subscriptions retained the `TableView`. Reassigning `Root` was the only
teardown path. A shared `TableSection` could also retain a dropped
`TableRoot` through the root's direct section event handlers.

## Fix

`TableRoot` now owns a `WeakEventManager` and exposes internal weak
notification surfaces for root collection changes, child-section
collection changes, and title changes. `TableSectionModel` subscribes
directly to those weak events and explicitly moves its subscriptions
when `Root` changes.

Section collection/property notifications now use weak proxies owned by
a private finalizable subscription helper. `TableRoot` retains the
handler delegates while alive, duplicate sections share one
subscription, and the private holder always unsubscribes remaining
proxies when finalized. Keeping finalization on the private holder
avoids adding a tracked `TableRoot.~TableRoot()` public API entry. This
prevents both a shared root retaining a dropped `TableView` and a shared
section retaining a dropped `TableRoot`.

## Regression tests

`TableViewUnitTests` covers:

- setter and constructor assignment with a shared `TableRoot`
- collection of a dropped `TableView` while the root remains alive
- root collection, section collection, root-title, and section-title
notifications after forced GC for both assignment paths
- complete detachment from the old root and attachment to the
replacement root for both constructor and property-setter initial
assignment paths
- section indexer replacement detaches the old section and subscribes
the replacement section
- a rooted/shared `TableSection` does not retain a dropped `TableRoot`

The focused `TableViewUnitTests` suite passes with 16 tests on
`net10.0`.

## Scope

Managed cross-platform change under `src/Controls`. No public API
additions.

> Generated by [Memory Leak
Fixer](https://github.com/dotnet/maui/actions/runs/29133575104)

<!-- gh-aw-agentic-workflow: Memory Leak Fixer, engine: copilot,
version: 1.0.63, model: claude-opus-4.8, id: 29133575104, workflow_id:
leak-fixer, run: https://github.com/dotnet/maui/actions/runs/29133575104
-->

<!-- gh-aw-workflow-id: leak-fixer -->
<!-- gh-aw-workflow-call-id: dotnet/maui/leak-fixer -->

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
kubaflo added a commit that referenced this pull request Aug 7, 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!

> [!NOTE]
> 🔍 **AI-generated PR.** This fix and its regression tests were produced
by the Memory Leak Fixer workflow. Please review carefully before
merging.

Fixes #36355

## Problem

A long-lived or shared `TableRoot` kept its owning `TableView` alive.
`TableSectionModel` subscribed instance handlers directly to collection,
section, and property-change events on the root, so those strong
subscriptions retained the `TableView`. Reassigning `Root` was the only
teardown path. A shared `TableSection` could also retain a dropped
`TableRoot` through the root's direct section event handlers.

## Fix

`TableRoot` now owns a `WeakEventManager` and exposes internal weak
notification surfaces for root collection changes, child-section
collection changes, and title changes. `TableSectionModel` subscribes
directly to those weak events and explicitly moves its subscriptions
when `Root` changes.

Section collection/property notifications now use weak proxies owned by
a private finalizable subscription helper. `TableRoot` retains the
handler delegates while alive, duplicate sections share one
subscription, and the private holder always unsubscribes remaining
proxies when finalized. Keeping finalization on the private holder
avoids adding a tracked `TableRoot.~TableRoot()` public API entry. This
prevents both a shared root retaining a dropped `TableView` and a shared
section retaining a dropped `TableRoot`.

## Regression tests

`TableViewUnitTests` covers:

- setter and constructor assignment with a shared `TableRoot`
- collection of a dropped `TableView` while the root remains alive
- root collection, section collection, root-title, and section-title
notifications after forced GC for both assignment paths
- complete detachment from the old root and attachment to the
replacement root for both constructor and property-setter initial
assignment paths
- section indexer replacement detaches the old section and subscribes
the replacement section
- a rooted/shared `TableSection` does not retain a dropped `TableRoot`

The focused `TableViewUnitTests` suite passes with 16 tests on
`net10.0`.

## Scope

Managed cross-platform change under `src/Controls`. No public API
additions.

> Generated by [Memory Leak
Fixer](https://github.com/dotnet/maui/actions/runs/29133575104)

<!-- gh-aw-agentic-workflow: Memory Leak Fixer, engine: copilot,
version: 1.0.63, model: claude-opus-4.8, id: 29133575104, workflow_id:
leak-fixer, run: https://github.com/dotnet/maui/actions/runs/29133575104
-->

<!-- gh-aw-workflow-id: leak-fixer -->
<!-- gh-aw-workflow-call-id: dotnet/maui/leak-fixer -->

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
kubaflo added a commit that referenced this pull request Aug 12, 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!

> [!NOTE]
> 🔍 **AI-generated PR.** This fix and its regression tests were produced
by the Memory Leak Fixer workflow. Please review carefully before
merging.

Fixes #36355

## Problem

A long-lived or shared `TableRoot` kept its owning `TableView` alive.
`TableSectionModel` subscribed instance handlers directly to collection,
section, and property-change events on the root, so those strong
subscriptions retained the `TableView`. Reassigning `Root` was the only
teardown path. A shared `TableSection` could also retain a dropped
`TableRoot` through the root's direct section event handlers.

## Fix

`TableRoot` now owns a `WeakEventManager` and exposes internal weak
notification surfaces for root collection changes, child-section
collection changes, and title changes. `TableSectionModel` subscribes
directly to those weak events and explicitly moves its subscriptions
when `Root` changes.

Section collection/property notifications now use weak proxies owned by
a private finalizable subscription helper. `TableRoot` retains the
handler delegates while alive, duplicate sections share one
subscription, and the private holder always unsubscribes remaining
proxies when finalized. Keeping finalization on the private holder
avoids adding a tracked `TableRoot.~TableRoot()` public API entry. This
prevents both a shared root retaining a dropped `TableView` and a shared
section retaining a dropped `TableRoot`.

## Regression tests

`TableViewUnitTests` covers:

- setter and constructor assignment with a shared `TableRoot`
- collection of a dropped `TableView` while the root remains alive
- root collection, section collection, root-title, and section-title
notifications after forced GC for both assignment paths
- complete detachment from the old root and attachment to the
replacement root for both constructor and property-setter initial
assignment paths
- section indexer replacement detaches the old section and subscribes
the replacement section
- a rooted/shared `TableSection` does not retain a dropped `TableRoot`

The focused `TableViewUnitTests` suite passes with 16 tests on
`net10.0`.

## Scope

Managed cross-platform change under `src/Controls`. No public API
additions.

> Generated by [Memory Leak
Fixer](https://github.com/dotnet/maui/actions/runs/29133575104)

<!-- gh-aw-agentic-workflow: Memory Leak Fixer, engine: copilot,
version: 1.0.63, model: claude-opus-4.8, id: 29133575104, workflow_id:
leak-fixer, run: https://github.com/dotnet/maui/actions/runs/29133575104
-->

<!-- gh-aw-workflow-id: leak-fixer -->
<!-- gh-aw-workflow-call-id: dotnet/maui/leak-fixer -->

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

agentic-workflows perf/memory-leak 💦 Memory usage grows / objects live forever (sub: perf) 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

5 participants