Skip to content

fix(ItemsView): drop leaking DEBUG layout-invalidation diagnostics - #23632

Merged
MartinZikmund merged 6 commits into
masterfrom
dev/nr/alc-itemsview-debug-layout-leak
Jul 6, 2026
Merged

MartinZikmund merged 6 commits into
masterfrom
dev/nr/alc-itemsview-debug-layout-leak

Conversation

@nickrandolph

Copy link
Copy Markdown
Contributor

ALC pin-fix stack — PR 3 of 4 (uno). Base: dev/nr/alc-weak-type-keyed-caches. Next: U4 (TreeView prune) stacks on this branch.

Fixes #23631

Spec

In Debug builds, ItemsView.OnLayoutChangedDbg() (#if DEBUG) subscribed instance-method handlers to Layout.MeasureInvalidated / Layout.ArrangeInvalidated. The default style assigns Layout from a <Setter> whose value is a single shared <controls:StackLayout /> that lives for the whole process, so the subscription made that shared object strongly retain every ItemsView ever created:

  • a permanent per-control leak in every Debug-built app, and
  • an ALC pin for hosts that load plugin/preview apps into collectible AssemblyLoadContexts: the retained ItemsView holds DataContext / ItemsSource / template objects from the collectible ALC, so AssemblyLoadContext.Unload() never completes (GC-root path confirmed with ClrMD: default-style StackLayout → MeasureInvalidated invocation list → ItemsView → app-ALC objects).

The revokers were only disposed when LayoutProperty changed again — never on teardown ( ~ItemsView() and OnUnloaded don't touch them, and the finalizer can't run while the rooted Layout references the control; Unloaded also doesn't fire when a tree is discarded wholesale). Both handlers are empty no-ops — their trace calls are commented out — so the subscription had zero diagnostic value. Removing it is strictly a leak fix with no behavior change.

Implementation

  • src/Uno.UI/UI/Xaml/Controls/ItemsView/ItemsView.cs (+9/−8): in the #if DEBUG OnLayoutChangedDbg(), removed the if (Layout is { } layout) block that subscribed OnLayoutMeasureInvalidatedDbg / OnLayoutArrangeInvalidatedDbg and created the DisposableAction revokers. Replaced it with a comment explaining why the subscription is intentionally not created (shared style-Setter Layout outlives the control; instance-method handlers retain the control; OnUnloaded is not a reliable teardown hook) and instructing that any future restoration of the traces must use a weak handler. The m_layoutMeasureInvalidatedDbg.Disposable = null; / m_layoutArrangeInvalidatedDbg.Disposable = null; resets are kept, as are the (now-unsubscribed) no-op handler methods, minimizing divergence from the WinUI reference source.

Test plan

  • Red/green (existing test, no new code needed): Given_FrameworkElement_And_Leak.When_Add_Remove with the [ActivatableDataRow(typeof(ItemsView), 15)] row (src/Uno.UI.RuntimeTests/Tests/Windows_UI_Xaml/Given_FrameworkElement_And_Leak.cs:115). It materializes 15 ItemsView instances under the default (and UWP) styles, removes them, GC-pressures for up to 30 s, and asserts every tracked WeakReference dies. On a Debug-configuration Uno.UI build this row fails before this change (all instances retained by the shared default-style StackLayout) and passes after. Note the bug is #if DEBUG-only, so Release legs compile it out — which is why this row was always green on Release CI.
  • ALC scenario verification: reproduced and verified in a downstream host that loads preview apps into collectible ALCs — before the fix, ClrMD dump analysis showed the unloaded app ALC pinned via StackLayout.MeasureInvalidated → ItemsView; after the fix that root path is gone and the ALC weak reference collects.

Risks / rollback

  • Risk: effectively none — the removed handlers were empty no-ops (trace bodies commented out), so no diagnostic output is lost and no runtime behavior changes in Debug or Release. The change is confined to #if DEBUG code.
  • Rollback: revert the single commit. If the layout-invalidation traces are ever wanted again, re-subscribe via a weak event handler so a shared Layout cannot retain the ItemsView (called out in the in-code comment).

Copilot AI review requested due to automatic review settings July 3, 2026 13:15
@CLAassistant

CLAassistant commented Jul 3, 2026 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ MartinZikmund
❌ Nick Randolph


Nick Randolph seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account.
You have signed the CLA already but the status is still pending? Let us recheck it.

@mergify

mergify Bot commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

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

Removes DEBUG-only ItemsView layout-invalidation diagnostic event subscriptions that accidentally caused lifetime leaks when Layout is provided by a process-lifetime shared Style Setter value (notably pinning collectible AssemblyLoadContexts in debug-host scenarios).

Changes:

  • Eliminates subscriptions to Layout.MeasureInvalidated / Layout.ArrangeInvalidated from ItemsView.OnLayoutChangedDbg().
  • Keeps the existing revoker reset logic but replaces the subscription block with an explanatory comment warning future maintainers to use weak handlers if reintroducing diagnostics.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@nickrandolph
nickrandolph force-pushed the dev/nr/alc-weak-type-keyed-caches branch from 1cd1a4f to 91074fb Compare July 3, 2026 13:36
@nickrandolph
nickrandolph force-pushed the dev/nr/alc-itemsview-debug-layout-leak branch from e652e9f to 6d9aae0 Compare July 3, 2026 13:41
Nick Randolph and others added 5 commits July 6, 2026 17:36
The DEBUG-only OnLayoutChangedDbg subscribed this ItemsView (instance-method
handlers) to Layout.MeasureInvalidated / ArrangeInvalidated. When Layout is a
single instance shared via the default Style (a Setter value lives for the whole
process), those handlers kept every ItemsView ever created alive for the life of
the app - a real leak in Debug builds, and under collectible AssemblyLoadContexts
it pinned the entire app ALC. OnUnloaded cannot be relied on (it does not fire
when the tree is torn down wholesale during ALC unload).

The handlers are empty no-ops (their trace calls are commented out), so the
subscription provided no value. Remove it. If the traces are ever restored,
re-subscribe via a weak handler so a shared Layout cannot retain the ItemsView.
Addresses review feedback (#23631): with the leaking subscription
removed, OnLayoutMeasureInvalidatedDbg / OnLayoutArrangeInvalidatedDbg
were unreferenced private members and raised IDE0051 (warning) in Debug
builds. They were empty no-ops; removed them and left a note in
OnLayoutChangedDbg on how to restore the diagnostics via a weak handler.

Co-Authored-By: Claude Fable 5 <[email protected]>
The WinUI-derived collection-change handling removes m_itemToNodeMap entries
only on ItemRemoved with an expanded parent. A Reset (ItemsSource collection
Clear) removed the nodes from view but left every item -> node mapping behind,
retaining the cleared items for the TreeView's lifetime — and when items come
from a collectible AssemblyLoadContext (plugin / preview hosting), pinning that
ALC. Prune mappings whose node is no longer attached to the origin node on
Reset; also covers removals under a collapsed parent once any reset occurs.
Companion to the item-to-node map prune: a selected node removed via a
collection Reset stayed in m_selectedNodes / m_selectedItems indefinitely,
keeping the node and its item alive (dump-proven: a TreeView-based tool's
selection vector retained the previous data session's items, pinning a
collectible ALC). SelectedItemsVector.RemoveAt keeps both vectors in sync and
raises selection-change notifications.
…lection tracking

Addresses review feedback (#23633): the Reset selection-pruning removed
via m_selectedItems.RemoveAt, bypassing TrackItemUnselected (RemoveAtCore
can't correlate an item already gone from SelectedItems), so
SelectionChanged wasn't raised in multi-select mode. Prune via
m_selectedNodes.RemoveAtCore (mirrors the ItemRemoved/Reset cases),
unsubscribe ChildrenChanged, and batch inside Begin/EndSelectionChanges
for a single aggregate SelectionChanged.

Co-Authored-By: Claude Fable 5 <[email protected]>
@nickrandolph
nickrandolph force-pushed the dev/nr/alc-itemsview-debug-layout-leak branch from 6d9aae0 to 55cd1af Compare July 6, 2026 07:37
@nickrandolph
nickrandolph changed the base branch from dev/nr/alc-weak-type-keyed-caches to master July 6, 2026 07:37
@unodevops

Copy link
Copy Markdown
Contributor

…p-reset-prune

fix(TreeView): prune item-to-node map on collection Reset
Copilot AI review requested due to automatic review settings July 6, 2026 13:34

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

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

@unodevops

Copy link
Copy Markdown
Contributor

@MartinZikmund
MartinZikmund merged commit 9281d6c into master Jul 6, 2026
48 checks passed
@MartinZikmund
MartinZikmund deleted the dev/nr/alc-itemsview-debug-layout-leak branch July 6, 2026 18:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

6 participants