Repository navigation
fix: Release subscriptions of never-loaded repeaters and collected bindings - #26115
Conversation
…er alive WinUI's InspectingDataSource and ItemsRepeater subscribe with raw-'this' delegates, which hold no reference to the subscriber. Uno's ports used ordinary handlers, so an items source that outlives a repeater (a view model's collection) kept the ItemsSourceView alive, and through it the repeater and everything it references. Unloaded removes the repeater's handler, but a repeater that never loads never unloads: the content of a flyout that is never opened is created and bound anyway, and kept the page that declares it alive. The ItemsSourceView finalizer meant to remove the source subscription could never run either, since the subscription itself rooted the view. - ItemsSourceView subscribes through a small subscription object that holds the view weakly. The view's finalizer removes it from the source on the UI thread, as WeakCanExecuteChangedSubscription does, since the source isn't required to be thread-safe. - ItemsRepeater subscribes to its ItemsSourceView through a handler that holds the repeater weakly and removes itself once the repeater is gone. Behavior change: an ItemsSourceView is no longer kept alive by its source. Code that creates one, subscribes to its CollectionChanged and keeps no reference to it stops receiving events once it is collected, as on WinUI. Keep a reference to the view for as long as it is needed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A {Binding} subscribes to its source's PropertyChanged with a handler
that holds the binding only weakly, and removes it when the binding is
disposed. When the bound element is dropped without its bindings being
cleared, the binding is collected but the handler stays on the source.
A source that outlives its views, like a view model kept while its
views are rebuilt, then accumulates one handler (with its weak
references and GC handles) per element ever bound to it, without bound.
The subscription returned to the binding is now an object whose
finalizer removes the handler once the binding is gone, without
waiting for the source to raise. The removal is queued on the UI
thread, since the source isn't required to be thread-safe, as
WeakCanExecuteChangedSubscription does for commands.
The subscription holds its source strongly so that the finalizer can
still reach it: the pooled weak references may already be finalized by
then. This only links the binding to its source, which the bound
element's DataContext already does, and the link is dropped on Dispose.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
WeakCanExecuteChangedSubscription, ItemsSourceView and the binding PropertyChanged subscription each queued the removal of a subscription on the UI thread from a finalizer, guarded against throwing, and logged failures. SubscriptionCleanup now does this in one place. Co-Authored-By: Claude Opus 5.5 <[email protected]>
master keeps the repeater and binding runtime tests under Microsoft/UI/Xaml, next to Given_ItemsRepeater and Given_BindingMemoryLeak. The namespaces already match. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The DataTemplate(Func<>) constructor the 6.8 test used is gone on master; build the item template with DataTemplate(owner, factory). Co-Authored-By: Claude Opus 5.5 <[email protected]>
The subscription that removes a collected binding's PropertyChanged handler held its source strongly, so that its finalizer could still reach it. In the common case, a page and its view model dropped together, this kept the view model alive through finalization and until the queued removal ran on the UI thread, although the removal was pointless: both sides were dead. master freed it in one GC. The source is now held through a raw weak GCHandle. Unlike a pooled ManagedWeakReference, it has no finalizer of its own that could run first, and it is cleared before finalizers run, so a source that died with the binding needs no removal at all. A live source, the leak this subscription exists for, is still unsubscribed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A binding whose path indexes into a collection ({Binding Items[0]})
also listens to the collection's CollectionChanged. That handler
captured the binding item strongly and was only removed on Dispose,
so a collection that outlives its views kept every binding ever made
on it alive, along with their PropertyChanged subscriptions, whose
cleanup then never ran.
The handler now holds the binding item weakly, and the subscription is
removed once the binding is collected, like the PropertyChanged one.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Each subscription removed from a finalizer queued its own dispatcher item at Normal priority. Collecting a page with thousands of bindings then queued thousands of items, which delayed the next frame until they all ran. Removals now go into one queue, drained at Low priority in batches of 256 by a single dispatcher item. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The source subscription is also referenced by its view, so what matters is that it holds the view weakly. The file header now lists the weak data-source subscription, and notes when a dead repeater's handler goes away. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The description passed to SubscriptionCleanup.Run was interpolated on every Dispose, although it's only used if the removal fails. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The repeater, binding and CanExecuteChanged leak tests each had their own copy of the helper that collects and pumps the dispatcher until finalizer-queued removals have run. It now lives in LeakTestHelper. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- an ItemsSourceView nobody references releases its subscription for each kind of observable source (INotifyCollectionChanged, IObservableVector<object> and Uno's untyped IObservableVector); - a raise to collected repeaters doesn't keep their subscriptions; - a nested binding path releases the handler of every segment. Co-Authored-By: Claude Opus 5.5 <[email protected]>
They pass there, and they count real .NET subscribers and objects, so CI can check that Uno releases the same subscriptions WinUI does. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🤖 Your WebAssembly Sample App stage site is ready! Visit it here: |
|
@Mergifyio backport release/stable/6.7 servicing/6.8 |
✅ Backports have been createdDetails
Cherry-pick of 0a44387 has failed: Cherry-pick of 69d2696 has failed: Cherry-pick of f2e148b has failed: To fix up this pull request, you can check it out locally. See documentation: https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/reviewing-changes-in-pull-requests/checking-out-pull-requests-locally
Cherry-pick of 0a44387 has failed: Cherry-pick of 69d2696 has failed: Cherry-pick of f2e148b has failed: To fix up this pull request, you can check it out locally. See documentation: https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/reviewing-changes-in-pull-requests/checking-out-pull-requests-locally |
|
The build 244099 found UI Test snapshots differences: Details
|
ajpinedam
left a comment
There was a problem hiding this comment.
Follow-ups from a deeper pass. The high and medium items are inline; the lower-severity ones are in a separate comment.
For context, from build 244099: the new leak tests ran on WASM, iOS, Android, Linux (X11, framebuffer, WebGPU), macOS and Windows with no failures. The iOS result XML shows each of them as a real pass, including When_Element_And_Source_Dropped_Together_Then_Source_Collected_Without_Dispatcher (not Inconclusive). The red Android shard 3 is Given_InputPane.When_Focus_Moves_While_Occluded_Then_New_Field_Brought_Above_Occlusion, which this PR doesn't touch.
|
Lower-severity items from the same pass; none of these blocks the PR.
|
Measured on native WinUI with 10 then 30 iterations, one attempt each: - The repeater leak tests and When_Binding_Cleared_Then_Handler_Removed pass every time, so the reporter's ones now run on WinUI too. - Tests that count the handlers of collected bindings fail within a few iterations: WinUI removes them on its own schedule, sometimes after the test's collection window. The indexer and nested-path tests are excluded again, and the reporter's two such tests stay excluded. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The test added in 0d9f987 repeated the reporter's raise-safety test and only added a subscriber-count assertion. That assertion now ends the reporter's test, renamed to say what it checks, and the copy is removed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…o.cs SourceSubscription is Uno-specific: keep it out of the file ported from WinUI. No change in behavior. Co-Authored-By: Claude Opus 5.5 <[email protected]>
It was private to BindingPath: make it a shared helper, taking the type to log failures under, so that other weak subscriptions can use it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The callbacks are now static lambdas that get their state explicitly, so capturing the source (which would keep it alive) is a compile error rather than a rule stated in a comment. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A removal copies the source's whole handler list, so 256 removals from a source with thousands of stale handlers could make one long main-thread task. A batch now also stops after 3 ms and reschedules the rest. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🤖 Your WebAssembly Sample App stage site is ready! Visit it here: |
An #if around a [TestMethod] hides it from test discovery: move it into the helper that uses the Uno-only DataTemplate(owner, factory). The test is still excluded on native WinUI by its PlatformCondition. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A repeater that never loads never unloads to detach from its ItemTransitionProvider. It fails before the next fix: the provider's TransitionCompleted handler held the repeater strongly. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ters TransitionManager subscribed to its provider's TransitionCompleted with a strong delegate, removed only on Unloaded, so a provider that outlives a never-loaded repeater (e.g. a shared one) kept it alive. WinUI subscribes with a raw-'this' delegate, holding no reference. The handler now holds the manager weakly, and the manager keeps a WeakSourceSubscription, whose finalizer removes the handler once the repeater is collected. Unloaded still removes it right away. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
The build 244217 found UI Test snapshots differences: Details
|
|
Thanks, all addressed:
|
|
🤖 Your WebAssembly Sample App stage site is ready! Visit it here: |
|
The build 244235 found UI Test snapshots differences: Details
|
The WASM interpreter's conservative stack scan keeps the elements alive from stale slots, depending on frame layout: with the shared helper on every run, with the inline loop only next to the other leak tests. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
The build 244423 found UI Test snapshots differences: Details
|
|
This pull request does not currently match the merge queue conditions, so it cannot be queued from here. The box comes back if it matches again. |
…r-26115 fix: Release subscriptions of never-loaded repeaters and collected bindings (backport #26115)
…6.7/pr-26115 fix: Release subscriptions of never-loaded repeaters and collected bindings (backport #26115)
GitHub Issue: closes unoplatform/kahua-private#566
PR Type:
🐞 Bugfix
What changed? 🚀
Two leaks in a common app pattern: a view model kept for the whole session, with views rebuilt on every visit. In both, a long-lived source keeps strong references to subscribers that should have gone away with the view.
The first three commits are the reporter's patches, ported to master. They are kept as written, and every change on top of them is a separate commit.
1. A never-loaded
ItemsRepeaterstays aliveWinUI holds no reference at either hop:
InspectingDataSourceandItemsRepeaterboth subscribe with raw-thisdelegates. Uno removed the repeater's handler onUnloaded, but a repeater that never loads never unloads. For example, the content of aFlyoutis created and bound even if the flyout is never opened. The~ItemsSourceViewfinalizer, meant to remove the source subscription, could never run either, because the subscription itself kept the view reachable.ItemsSourceViewsubscribes through a forwarder that holds the view weakly. The view keeps a subscription object whose finalizer removes the forwarder once the view is collected;~ItemsSourceViewis gone.ItemsRepeatersubscribes to itsItemsSourceViewwith a handler that holds the repeater weakly. The handler is removed the same way once the repeater is collected, not only on the view's next raise.TransitionManagerhad the same problem with a sharedItemTransitionProvider: itsTransitionCompletedhandler is now weak too.Unloadedstill removes it right away.Behavior change (no API change): an
ItemsSourceViewis no longer kept alive by its source. Code that creates one, subscribes toCollectionChanged, then drops its own reference stops receiving events once the view is collected. This matches WinUI, and a new test checks it on both Uno and native WinUI. Every in-repo consumer keeps a reference to its view (ItemsView, RadioButtons, BreadcrumbBar, SelectionNode, TreeViewNode, NavigationView). The throwaway viewsNavigationViewcreates to inspect its items used to leave a permanent handler on the source; they no longer do.2.
{Binding}leaves its handlers on the sourceBindingPathadded aPropertyChangedhandler that holds the binding weakly, but removed it only when the binding was disposed. Bindings of a view that is simply dropped are never disposed. So a long-lived source accumulated one handler, with its weak references and GC handles, per element ever bound to it. The reporter measured 694 handlers on one view model after 11 rounds.On WinUI, the subscription goes away when the binding expression is destroyed. This PR is the .NET counterpart: the subscription the binding keeps is an object whose finalizer removes the handler once the binding is collected, even if the source never raises again.
Disposebehaves as before and suppresses the finalizer, which is the path recycled list items take when theirDataContextchanges. Bindings with an indexer path ({Binding Items[0]}) also subscribe to the collection'sCollectionChanged; that handler captured the binding strongly, and now gets the same treatment.Shared cleanup
All of the above, and the
CanExecuteChangedsubscription ofButtonBase/MenuFlyoutItem(#25965), now use one helper,WeakSourceSubscription:GCHandle. A source that dies together with its subscriber (a page and its view model) is collected at once and needs no removal. The reporter's version, and fix: Subscribe to Command.CanExecuteChanged weakly #25965's command subscription, held the source strongly until the queued removal ran; new tests cover both.SubscriptionCleanupqueues them from finalizers and drains them at Low priority, in batches of at most 256 removals or 3 ms, with a single dispatcher item at a time.Dispose, and the message names the source's type. This is new for a binding'sDispose, which used to throw if the source'sremoveaccessor did.Why finalizers
A dropped page has no deterministic teardown point: content that never loaded is never unloaded, and nothing disposes its bindings. WinUI frees its subscriptions when the reference count of the binding expression or control drops to zero; in .NET, that moment is only observable through finalization. The reviewer's alternative, one weak fan-out handler per source, would make the removals much cheaper (see below), but still needs the same trigger to prune dead entries. It's tracked in #26127.
Cost
Measured on Skia desktop (Win32), this PR against its merge-base:
DataContextis swapped 10,000 times take about 10-15% longer (one finalizable object per subscription), with slightly fewer bytes allocated (33.6 vs 34.8 KB per swap).-=copies the event's invocation list. With 20 such pages collected before any removal runs (90,000 pending on one view model), the removals take about 60 s of UI-thread CPU, still in 3 ms batches. The per-source fan-out in Subscribe {Binding} to a source through one shared handler per source #26127 would remove this cost.Validation
Given_ItemsRepeater_Leak,Given_BindingStaleHandlers,Given_CommandCanExecuteChanged,Given_BindingMemoryLeak) pass 10 iterations in a row with a single attempt each.[Ignore]). It covers the Repeater, ItemsView and NavigationView suites (Uno and MUX), the Data and binding suites,Given_UIElement,Given_FrameworkElement,Given_ItemsControl,Given_ContentControl,Given_Button,Given_MenuFlyoutItemandGiven_AppBarButton.When_Binding_Cleared_Then_Handler_Removed, the dropped-together tests and theItemsSourceViewbehavior-change test pass every time.Uno.UI.UnitTestshas no new failures. The 13Given_Calendarfailures are the existing time-zone baseline.dotnet format whitespaceare clean.Follow-ups
DispatcherConditionalDisposable,ImageSource,BrowserHtmlElement) onto the same helper.{Binding}through one handler per source, to remove the O(n²) worst case above.Backports to the stable branches will follow.
PR Checklist ✅
Screenshots Compare Test Runresults.ItemsSourceViewbehavior change above)🤖 Generated with Claude Code