Skip to content

fix(binding): Remove stale callbacks and follow indexed collections - #26219

Merged
Xiaoy312 merged 10 commits into
masterfrom
dev/xygu/20261107/binding-source-leaks
Nov 9, 2026
Merged

Xiaoy312 merged 10 commits into
masterfrom
dev/xygu/20261107/binding-source-leaks

Conversation

@Xiaoy312

@Xiaoy312 Xiaoy312 commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

GitHub Issue: closes unoplatform/kahua-private#568

PR Type:

🐞 Bugfix

What changed? 🚀

This follows #26115 (kahua-private#566) and fixes three more problems with bindings to a long-lived source. The first four 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. Callbacks on a DependencyObject source were never removed

A property-changed callback that another object registers on a DependencyObject is held weakly. A {Binding} whose source is a DependencyObject is one example. A ConditionalDisposable tied to the subscriber removes the callback from its finalizer, but only if the source is still alive.

It read the source's liveness from a WeakReference that nothing else referenced. That WeakReference became unreachable in the same collection as the ConditionalDisposable, and finalizers run in any order. When the WeakReference was finalized first, it reported its target as gone, so the callback was never removed. A long-lived source kept one dead callback for every subscriber it ever had.

ConditionalDisposable now holds the source through a weak GCHandle, which has no finalizer and is freed by the ConditionalDisposable itself.

Now that these removals actually happen, each one queued its own dispatcher item from the finalizer. DispatcherConditionalDisposable now queues them through SubscriptionCleanup, like the other removals added in #26115: one dispatcher item at a time, run at Low priority in batches.

2. An indexer path didn't follow a replaced collection

A {Binding} or x:Bind with a path such as Items[0] subscribes to the collection's CollectionChanged. The item before the indexer made that subscription, on the collection it held at that moment. After Items = new ..., the binding kept listening to the old collection and never subscribed to the new one.

