Skip to content

fix: Release subscriptions of never-loaded repeaters and collected bindings (backport #26115) - #26193

Merged
Xiaoy312 merged 35 commits into
servicing/6.8from
mergify/bp/servicing/6.8/pr-26115
Nov 8, 2026
Merged

Xiaoy312 merged 35 commits into
servicing/6.8from
mergify/bp/servicing/6.8/pr-26115

Conversation

@mergify

@mergify mergify Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

GitHub Issue: closes unoplatform/kahua-private#566

Note

Backport notes for servicing/6.8

  • The branch was rebuilt by hand. Mergify's cherry-pick added master's ItemsRepeater.mux.cs and ItemsRepeater.uno.cs next to 6.x's single ItemsRepeater.cs, which doesn't build. 6.x has no such split, and it keeps runtime tests under Tests/Windows_UI_Xaml[_Controls]/. The branch starts from the reporter's original patches, which were written against servicing/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 weak SubscribeToItemsSourceView helper 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.
    • Dropped: the master commit that moved the tests to the new folders, and the one that switched the tests to DataTemplate(owner, factory). 6.x keeps DataTemplate(Func<>); the (owner, factory) call is ambiguous there.
    • Given_CommandCanExecuteChanged: this branch's Android BindableButton tests stay, next to the new command test.
  • 6.x-only test exclusion. The three "dropped together, collected without dispatcher" tests (binding, command, repeater) are skipped on WASM and mobile. 6.x's DependencyObjectStore still 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.
  • 6.x-only: two more leak tests skipped on the Mono interpreter. 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_Removed is 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.
  • Behavior change (no API change), as on master: an ItemsSourceView is no longer kept alive by its source. Code that creates one, subscribes to CollectionChanged, then drops its own reference stops receiving events once the view is collected. This matches WinUI.
  • The CanExecuteChanged removals 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 shared SubscriptionCleanup sweep, in batches at Low priority on the UI thread.
  • Runtime, Skia desktop (locally): 208 passed, 0 failed, 45 skipped (Repeater Uno + MUX suites, Data, 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 ItemsRepeater stays alive

items source (a view model's collection)
 → ItemsSourceView       (source.CollectionChanged handler)
 → ItemsRepeater         (ItemsSourceView.CollectionChanged handler)
 → everything the repeater references (its template, its page, ...)

WinUI holds no reference at either hop: InspectingDataSource and ItemsRepeater both subscribe with raw-this delegates. Uno removed the repeater's handler on Unloaded, but a repeater that never loads never unloads. For example, the content of a Flyout is created and bound even if the flyout is never opened. The ~ItemsSourceView finalizer, meant to remove the source subscription, could never run either, because the subscription itself kept the view reachable.

  • ItemsSourceView subscribes through a forwarder that holds the view weakly. The view keeps a subscription object whose finalizer removes the forwarder once the view is collected; ~ItemsSourceView is gone.
  • ItemsRepeater subscribes to its ItemsSourceView with 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.
  • TransitionManager had the same problem with a shared ItemTransitionProvider: its TransitionCompleted handler is now weak too. Unloaded still removes it right away.

Behavior change (no API change): an ItemsSourceView is no longer kept alive by its source. Code that creates one, subscribes to CollectionChanged, 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 views NavigationView creates to inspect its items used to leave a permanent handler on the source; they no longer do.

2. {Binding} leaves its handlers on the source

BindingPath added a PropertyChanged handler 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. Dispose behaves as before and suppresses the finalizer, which is the path recycled list items take when their DataContext changes. Bindings with an indexer path ({Binding Items[0]}) also subscribe to the collection's CollectionChanged; that handler captured the binding strongly, and now gets the same treatment.

Shared cleanup

All of the above, and the CanExecuteChanged subscription of ButtonBase / MenuFlyoutItem (#25965), now use one helper, WeakSourceSubscription:

  • The source is held weakly, through a raw weak 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.
  • Removals run on the UI thread, since sources aren't required to be thread-safe. SubscriptionCleanup queues 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.
  • Failures are logged, never thrown, from the finalizer path and from Dispose, and the message names the source's type. This is new for a binding's Dispose, which used to throw if the source's remove accessor 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:

  • Recycling: 20 bindings whose DataContext is 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).
  • Navigation: visiting a 3000-binding page 20 times on one long-lived view model, with a full GC between visits, costs the same to build. The queued removals then take about 72 ms of UI-thread time per visit, in batches of at most 3 ms. On the merge-base, 60,000 dead handlers are left on the view model and a raise takes 4.3 ms; with this PR, none are left.
  • Worst case: removing n dead handlers from one source costs O(n²), because every -= 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

  • Runtime, Skia desktop (Win32):
    • The new tests fail before their fix, and pass after it: never-loaded repeaters (the reporter's), stale binding handlers, sources dropped with their subscriber (bindings, items sources, commands), dead repeaters' handlers on a shared view, a shared transition provider.
    • The leak classes (Given_ItemsRepeater_Leak, Given_BindingStaleHandlers, Given_CommandCanExecuteChanged, Given_BindingMemoryLeak) pass 10 iterations in a row with a single attempt each.
    • Regression run: 973 passed, 0 failed, 66 skipped ([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_MenuFlyoutItem and Given_AppBarButton.
  • Runtime, native WinUI (WinAppSDK): the leak tests now run there in CI, except those that count the handlers of collected bindings: WinUI removes them on its own schedule, which made them fail within a few iterations. Each remaining exclusion states its reason. Measured with 10 then 30 iterations: the repeater leak tests, When_Binding_Cleared_Then_Handler_Removed, the dropped-together tests and the ItemsSourceView behavior-change test pass every time.
    • A final run of the four leak classes, 10 iterations with a single attempt each: all 26 enabled cases pass, including the shared transition-provider test.
  • CI, build 244099 (before this round): the new leak tests passed on WASM, iOS, Android, Linux (X11, framebuffer, WebGPU), macOS and Windows.
  • Unit tests: Uno.UI.UnitTests has no new failures. The 13 Given_Calendar failures are the existing time-zone baseline.
  • Reporter's repro, against this build: closed views still alive and subscribers left go from 10 / 30 / 10 to 0 / 0 / 0. Re-run after this round: still 0 / 0 / 0.
  • Compile: strict desktop build (analyzers on), the WinAppSDK head, and dotnet format whitespace are clean.

Follow-ups

Backports to the stable branches will follow.

PR Checklist ✅

🤖 Generated with Claude Code


This is an automatic backport of pull request #26115 done by [Mergify](https://mergify.com).

jbourque-kahua and others added 30 commits November 6, 2026 16:16
…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]>
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]>
…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]>
Xiaoy312 and others added 3 commits November 6, 2026 16:16
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]>
@mergify mergify Bot added the conflicts Automated merge hit conflicts label Nov 6, 2026
@mergify

This comment has been minimized.

@Xiaoy312
Xiaoy312 force-pushed the mergify/bp/servicing/6.8/pr-26115 branch from fe5d082 to c45943d Compare November 6, 2026 21:50
@Xiaoy312 Xiaoy312 removed the conflicts Automated merge hit conflicts label Nov 6, 2026
@unodevops

Copy link
Copy Markdown
Contributor

🤖 Your WebAssembly Sample App stage site is ready! Visit it here:

@Xiaoy312 Xiaoy312 added the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label 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]>
@unodevops

Copy link
Copy Markdown
Contributor

🤖 Your WebAssembly Sample App stage site is ready! Visit it here:

@mergify

mergify Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
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.

@unodevops

Copy link
Copy Markdown
Contributor

🤖 Your WebAssembly Sample App stage site is ready! Visit it here:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants