Repository navigation
fix: Release subscriptions of never-loaded repeaters and collected bindings (backport #26115) - #26193
Merged
Merged
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]>
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]>
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]>
An items source or a command that becomes unreachable together with its subscriber must be collectable without waiting for the dispatcher to run the subscription's queued removal. Both fail before the next fixes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
~ItemsSourceView queued the removal of its subscription with a callback holding the source strongly, so a collection dropped together with its view stayed rooted until the dispatcher ran it, then needed another GC. The subscription is now a WeakSourceSubscription held by the view only: it holds the source weakly and its own finalizer removes the forwarder, skipping a source that died too. ItemsSourceView needs no finalizer, so a view and its source dropped together are collected in a single GC. Co-Authored-By: Claude Opus 5.5 <[email protected]>
As the finalizer path already does, so it can replace the subscription of WeakCanExecuteChangedSubscription, whose Dispose must not throw when a command's remove accessor fails. A binding's Dispose now logs such a failure too, instead of throwing out of the binding's teardown. Co-Authored-By: Claude Opus 5.5 <[email protected]>
~Handle queued Subscription.Dispose, which held the command strongly, so a command dropped together with its button stayed rooted until the dispatcher ran the removal, then needed another GC. The owner now holds a WeakSourceSubscription: it holds the command weakly, and its finalizer skips a command that died too. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A view that outlives its repeaters and rarely raises, such as one a view model exposes, must not accumulate a handler per collected repeater. It fails before the next fix: the handlers were only removed on a raise. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The handler a repeater adds to its ItemsSourceView was only removed on the view's next raise once the repeater was collected, so a view that outlives its repeaters and rarely raises kept one handler per rebuilt page. The repeater now keeps a WeakSourceSubscription, whose finalizer removes the handler, like the other subscriptions, and skips a view that died too. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The source no longer keeps an ItemsSourceView alive, as on WinUI, so a view with a subscriber but no other reference is collected, and its subscriber is no longer notified of the source's changes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A finalized WeakSourceSubscription now queues itself with its source, instead of a closure capturing both. The failure logs also name the source's type, so a log points to the view model or collection involved. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- A removal that fails to be scheduled stays queued and runs with the next one scheduled: log it as a warning that says so, not as an error that reads like a leak. Only a failure to queue it loses it. - A batch reschedules itself in a finally, so a throwing logger doesn't hold back the rest of the queue. - A Debug line reports how many removals a batch ran and how many are still queued, to tell a late removal from a leak. 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]>
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 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]>
This comment has been minimized.
This comment has been minimized.
2 of 5 tasks
Xiaoy312
force-pushed
the
mergify/bp/servicing/6.8/pr-26115
branch
from
November 6, 2026 21:50
fe5d082 to
c45943d
Compare
Contributor
|
🤖 Your WebAssembly Sample App stage site is ready! Visit it here: |
ajpinedam
approved these changes
Nov 7, 2026
On 6.x the owner's DependencyObjectStore has a finalizer, so it keeps the source or command alive until finalizers run. Single-threaded WASM runs them only from the event loop; Android fails too. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Contributor
|
🤖 Your WebAssembly Sample App stage site is ready! Visit it here: |
Contributor
Author
|
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. |
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Contributor
|
🤖 Your WebAssembly Sample App stage site is ready! Visit it here: |
2 of 5 tasks
Merged
1 task done
This was referenced Nov 9, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
GitHub Issue: closes unoplatform/kahua-private#566
Note
Backport notes for
servicing/6.8ItemsRepeater.mux.csandItemsRepeater.uno.csnext to 6.x's singleItemsRepeater.cs, which doesn't build. 6.x has no such split, and it keeps runtime tests underTests/Windows_UI_Xaml[_Controls]/. The branch starts from the reporter's original patches, which were written againstservicing/6.8, followed by every follow-up commit from fix: Release subscriptions of never-loaded repeaters and collected bindings #26115. The Uno.UI changes match master's, with these differences:ItemsRepeater.cs: the weakSubscribeToItemsSourceViewhelper is applied by hand to the single file. The detach comment from the last master commit is skipped because 6.x doesn't have that comment.DataTemplate(owner, factory). 6.x keepsDataTemplate(Func<>); the(owner, factory)call is ambiguous there.Given_CommandCanExecuteChanged: this branch's AndroidBindableButtontests stay, next to the new command test.DependencyObjectStorestill has a finalizer, which master removed. It keeps the source or command alive until finalizers run, and single-threaded WASM runs them only from the event loop. On 6.8 WASM, suppressing the store's finalizer makes the command test pass. They still run on desktop.When_Raised_Before_Handlers_Removed_Then_Safe(already skipped on WASM) is also skipped on iOS, where all 5 elements stayed alive on CI.When_Repeater_Collected_Then_Raising_CollectionChanged_Is_Safe_And_Subscription_Removedis skipped on WASM and iOS, where 1 repeater stayed alive now and then. In both cases, stale stack slots that the interpreter scans conservatively keep the objects alive. Both tests passed when their jobs were re-run.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.CanExecuteChangedremovals from fix: Subscribe to Command.CanExecuteChanged weakly #25965 are now batched. A collected control's subscription used to be removed through one dispatcher item per control. It now goes through the sharedSubscriptionCleanupsweep, in batches atLowpriority on the UI thread.Given_BindingMemoryLeak,Given_BindingStaleHandlers,Given_ItemsRepeater_Leak,Given_CommandCanExecuteChanged,Given_Button). The two leak classes also ran 10 iterations with 1 attempt each: 47 passed, 0 failed. Not run locally: the 6.x native renderers (Android, iOS, WebAssembly DOM) and the native WinUI head; those rely on CI.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
This is an automatic backport of pull request #26115 done by [Mergify](https://mergify.com).