The indexer item now makes the subscription, on the collection it indexes into (its DataContext). It resubscribes whenever its DataContext changes. The handler still holds the binding weakly through WeakSourceSubscription (#26115).

The reporter's 6.8 patch also had its own subscription class and SubscriptionCleanup. Those duplicate what #26115 already put on master, and the patch's class held the collection strongly. So only the move to the indexer and the tests are ported, as the commit message says.

3. An indexer showed the collection instead of the item

When the indexed collection raised CollectionChanged, the binding pushed the collection itself to its target. A TextBlock bound to Items[0] then showed the collection's type name. The collection's PropertyChanged raises "Item[]", which doesn't match the "Item[0]" the indexer listens to, so it doesn't help. The indexer now re-reads its value on CollectionChanged, which also updates a longer path such as Items[0].Length.

Tests

Given_BindingSourceStaleHandlers (14 tests) covers:

  • {Binding} and x:Bind OneWay handlers left on a view model and on an indexed collection.
  • Callbacks left on a DependencyObject source.
  • A replaced, emptied and refilled collection.
  • A cleared binding.
  • A raise after the bindings are collected.

It replaces the indexer test in Given_BindingStaleHandlers.

Note for bisecting: the reporter's master port of the tests (b66dbfbe20) was never compiled on master, so Uno.UI.RuntimeTests doesn't build from 886be6812d to b66dbfbe20. 402ac0e9d7 fixes it. Those commits are left as written.

Validation

  • Runtime, Skia desktop (Win32):
    • Before the fix (master's product code with the new tests), 7 of the 14 tests fail: the callbacks left on the DependencyObject source, the collection's type name, and the replaced collection.
    • After it, all 22 tests in Given_BindingSourceStaleHandlers and Given_BindingStaleHandlers pass. The binding suites (Given_Binding*, Given_xBind, Given_XBind*, Windows_UI_Xaml_Data, BindingTests) pass 97 of 97.
    • Wider run over Windows_UI_Xaml.* and Uno_UI_Extensions: 1220 passed, 3 failed. The 3 are theme tests (When_RequestedTheme_Set_Explicitly, When_Secondary_Window_No_Background_*) that expect Light while the machine's OS is in dark mode. The reporter saw the same 3 fail without these changes.
  • Runtime, native WinUI (WinAppSDK): the 6 tests on live bindings (the indexer refresh, the replaced collection, the cleared binding) pass 10 iterations with a single attempt each, so they now run there in CI. That confirms the fixed behavior matches WinUI. The tests that wait for collected bindings stay excluded, as in Given_BindingStaleHandlers, and so does the one that reads Uno's internal callbacks. Each exclusion states its reason.
  • Unit tests: Uno.UI.UnitTests has no new failures. The 13 Given_Calendar failures are the existing time-zone baseline.
  • Compile: the strict desktop build (analyzers on), the WinAppSDK head, and dotnet format whitespace are clean.
  • Not run locally: WASM, Android and iOS. The raise-after-collection tests are skipped on WASM, for the same conservative-stack-scan reason as in Given_BindingStaleHandlers.

Backports to 6.7 and 6.8 will follow once #26192 and #26193 merge, since this builds on #26115.

PR Checklist ✅

🤖 Generated with Claude Code

jbourque-kahua and others added 10 commits November 7, 2026 23:24
A property-changed callback registered on a DependencyObject by another
object, like a {Binding} whose source is a DependencyObject, is held
weakly and removed once that object is collected: a ConditionalDisposable
tied to the subscriber removes it from its finalizer, if the source is
still alive.

The source's liveness was read from a WeakReference that only the
ConditionalDisposable references. Both become unreachable in the same
collection and their finalizers run in any order; a WeakReference
finalized first reports its target as collected, so the callback was
never removed. A long-lived source accumulated one dead callback per
subscriber ever registered, for good.

ConditionalDisposable now takes the condition source itself and holds it
through a weak GCHandle, which has no finalizer and is freed by the
ConditionalDisposable. Callers no longer allocate a WeakReference to
pass it in.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A {Binding} or x:Bind whose path indexes into an INotifyCollectionChanged
value (Items[0]) subscribes to the collection's CollectionChanged. The
subscription was made by the item before the indexer, on the value it
held when it subscribed, and nothing moved it: after Items = new ...,
the binding kept listening to the old collection, and never to the new
one.

The subscription is now made by the indexer item, on the collection it
indexes into (its DataContext). The indexer resubscribes whenever its
DataContext changes, so a replaced collection is followed.

The tests also cover the CollectionChanged handlers of collected
bindings: they are removed, and a raise after the bindings are collected
is safe.

Ported from the servicing/6.8 patch "fix(binding): Don't let collections
pin bindings". Its weakly held handler and finalizer cleanup are already
on master (WeakSourceSubscription), so only the move to the indexer and
the tests are ported.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
When the collection a {Binding} path indexes into (Items[0]) raised
CollectionChanged, the binding pushed the collection itself to its
target instead of the indexed value: a TextBlock bound to Items[0]
showed the collection's type name after Items[0] = "x" or an insert.
The collection's PropertyChanged doesn't help, since it raises "Item[]"
and the indexer listens to "Item[0]".

The indexer now re-reads its value on CollectionChanged and propagates
it, as it does on PropertyChanged, which also updates a longer path such
as Items[0].Length. x:Bind, which re-evaluates its whole path, still
follows the collection, through the same propagation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
{x:Bind Mode=OneWay} goes through the same BindingPath as {Binding}, so
it leaves the same PropertyChanged handlers on a long-lived source when
its element is collected. An indexer path (Items[0]) leaves them both on
the view model and on the collection.

These tests pass only once PropertyChanged handlers of collected
bindings are removed from their source (BindingPath.
SubscribeToNotifyPropertyChanged), which is a separate fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The ported test read a source's property-changed callbacks through
IDependencyObjectStoreProvider, which master no longer has: the store is
merged into DependencyObject. Also keep the Uno-internal read out of the
WinAppSDK build, where the test is excluded.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Also skip the CollectionChanged raise test on WASM, like the
PropertyChanged one: the interpreter's conservative stack scan can keep
the elements alive from stale slots, depending on frame layout.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Given_BindingSourceStaleHandlers checks the CollectionChanged handlers of
collected indexer bindings, loaded and not, and their PropertyChanged
handlers on the view model.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Now that a ConditionalDisposable reliably removes the callback of a
collected subscriber from a live source, each removal queued its own
Idle dispatcher item from the finalizer. Queue them with the other
removals of collected subscribers instead (SubscriptionCleanup), drained
at Low priority in bounded batches by a single dispatcher item.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Measured on native WinUI with 10 iterations, one attempt each: the six
tests that only follow or count the subscriptions of live bindings (the
indexer refresh, the replaced collection, the cleared binding) pass every
time, so they now run there too, which also confirms the fixed behavior
matches WinUI's.

The tests that wait for collected bindings to be cleaned up stay
excluded, as in Given_BindingStaleHandlers, and so does the one that
reads Uno's property-changed callbacks. Each exclusion now says why.

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:

@nventive-devops

Copy link
Copy Markdown
Contributor

The build 244649 found UI Test snapshots differences: skia-linux-screenshots: 2458, skia-windows-screenshots: 2458

Details
  • skia-linux-screenshots: 2458 changed over 2494

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • AnimatedBackVisualSourceSamplePage.png
    • Accessibility_ScreenReader.png-dark
    • AnimatedVisualsTestbedPage.png-dark
    • AnimatedVisualsTestbedPage.png
    • AppBarToggleButtonTest.png
    • Application_DispatcherShutdownMode.png-dark
    • ApplicationViewSizing.png
    • AppWindowPresenters.png-dark
    • AppWindowFeatures.png-dark
    • ArcSegment.png
    • AppWindowPositionAndSize.png
    • Attributed_text_Supserscript.png
    • ArcSegment.png-dark
    • AutoBorderStretchwithleftmargin.png-dark
    • Attributed_text_FontSize_Changing.png-dark
    • AutoBorderStretchwithtopmargin.png-dark
    • AuthenticationBroker_Cancel.png
    • AutomationProperties_Name.png-dark
    • AuthenticationBroker_Demo.png-dark
    • AutomationProperties_Name.png
  • skia-windows-screenshots: 2458 changed over 2494

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • Accessibility_ScreenReader.png
    • AnimatedBackVisualSourceSamplePage.png
    • AppBarButtonTest.png-dark
    • AppBarButtonTest.png
    • AppBarToggleButtonTest.png
    • Application_DispatcherShutdownMode.png-dark
    • AppWindowPositionAndSize.png
    • AppXamlDefinedResources.png-dark
    • Attributed_text_Simple.png-dark
    • Attributed_text_Simple.png
    • AutoBorderStretchwithrightmargin.png
    • AutoBorderStretchwithtopmargin.png-dark
    • AutomationProperties_StructureAndProps.png
    • AutoSizedPathCentered.png-dark
    • AutoSuggestBox_SoftKeboard.png-dark
    • AutoSuggestBox_SoftKeboard.png
    • BasicThemeResources.png-dark
    • BasicThemeResources.png
    • BitmapIcon_Generic.png-dark
    • BitmapIcon_Generic.png

@Xiaoy312
Xiaoy312 marked this pull request as ready for review November 9, 2026 15:57
@unodevops

Copy link
Copy Markdown
Contributor

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

@nventive-devops

Copy link
Copy Markdown
Contributor

The build 244820 found UI Test snapshots differences: skia-linux-screenshots: 256, skia-windows-screenshots: 304

Details
  • skia-linux-screenshots: 256 changed over 2494

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • AnimatedBackVisualSourceSamplePage.png-dark
    • AnimatedVisualsTestbedPage.png
    • AutomationProperties_AutomationId.png-dark
    • AutomationProperties_StructureAndProps.png-dark
    • AutomationProperties_StructureAndProps.png
    • Basics.png-dark
    • Basics.png
    • BreadcrumbBarPage.png-dark
    • BreadcrumbBarPage.png
    • CalendarView_Theming.png-dark
    • CalendarView_Theming.png
    • ClipboardTests.png-dark
    • ClipboardTests.png
    • Border_CornerRadius_BorderThickness.png-dark
    • Border_CornerRadius_BorderThickness.png
    • Buttons.png-dark
    • Buttons.png
    • AppWindowTitleBar Properties.png
    • BenchmarkDotNet.png-dark
    • BenchmarkDotNet.png
  • skia-windows-screenshots: 304 changed over 2494

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • AnimatedBackVisualSourceSamplePage.png
    • AnimatedVisualsTestbedPage.png-dark
    • AutomationProperties_StructureAndProps.png-dark
    • BasicAcrylicBrushTest2.png-dark
    • AutomationProperties_AutomationId.png-dark
    • BasicAcrylicBrushTest2.png
    • AutomationProperties_AutomationId.png
    • AutomationProperties_StructureAndProps.png
    • Border_CornerRadius_Binding.png-dark
    • Border_CornerRadius_Binding.png
    • ButtonClippingTestsControl.png-dark
    • ButtonClippingTestsControl.png
    • Border_CornerRadius_BorderThickness.png-dark
    • Border_CornerRadius_BorderThickness.png
    • Buttons.png-dark
    • Buttons.png
    • BreadcrumbBarPage.png-dark
    • BreadcrumbBarPage.png
    • CalendarView_Theming.png-dark
    • CalendarView_Theming.png

@mergify

mergify Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

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.

@Xiaoy312
Xiaoy312 merged commit 7b1623c into master Nov 9, 2026
53 checks passed
@Xiaoy312
Xiaoy312 deleted the dev/xygu/20261107/binding-source-leaks branch November 9, 2026 17:07
@Xiaoy312

Xiaoy312 commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

@Mergifyio backport release/stable/6.7 servicing/6.8

@mergify

mergify Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

backport release/stable/6.7 servicing/6.8

✅ Backports have been created

Details

Cherry-pick of 1f48e64 has failed:

On branch mergify/bp/release/stable/6.7/pr-26219
Your branch is ahead of 'origin/release/stable/6.7' by 5 commits.
  (use "git push" to publish your local commits)

You are currently cherry-picking commit 1f48e64.
  (fix conflicts and run "git cherry-pick --continue")
  (use "git cherry-pick --skip" to skip this patch)
  (use "git cherry-pick --abort" to cancel the cherry-pick operation)

Changes to be committed:
	renamed:    src/Uno.UI.RuntimeTests/Tests/BindingTests/XBindIndexerControl.xaml -> src/Uno.UI.RuntimeTests/BindingTests/XBindIndexerControl.xaml
	renamed:    src/Uno.UI.RuntimeTests/Tests/BindingTests/XBindIndexerControl.xaml.cs -> src/Uno.UI.RuntimeTests/BindingTests/XBindIndexerControl.xaml.cs
	renamed:    src/Uno.UI.RuntimeTests/Tests/BindingTests/XBindOneWayLeakControl.xaml -> src/Uno.UI.RuntimeTests/BindingTests/XBindOneWayLeakControl.xaml
	renamed:    src/Uno.UI.RuntimeTests/Tests/BindingTests/XBindOneWayLeakControl.xaml.cs -> src/Uno.UI.RuntimeTests/BindingTests/XBindOneWayLeakControl.xaml.cs
	deleted:    src/Uno.UI.RuntimeTests/Tests/BindingTests/Given_BindingSourceStaleHandlers.cs

Unmerged paths:
  (use "git add <file>..." to mark resolution)
	both modified:   src/Uno.UI.RuntimeTests/Tests/Windows_UI_Xaml/Given_BindingSourceStaleHandlers.cs

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 1f48e64 has failed:

On branch mergify/bp/servicing/6.8/pr-26219
Your branch is ahead of 'origin/servicing/6.8' by 5 commits.
  (use "git push" to publish your local commits)

You are currently cherry-picking commit 1f48e64.
  (fix conflicts and run "git cherry-pick --continue")
  (use "git cherry-pick --skip" to skip this patch)
  (use "git cherry-pick --abort" to cancel the cherry-pick operation)

Changes to be committed:
	renamed:    src/Uno.UI.RuntimeTests/Tests/BindingTests/XBindIndexerControl.xaml -> src/Uno.UI.RuntimeTests/BindingTests/XBindIndexerControl.xaml
	renamed:    src/Uno.UI.RuntimeTests/Tests/BindingTests/XBindIndexerControl.xaml.cs -> src/Uno.UI.RuntimeTests/BindingTests/XBindIndexerControl.xaml.cs
	renamed:    src/Uno.UI.RuntimeTests/Tests/BindingTests/XBindOneWayLeakControl.xaml -> src/Uno.UI.RuntimeTests/BindingTests/XBindOneWayLeakControl.xaml
	renamed:    src/Uno.UI.RuntimeTests/Tests/BindingTests/XBindOneWayLeakControl.xaml.cs -> src/Uno.UI.RuntimeTests/BindingTests/XBindOneWayLeakControl.xaml.cs
	deleted:    src/Uno.UI.RuntimeTests/Tests/BindingTests/Given_BindingSourceStaleHandlers.cs

Unmerged paths:
  (use "git add <file>..." to mark resolution)
	both modified:   src/Uno.UI.RuntimeTests/Tests/Windows_UI_Xaml/Given_BindingSourceStaleHandlers.cs

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

agneszitte added a commit that referenced this pull request Nov 9, 2026
…r-26219

fix(binding): Remove stale callbacks and follow indexed collections (backport #26219)
agneszitte added a commit that referenced this pull request Nov 10, 2026
…6.7/pr-26219

fix(binding): Remove stale callbacks and follow indexed collections (backport #26219)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants