Repository navigation
Faster TypedBinding subscriptions for compiled bindings - #40819
Conversation
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Measure typed bindings whose paths have 1 to 7 objects, created by BindingSourceGen and by the handler-array constructor that XamlC emits: leaf updates, context swaps, replacing the first object after the source, and creating, applying and removing a binding. The benchmarks dispatch property changes synchronously, and use only API that main has, so that both run the same code. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
TypedBinding subscribed to every object of its path through its own PropertyChangedProxy and WeakPropertyChangedProxy. It created new proxies whenever an observed object changed, and finalized them one by one. A binding now has one TypedBindingSubscriptions. A position of the path keeps its listener while the same object and property are reported there, so a change of the observed objects allocates nothing. Listeners still reference the binding weakly, and its finalizer removes the handlers from objects that outlive it. An explicit removal that leaves no handler suppresses the finalizer. Generated code reports the observed objects through the new TypedBindingSubscriber constructor, without a delegate per object. The handler-array constructor, which XamlC output and compiled libraries call, uses the same store. User code in event accessors, getters, converters and binding diagnostic handlers can apply, remove or move the binding while it observes the path. The latest walk owns the subscriptions. The applies and unapplies that event accessors request are settled synchronously once the accessor returns, and a path that keeps changing is reported after 100,000 rounds. Exceptions from event accessors and from reading the path are reported as binding diagnostics instead of escaping into the code that applied the binding or raised the change. TypedBindingCompatibilityTests runs every scenario with both constructors. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
The generated bindings report the objects of their path through a TypedBindingSubscriber instead of an array of handler delegates. They read the same prefixes of the path as before, so property getters run as often. Objects whose type can't notify aren't observed: enums, arrays, delegates, and sealed classes and structs of the core library, such as string and DateTime. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Compiled bindings use the BindingSourceGen subscriber. C# expression bindings evaluate each member chain independently, so a null object, a Nullable<T> without a value, or a member that throws in one chain doesn't stop the binding from observing the others. A chain whose owner type can't be resolved is read through its original expression and always observed. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
XamlC is deprecated, and #40608 removes it. Before this change, BindingSourceGen and the XAML source generator emitted the same handler-array constructor, so the legacy benchmark represents all code compiled against earlier versions, not only XamlC output. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
🔵 Needs a closer look
The shared compiled-binding lifecycle rewrite and new public API need maintainer/runtime validation beyond macOS unit tests, particularly for cross-platform dispatch, GC, and iOS AOT behavior.
No open issues 🎉
What changed in this PR
This PR reduces compiled-binding subscription overhead in MAUI by replacing per-path proxies with a reusable subscription store. It preserves the legacy constructor for existing compiled libraries and XamlC output while moving both source generators to the new subscriber API.
Changes:
- Reworks subscription lifetime, cleanup, reentrant updates, and exception handling.
- Generates subscriber callbacks with type-aware notification filtering and independent C# expression-chain observation.
- Adds benchmarks and regression coverage, updates generated-code expectations, and records the new public API on all six targets.
| File | Description |
|---|---|
| src/Core/tests/Benchmarks/Benchmarks/TypedBindingScenarioBenchmarker.cs | Adds legacy binding lifecycle and update benchmarks. |
| src/Core/tests/Benchmarks/Benchmarks/TypedBindingDepthBenchmarker.cs | Compares generated and legacy bindings across path depths. |
| src/Controls/tests/Xaml.UnitTests/CSharpExpressionListeners.sgen.xaml.cs | Tests expression subscriptions with nulls and throwing members. |
| src/Controls/tests/Xaml.UnitTests/CSharpExpressionListeners.sgen.xaml | Defines expression-binding regression fixtures. |
| src/Controls/tests/Xaml.UnitTests/BindingsCompiler.xaml.cs | Tests notifications through a struct wrapper. |
| src/Controls/tests/Xaml.UnitTests/BindingsCompiler.xaml | Adds a notifying-struct binding fixture. |
| src/Controls/tests/SourceGen.UnitTests/XamlIncrementalHotReloadCSharpExpressionTests.cs | Updates Hot Reload subscriber expectations. |
| src/Controls/tests/SourceGen.UnitTests/InitializeComponent/IndexerBindings.cs | Verifies arrays are read without being observed. |
| src/Controls/tests/SourceGen.UnitTests/InitializeComponent/CompiledBindings.cs | Updates compiled-binding subscriber snapshots. |
| src/Controls/tests/SourceGen.UnitTests/CSharpExpressionListenersTests.cs | Checks generated expression subscriber statements. |
| src/Controls/tests/SourceGen.UnitTests/CSharpExpressionDiagnosticsTests.cs | Updates subscription assertions in diagnostic tests. |
| src/Controls/tests/Core.UnitTests/TypedBindingUnitTests.cs | Adapts collection checks to the subscription store. |
| src/Controls/tests/BindingSourceGen.UnitTests/ObservablePropertyTests.cs | Verifies generated observable-property subscriptions. |
| src/Controls/tests/BindingSourceGen.UnitTests/MayNotifyPropertyChangedTests.cs | Tests notification-capability classification. |
| src/Controls/tests/BindingSourceGen.UnitTests/IntegrationTests.cs | Updates generated binding expectations. |
| src/Controls/tests/BindingSourceGen.UnitTests/BindingRepresentationGenTests.cs | Updates struct notification metadata expectations. |
| src/Controls/tests/BindingSourceGen.UnitTests/BindingCodeWriterTests.cs | Updates subscriber code-generation snapshots. |
| src/Controls/src/SourceGen/SetPropertyHelpers.cs | Emits independently evaluated expression subscriptions. |
| src/Controls/src/SourceGen/CompiledBindingMarkup.cs | Uses shared subscriber generation for XAML bindings. |
| src/Controls/src/Core/TypedBindingListeners.cs | Adds listener API and reusable subscription management. |
| src/Controls/src/Core/TypedBinding.cs | Integrates the subscription store and reentrancy guards. |
| src/Controls/src/Core/PublicAPI/netstandard/PublicAPI.Unshipped.txt | Records new APIs for .NET Standard. |
| src/Controls/src/Core/PublicAPI/net/PublicAPI.Unshipped.txt | Records new APIs for .NET. |
| src/Controls/src/Core/PublicAPI/net-windows/PublicAPI.Unshipped.txt | Records new APIs for Windows. |
| src/Controls/src/Core/PublicAPI/net-maccatalyst/PublicAPI.Unshipped.txt | Records new APIs for Mac Catalyst. |
| src/Controls/src/Core/PublicAPI/net-ios/PublicAPI.Unshipped.txt | Records new APIs for iOS. |
| src/Controls/src/Core/PublicAPI/net-android/PublicAPI.Unshipped.txt | Records new APIs for Android. |
| src/Controls/src/BindingSourceGen/PathPart.cs | Extends path metadata and equality checks. |
| src/Controls/src/BindingSourceGen/PathParser.cs | Captures member and indexer result types. |
| src/Controls/src/BindingSourceGen/ITypeSymbolExtensions.cs | Classifies types that may notify property changes. |
| src/Controls/src/BindingSourceGen/BindingInvocationDescription.cs | Adds notification-capability metadata to type descriptions. |
| src/Controls/src/BindingSourceGen/BindingCodeWriter.cs | Emits subscribers and tracks required unsafe accessors. |
Review effort: Balanced
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
Selected Tests
🧪 Test selection — click to expand
🧪 UI tests — the full suite on every platform✅ maui-pr-uitests #1704493 passed. GPT-6.2 Sol: Run the full UI suite on all four platforms because the shared compiled-binding runtime changes how controls receive updates. 🧪 Ran — 77 categories on Android, iOS, MacCatalyst, WindowsThe complete 📊 Results — succeeded: 134 passed, 0 failed of 134 jobs🔗 All test results · Build logs 🧪 Device tests —
|
| Platform | Categories |
|---|---|
| Android | Controls.Accessibility, Controls.Animations, Controls.Application, Controls.Behavior, Controls.Border, Controls.BoxView, Controls.Button, Controls.CarouselView, Controls.CheckBox, Controls.CollectionView, Controls.Compatibility, Controls.ContentView, Controls.DatePicker, Controls.Dispatcher, Controls.Editor, Controls.Element, Controls.Entry, Controls.FlexLayout, Controls.FlyoutPage, Controls.Frame, Controls.Gesture, Controls.HybridWebView, Controls.Image, Controls.Label, Controls.Layout, Controls.Lifecycle, Controls.Map, Controls.Mapper, Controls.Memory, Controls.MenuFlyout, Controls.Modal, Controls.NavigationPage, Controls.Page, Controls.PageTransitions, Controls.Path, Controls.Picker, Controls.RadioButton, Controls.RefreshView, Controls.ScrollView, Controls.SearchBar, Controls.Shape, Controls.Shell, Controls.Slider, Controls.SwipeView, Controls.Switch, Controls.TabbedPage, Controls.TemplatedView, Controls.TextInput, Controls.Toolbar, Controls.View, Controls.VisualElement, Controls.VisualElementTree, Controls.WebView, Controls.Window, Controls.WindowOverlay, Controls.Xaml |
| iOS | Controls.Accessibility, Controls.Animations, Controls.Application, Controls.Behavior, Controls.Border, Controls.BoxView, Controls.Button, Controls.CarouselView, Controls.CheckBox, Controls.CollectionView, Controls.Compatibility, Controls.ContentView, Controls.DatePicker, Controls.Dispatcher, Controls.Editor, Controls.Element, Controls.Entry, Controls.FlexLayout, Controls.FlyoutPage, Controls.Frame, Controls.Gesture, Controls.HybridWebView, Controls.Image, Controls.Label, Controls.Layout, Controls.Lifecycle, Controls.Map, Controls.Mapper, Controls.Memory, Controls.MenuFlyout, Controls.Modal, Controls.NavigationPage, Controls.Page, Controls.PageTransitions, Controls.Path, Controls.Picker, Controls.RadioButton, Controls.RefreshView, Controls.ScrollView, Controls.SearchBar, Controls.Shape, Controls.Shell, Controls.Slider, Controls.SwipeView, Controls.Switch, Controls.TabbedPage, Controls.TemplatedView, Controls.TextInput, Controls.Toolbar, Controls.View, Controls.VisualElement, Controls.VisualElementTree, Controls.WebView, Controls.Window, Controls.WindowOverlay, Controls.Xaml |
| MacCatalyst | Controls.Accessibility, Controls.Animations, Controls.Application, Controls.Behavior, Controls.Border, Controls.BoxView, Controls.Button, Controls.CarouselView, Controls.CheckBox, Controls.CollectionView, Controls.Compatibility, Controls.ContentView, Controls.DatePicker, Controls.Dispatcher, Controls.Editor, Controls.Element, Controls.Entry, Controls.FlexLayout, Controls.FlyoutPage, Controls.Frame, Controls.Gesture, Controls.HybridWebView, Controls.Image, Controls.Label, Controls.Layout, Controls.Lifecycle, Controls.Map, Controls.Mapper, Controls.Memory, Controls.MenuFlyout, Controls.Modal, Controls.NavigationPage, Controls.Page, Controls.PageTransitions, Controls.Path, Controls.Picker, Controls.RadioButton, Controls.RefreshView, Controls.ScrollView, Controls.SearchBar, Controls.Shape, Controls.Shell, Controls.Slider, Controls.SwipeView, Controls.Switch, Controls.TabbedPage, Controls.TemplatedView, Controls.TextInput, Controls.Toolbar, Controls.View, Controls.VisualElement, Controls.VisualElementTree, Controls.WebView, Controls.Window, Controls.WindowOverlay, Controls.Xaml |
| Windows | Controls.Accessibility, Controls.Animations, Controls.Application, Controls.Behavior, Controls.Border, Controls.BoxView, Controls.Button, Controls.CarouselView, Controls.CheckBox, Controls.CollectionView, Controls.Compatibility, Controls.ContentView, Controls.DatePicker, Controls.Dispatcher, Controls.Editor, Controls.Element, Controls.Entry, Controls.FlexLayout, Controls.FlyoutPage, Controls.Frame, Controls.Gesture, Controls.HybridWebView, Controls.Image, Controls.Label, Controls.Layout, Controls.Lifecycle, Controls.Map, Controls.Mapper, Controls.Memory, Controls.MenuFlyout, Controls.Modal, Controls.NavigationPage, Controls.Page, Controls.PageTransitions, Controls.Path, Controls.Picker, Controls.RadioButton, Controls.RefreshView, Controls.ScrollView, Controls.SearchBar, Controls.Shape, Controls.Shell, Controls.Slider, Controls.SwipeView, Controls.Switch, Controls.TabbedPage, Controls.TemplatedView, Controls.TextInput, Controls.Toolbar, Controls.View, Controls.VisualElement, Controls.VisualElementTree, Controls.WebView, Controls.Window, Controls.WindowOverlay, Controls.Xaml |
📊 Results — failed: 4 passed, 1 failed of 5 jobs
❌ Failed tests (1)
| Test | Failed on | Error |
|---|---|---|
CollectionViewTests.[CollectionView] [NavigationRenderer] Back at the end after a ScrollTo away, the list keeps the end in view as the last item shrinks |
Unknown | Following the end, the list should keep the end in view as the last item shrinks. Distance to the end: 370. |
🔗 All test results · Build logs
| Job | Result |
|---|---|
| net12.0 direct device tests Catalyst controls CoreCLR macos27 | ❌ failed |
| net12.0 direct device tests Android API 33 controls coreclr | ✅ succeeded |
| net12.0 direct device tests iOS controls coreclr macos27 All | ✅ succeeded |
| net12.0 direct device tests Windows controls packaged | ✅ succeeded |
| net12.0 direct device tests Windows controls unpackaged | ✅ succeeded |
⏭️ Skipped — what neither suite runs
Device tests — 49 categories, 0 platforms
Categories not run: Core.ActivityIndicator, Core.Animation, Core.Application, Core.Border, Core.BoxView, Core.Button, Core.CheckBox, Core.ContentView, Core.DatePicker, Core.Dispatcher, Core.Editor, Core.Element, Core.Entry, Core.FlowDirection, Core.FlyoutView, Core.Fonts, Core.Formatting, Core.Graphics, Core.GraphicsView, Core.Image, Core.ImageButton, Core.ImageSource, Core.IndicatorView, Core.Label, Core.Layout, Core.Lifecycle, Core.MauiContext, Core.Memory, Core.NavigationPage, Core.Page, Core.Picker, Core.ProgressBar, Core.RadioButton, Core.RefreshView, Core.ScrollView, Core.SearchBar, Core.ShapeView, Core.Slider, Core.Stepper, Core.SwipeView, Core.Switch, Core.TimePicker, Core.View, Core.WebView, Core.Window, Core.WindowOverlay, Graphics, Essentials, BlazorWebView
Each skipped platform and project is listed as a maui-pr-devicetests (skipped) … status on this commit. Use /azp run maui-pr-devicetests for the full suite.
🤖 Why these tests — AI rationale (GPT-6.2 Sol + MAI Code 2)
UI tests
Each model chose independently; every test that runs was selected by at least one of them.
| Platform | GPT-6.2 Sol | MAI Code 2 |
|---|---|---|
| Android | all categories | all categories |
| iOS | all categories | all categories |
| MacCatalyst | all categories | all categories |
| Windows | all categories | all categories |
GPT-6.2 Sol — Run the full UI suite on all four platforms because the shared compiled-binding runtime changes how controls receive updates.
- TypedBinding and its listener store change property updates and rebinding across controls and platforms.
- Both generators use the new path; existing XamlC output still uses the changed runtime.
- No Android-specific Material3 rendering change warrants a separate lane.
MAI Code 2 — Cross-platform TypedBinding subscription and source-generation overhaul; runs the full UI and Controls device suites.
- TypedBinding runtime behavior and generated subscription code are shared by compiled bindings across all platforms and controls, so a broad UI smoke is warranted.
- Both XAML binding generators now emit the new listener arguments, affecting what the UI test app builds and runs by default.
- The legacy constructor and all binding path/lifetime scenarios were rewritten, so limiting validation to a single control would miss representative binding failures.
- Device validation is limited to the Controls project; Core handlers, Graphics, Essentials, and BlazorWebView are not changed.
Device tests
Each model chose independently; every test that runs was selected by at least one of them.
| Platform | GPT-6.2 Sol | MAI Code 2 |
|---|---|---|
| Android | Controls.Xaml, Controls.Memory |
Controls.Accessibility, Controls.Animations, Controls.Application, Controls.Behavior, Controls.Border, Controls.BoxView, Controls.Button, Controls.CarouselView, Controls.CheckBox, Controls.CollectionView, Controls.Compatibility, Controls.ContentView, Controls.DatePicker, Controls.Dispatcher, Controls.Editor, Controls.Element, Controls.Entry, Controls.FlexLayout, Controls.FlyoutPage, Controls.Frame, Controls.Gesture, Controls.HybridWebView, Controls.Image, Controls.Label, Controls.Layout, Controls.Lifecycle, Controls.Map, Controls.Mapper, Controls.Memory, Controls.MenuFlyout, Controls.Modal, Controls.NavigationPage, Controls.Page, Controls.PageTransitions, Controls.Path, Controls.Picker, Controls.RadioButton, Controls.RefreshView, Controls.ScrollView, Controls.SearchBar, Controls.Shape, Controls.Shell, Controls.Slider, Controls.SwipeView, Controls.Switch, Controls.TabbedPage, Controls.TemplatedView, Controls.TextInput, Controls.Toolbar, Controls.View, Controls.VisualElement, Controls.VisualElementTree, Controls.WebView, Controls.Window, Controls.WindowOverlay, Controls.Xaml |
| iOS | Controls.Xaml, Controls.Memory |
Controls.Accessibility, Controls.Animations, Controls.Application, Controls.Behavior, Controls.Border, Controls.BoxView, Controls.Button, Controls.CarouselView, Controls.CheckBox, Controls.CollectionView, Controls.Compatibility, Controls.ContentView, Controls.DatePicker, Controls.Dispatcher, Controls.Editor, Controls.Element, Controls.Entry, Controls.FlexLayout, Controls.FlyoutPage, Controls.Frame, Controls.Gesture, Controls.HybridWebView, Controls.Image, Controls.Label, Controls.Layout, Controls.Lifecycle, Controls.Map, Controls.Mapper, Controls.Memory, Controls.MenuFlyout, Controls.Modal, Controls.NavigationPage, Controls.Page, Controls.PageTransitions, Controls.Path, Controls.Picker, Controls.RadioButton, Controls.RefreshView, Controls.ScrollView, Controls.SearchBar, Controls.Shape, Controls.Shell, Controls.Slider, Controls.SwipeView, Controls.Switch, Controls.TabbedPage, Controls.TemplatedView, Controls.TextInput, Controls.Toolbar, Controls.View, Controls.VisualElement, Controls.VisualElementTree, Controls.WebView, Controls.Window, Controls.WindowOverlay, Controls.Xaml |
| MacCatalyst | Controls.Xaml, Controls.Memory |
Controls.Accessibility, Controls.Animations, Controls.Application, Controls.Behavior, Controls.Border, Controls.BoxView, Controls.Button, Controls.CarouselView, Controls.CheckBox, Controls.CollectionView, Controls.Compatibility, Controls.ContentView, Controls.DatePicker, Controls.Dispatcher, Controls.Editor, Controls.Element, Controls.Entry, Controls.FlexLayout, Controls.FlyoutPage, Controls.Frame, Controls.Gesture, Controls.HybridWebView, Controls.Image, Controls.Label, Controls.Layout, Controls.Lifecycle, Controls.Map, Controls.Mapper, Controls.Memory, Controls.MenuFlyout, Controls.Modal, Controls.NavigationPage, Controls.Page, Controls.PageTransitions, Controls.Path, Controls.Picker, Controls.RadioButton, Controls.RefreshView, Controls.ScrollView, Controls.SearchBar, Controls.Shape, Controls.Shell, Controls.Slider, Controls.SwipeView, Controls.Switch, Controls.TabbedPage, Controls.TemplatedView, Controls.TextInput, Controls.Toolbar, Controls.View, Controls.VisualElement, Controls.VisualElementTree, Controls.WebView, Controls.Window, Controls.WindowOverlay, Controls.Xaml |
| Windows | Controls.Xaml, Controls.Memory |
Controls.Accessibility, Controls.Animations, Controls.Application, Controls.Behavior, Controls.Border, Controls.BoxView, Controls.Button, Controls.CarouselView, Controls.CheckBox, Controls.CollectionView, Controls.Compatibility, Controls.ContentView, Controls.DatePicker, Controls.Dispatcher, Controls.Editor, Controls.Element, Controls.Entry, Controls.FlexLayout, Controls.FlyoutPage, Controls.Frame, Controls.Gesture, Controls.HybridWebView, Controls.Image, Controls.Label, Controls.Layout, Controls.Lifecycle, Controls.Map, Controls.Mapper, Controls.Memory, Controls.MenuFlyout, Controls.Modal, Controls.NavigationPage, Controls.Page, Controls.PageTransitions, Controls.Path, Controls.Picker, Controls.RadioButton, Controls.RefreshView, Controls.ScrollView, Controls.SearchBar, Controls.Shape, Controls.Shell, Controls.Slider, Controls.SwipeView, Controls.Switch, Controls.TabbedPage, Controls.TemplatedView, Controls.TextInput, Controls.Toolbar, Controls.View, Controls.VisualElement, Controls.VisualElementTree, Controls.WebView, Controls.Window, Controls.WindowOverlay, Controls.Xaml |
GPT-6.2 Sol — Run Controls.Xaml and Controls.Memory on all four platforms to cover XAML integration and listener lifetime.
- Controls.Xaml covers on-device XAML and binding integration.
- Controls.Memory covers lifetime regressions from weak subscription and cleanup changes.
- No handler, Graphics, Essentials, or BlazorWebView runtime changes.
MAI Code 2 — Shared TypedBinding runtime and generated compiled-binding paths affect Controls device tests on every platform.
- TypedBinding and its subscription store are platform-neutral Controls runtime code, so Android, iOS, Mac Catalyst, and Windows can exercise the behavior.
- Compiled bindings and the legacy handler-array constructor are used across Controls, requiring the full Controls test set rather than one control category.
- Core handler, Graphics, Essentials, and BlazorWebView test projects are outside the changed code and deliberately excluded.
Generated by /review run-tests. A targeted run is a fast signal, not full-suite certification.
There was a problem hiding this comment.
Expert Review — No findings
Reviewed commit 4c07c58.
Listen(object?) is unshipped API that #40819 added, so no compiled code needs it. Generated subscribers never pass a null literal or a ref struct, the only arguments that need the object overload. Subscribers for C# expressions in XAML pass an object? local, which binds to Listen<object>. For a reference type, Listen<T> runs the same code as the object overload did. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
#40844) <!-- copilot-assessment:v1 --> ### Agent assessment Self-reported assessment, not an independent review. Assessed revision: `21f7caeb2041cdcf0382a632dca83e4a49365107` | Dimension | Assessment | Rationale | |---|---|---| | Change confidence | 9.5/10 | ↑ On current `main` the project fails to build with the same two xUnit1051 errors as CI. With this change it builds with no warnings, and all 157 tests pass in Debug and Release.<br>↑ Test-only change. The assertions are unchanged.<br>↓ Validated locally on macOS only. CI on this PR is pending. | | Diagnosis confidence | 10/10 | ↑ The analyzer errors name both calls, and restoring `main`'s version of the file reproduces them.<br>↑ #40661 moved the project to xUnit v3 after the branch of #40819 was created. | | Evidence fit | 10/10 | ↑ These two errors are the only failure in the four failed Run Unit Tests legs of maui-pr build 1704463, the PR build of #40819. Every other test project passed in all four legs. | <!-- /copilot-assessment --> <!-- Please let the below note in for people that find this PR --> > [!NOTE] > Are you waiting for the changes in this PR to be merged? > It would be very helpful if you could [test the resulting artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). The break is on `main`, where both #40819 and #40661 landed. For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change <!-- Enter description of the fix in this section --> `Controls.BindingSourceGen.UnitTests` doesn't build on `main`: ``` MayNotifyPropertyChangedTests.cs(51,5): error xUnit1051: Calls to methods which accept CancellationToken should use TestContext.Current.CancellationToken to allow test cancellation to be more responsive. MayNotifyPropertyChangedTests.cs(67,16): error xUnit1051: Calls to methods which accept CancellationToken should use TestContext.Current.CancellationToken to allow test cancellation to be more responsive. ``` #40819 added `MayNotifyPropertyChangedTests` on a branch created before #40661 moved the unit tests to xUnit v3. The xUnit v3 analyzers report these two calls as errors. The PR build of #40819 ([maui-pr 1704463](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1704463)) failed the four Run Unit Tests legs (Windows and macOS, Debug and Release) for this reason only. The PR was merged with those legs red. Until this is fixed, they fail on `main` and in every PR build that merges `main`. `Controls.Core.UnitTests` also fails on `main`, for an unrelated reason. 31 async leak tests have failed since #40824, whose own PR build [1704502](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1704502) failed them on all four unit-test legs. This PR doesn't fix those, so the unit-test legs stay red until they're fixed too. This passes `TestContext.Current.CancellationToken` to `CSharpSyntaxTree.ParseText` and `Compilation.GetDiagnostics`, as the other tests in the project already do. The assertions don't change. Validation on macOS arm64 with the pinned SDK 12.0.100-alpha.1.26523.103: | Command | Result | | --- | --- | | `dotnet build src/Controls/tests/BindingSourceGen.UnitTests/Controls.BindingSourceGen.UnitTests.csproj -c Debug -p:MauiPlatforms= -p:IncludePreviousTfms=false`, with `main`'s version of the test file | Failed with the two errors above | | The same command with this change, with `-c Debug` and with `-c Release` | Succeeded, 0 warnings | | `dotnet test --project src/Controls/tests/BindingSourceGen.UnitTests/Controls.BindingSourceGen.UnitTests.csproj -c Debug --no-build`, and the same with `-c Release` | Passed, 157 of 157 in each | ### Issues Fixed <!-- Please make sure that there is a bug logged for the issue being fixed. The bug should describe the problem and how to reproduce it. --> No issue is filed. This fixes the build break on `main` from #40819. ### Let AI finish this PR - [ ] **Let the MAUI agent address review feedback and fix remaining issues on this PR.** Maintainers still decide whether it is merged. For PRs from forks, keep "Allow edits by maintainers" on so the agent can push to your branch; otherwise it opens a follow-up PR that keeps your commits. <!-- Verify the target branch follows the release workflow in docs/ReleaseBranchWorkflow.md. Infrastructure and documentation changes should target the branch where they apply. --> Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
#40856) <!-- copilot-assessment:v1 --> ### Agent assessment Self-reported assessment, not an independent review. Assessed revision: `cecdfd482a7c8c2281a8e086f7782d553eb23efa` | Dimension | Assessment | Rationale | |---|---|---| | Change confidence | 9/10 | ↑ `TypedBinding` only calls a subscriber for `OneWay` and `TwoWay` bindings, and `Mode` can't change once a binding is applied. So for a literal `OneTime` mode, the removed subscriber was dead code.<br>↑ SourceGen (940 passed) and XAML (2,341 passed) unit tests pass locally. The new generator test fails on main's generator for the `OneTime` case only.<br>↑ The assembly with the measured page shrinks by 21% (IL only) and 13% (ReadyToRun), and its first creation is faster under both JIT and ReadyToRun.<br>↓ No CI or device runs yet, because the PR pipelines are disabled. | <!-- /copilot-assessment --> <!-- Please let the below note in for people that find this PR --> > [!NOTE] > Are you waiting for the changes in this PR to be merged? > It would be very helpful if you could [test the resulting artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). This is .NET 12 performance work on the compiled bindings from #40819, which is on `main`. For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change <!-- Enter description of the fix in this section --> This is a follow-up to #40819. The XAML source generator compiles each `{Binding}` with an `x:DataType` into a `TypedBinding`. Since #40819, that binding gets a subscriber lambda, which reports the objects on its path that the binding observes. A binding whose `Mode` is `OneTime` reads its path once and never observes it: `TypedBinding` only calls the subscriber for `OneWay` and `TwoWay` bindings. When `Mode` is the literal `OneTime`, the generator already leaves out the setter. Now it also leaves out the subscriber. It emits `listenerCount: 0, subscriber: null`, as it already does for a self-binding like `{Binding .}`. A `Mode` that isn't a literal, such as `{x:Static BindingMode.OneTime}`, keeps its subscriber. Generated code for `{Binding Child.Q1, Mode=OneTime}`, before: ```csharp return new global::Microsoft.Maui.Controls.Internals.TypedBinding<global::Test.TestViewModel, string?>( getter: source => (source.Child?.Q1, true), setter, listenerCount: 2, subscriber: static (global::Test.TestViewModel source, ref global::Microsoft.Maui.Controls.Internals.TypedBindingListeners listeners) => { if (source is null) return; listeners.Listen(source, "Child"); if (source.Child is not { } part1) return; listeners.Listen(part1, "Q1"); }) { Mode = extension.Mode, }; ``` After: ```csharp return new global::Microsoft.Maui.Controls.Internals.TypedBinding<global::Test.TestViewModel, string?>( getter: source => (source.Child?.Q1, true), setter, listenerCount: 0, subscriber: null) { Mode = extension.Mode, }; ``` For each `OneTime` binding, the page no longer has the lambda method and the static field that caches its delegate. It also skips allocating that delegate the first time the binding is created. #### Measurements How the measurements were made: - **Generated page.** A temporary test, which isn't part of this PR, ran the XAML source generator from main and from this PR. Its input was a page with 100 `Label`s bound with `Mode=OneTime`: 50 one-level paths like `P3` and 50 two-level paths like `Child.Q3`. The same assembly also has a small warm-up page with two `OneTime` bindings and one `OneWay` binding. The test emitted the assembly with Release optimizations. - **Timing.** A console app loaded that assembly with Release builds of MAUI. It creates the warm-up page first, so that the measured creation of the 100-binding page doesn't include MAUI's own first-use costs. Each first-creation sample is a fresh process, alternating main and this PR, with 31 pairs. - **ReadyToRun.** The ReadyToRun builds come from `dotnet publish -c Release -r osx-arm64 -p:PublishReadyToRun=true`. - **Environment.** Apple Silicon, .NET 12 (`12.0.100-alpha.1.26523.103`).  The labels on the timing charts are the median paired difference. | Measurement | main | This PR | Change | |---|---:|---:|---:| | Page assembly, IL only | 73,728 B | 58,368 B | −15,360 B (−21%) | | Page assembly, ReadyToRun | 288,256 B | 250,368 B | −37,888 B (−13%) | | Methods and fields in the page assembly | 366 and 230 | 264 and 128 | −102 each | | First creation of the page, JIT (median) | 9,085 µs | 8,269 µs | −681 µs (95% CI −975 to −460) | | First creation of the page, ReadyToRun (median) | 945 µs | 887 µs | −56 µs (95% CI −76 to −46) | | Allocated by the first creation | 648,840 B | 643,240 B | −5,600 B | Steady-state creation of the page shows no significant difference. The paired 95% confidence intervals are −32 to +73 µs per page with JIT and −160 to +101 µs with ReadyToRun, and allocations are identical at 635,224 B per page. Per `OneTime` binding, that's about 150 B of IL-only assembly and 370 B of ReadyToRun image, one method and one field less. The page assembly has 102 `OneTime` bindings: the 100 in the measured page and 2 in the warm-up page. #### Changes - `CompiledBindingMarkup.cs`: for a literal `OneTime` mode, emit `listenerCount: 0, subscriber: null` instead of the subscriber. - New theory `OnlyBindingsThatCanObserveTheirPathGetASubscriber` in the SourceGen unit tests. A literal `OneTime` mode gets no subscriber. `OneWay`, `TwoWay`, `Default`, `{x:Static BindingMode.OneTime}` and an unset mode keep theirs. - `BindingsCompiler` XAML test: a `OneTime` label keeps its first value after its source changes. This runs for the Runtime, XamlC and SourceGen inflators. #### Validation These were run on macOS arm64 with the pinned SDK. Each project was built first with `dotnet build <project> -c Debug -p:MauiPlatforms= -p:IncludePreviousTfms=false -p:PublicApiType=Validate`. | Command | Result | | --- | --- | | `dotnet test --project src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj -c Debug --no-build` | 940 passed, 71 skipped | | The same command with `--filter-method '*OnlyBindingsThatCanObserveTheirPathGetASubscriber'`, against main's generator | 1 of 6 cases failed, the `Mode=OneTime` one, as expected | | `dotnet test --project src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj -c Debug --no-build` | 2,341 passed, 8 skipped | | `dotnet format whitespace --folder --include <changed files> --verify-no-changes` | No changes | Until #40844 merges, the unit-test legs of this PR's CI will fail on `BindingSourceGen.UnitTests`. They'll also fail on the 31 leak tests from #40824 until those are fixed. ### Issues Fixed <!-- Please make sure that there is a bug logged for the issue being fixed. The bug should describe the problem and how to reproduce it. --> No issue is filed. This is a follow-up to #40819. ### Let AI finish this PR - [ ] **Let the MAUI agent address review feedback and fix remaining issues on this PR.** Maintainers still decide whether it is merged. For PRs from forks, keep "Allow edits by maintainers" on so the agent can push to your branch; otherwise it opens a follow-up PR that keeps your commits. <!-- Verify the target branch follows the release workflow in docs/ReleaseBranchWorkflow.md. Infrastructure and documentation changes should target the branch where they apply. --> Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
…#40858) <!-- copilot-assessment:v1 --> ### Agent assessment Self-reported assessment, not an independent review. Assessed revision: `2e8d9b4df24c1866e6bfcdcde07873a52eac31ae` | Dimension | Assessment | Rationale | |---|---|---| | Change confidence | 9/10 | ↑ The code moves unchanged to the base class, except that `ApplyCore` is split into helpers and two `catch` clauses per handler are merged into one with the same effect. An independent line-by-line review found no behavior change.<br>↑ Controls.Core (the same 31 known failures as main), SourceGen (934 passed), XAML (2,341 passed) and BindingSourceGen (157 passed) unit tests pass locally.<br>↑ Each value type JIT-compiles 3 methods instead of 12. The first apply of 10 value-type bindings is 60% faster with JIT and 64% faster with ReadyToRun. Steady-state times are within about 1%, and allocations are unchanged.<br>↑ In an Android app, 25 fewer methods and 6 KB less IL are JIT-compiled before the first frame.<br>↓ No CI or device test runs yet, because the PR pipelines are disabled.<br>↓ NativeAOT and iOS weren't measured. | <!-- /copilot-assessment --> <!-- Please let the below note in for people that find this PR --> > [!NOTE] > Are you waiting for the changes in this PR to be merged? > It would be very helpful if you could [test the resulting artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). This is .NET 12 performance work on the compiled bindings from #40819, which is on `main`. For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change <!-- Enter description of the fix in this section --> This is a follow-up to #40819. The runtime compiles the methods of a generic class again for every value type that the class is instantiated with. `TypedBinding<MyViewModel, bool>`, `TypedBinding<MyViewModel, double>`, `TypedBinding<MyViewModel, DateTime>` and every enum each get their own code, while reference types share one copy. ReadyToRun can't precompile most of these instantiations. MAUI's own image only has the ones that MAUI uses itself, and Android's default partial ReadyToRun only compiles the methods in MAUI's startup profiles. So the first time a compiled binding reads a value type, the JIT compiles 12 methods of `TypedBinding<TSource, TProperty>` for it: - 9 when the binding is first applied: `.ctor`, `Apply`, `ApplyToResolvedSource`, `ApplyCore`, `CacheDefaultValue`, `ClearAncestryChangeSubscriptions`, `GetSourceValue`, `Settle` and `Unapply`. - 3 when the source or the target changes: `OnSourceChanged`, `GetTargetValue` and `Apply(bool)`. Only a few lines of these methods depend on the types of the source and the value. This PR moves the state of the binding, and every method that depends on neither `TSource` nor `TProperty`, into the non-generic `TypedBindingBase`. `TypedBinding<TSource, TProperty>` keeps: - its constructors, `Clone` and `ListenToHandlers`; - a slimmer `ApplyCore`, which type-checks the source, walks the path through the subscriber or the handlers, and runs the getter; - `UpdateSource`, which runs the setter. It's a separate method, so that only `TwoWay` and `OneWayToSource` bindings compile it. The rest of `ApplyCore` moved to the base-class methods `BeginApply`, `CompleteWalk`, `UpdateTarget` and `TryGetValueForSource`. `ApplyCore` is now an abstract member of `TypedBindingBase`, which calls it. Its IL shrinks from 1,075 to 548 bytes, and from 5 exception-handling clauses to 2. The getter's and the setter's `catch (Exception ex) when (IsPathException(ex))` and the `catch` that follows it each became one `catch` that checks `IsPathException`, with the same effect. Behavior doesn't change. The steps of an apply run in the same order, with the same checks for an apply that user code superseded. There are no public API changes, and the generators and the code they generate are unchanged. `ApplyCore` still reads `_removingTarget` and `_subscriptions` directly, rather than through small helpers. crossgen2 inlines such a helper into every precompiled caller and then emits no code for the helper itself, so the JIT-compiled `ApplyCore` of a value type would have to compile the helper too. #### Measurements  The labels on the timing charts are the median paired difference. **First use, console app.** A console app referenced Release builds of MAUI from main and from this PR. It first warms MAUI up with a `string` binding that goes through the same steps. Then, for 10 value types (`bool`, `int`, `double`, `float`, `long`, `DateTime`, `TimeSpan`, `Thickness`, `FontAttributes` and `TextAlignment`), it creates a binding the way the source generators do and goes through two phases: - **First apply:** `SetBinding`, then setting the binding context. - **Updates and removal:** changing the source, changing the target, swapping the binding context, and removing the binding. The bindings are `TwoWay`, so that the setter runs too. `JitInfo` counts the methods that the main thread JIT-compiles, and runtime events list them. Each sample is a fresh process, alternating main and this PR, with 41 pairs. The app ran with IL-only MAUI assemblies (JIT) and with `dotnet publish -c Release -r osx-arm64 -p:PublishReadyToRun=true` (ReadyToRun). | Per value type | main | This PR | |---|---:|---:| | Methods JIT-compiled at the first apply | 9 | 2 (`.ctor`, `ApplyCore`) | | Methods JIT-compiled by updates and removal | 3 | 1 (`UpdateSource`), only for `TwoWay` and `OneWayToSource` | | IL that the JIT compiles | 2,233 B | 683 B | With ReadyToRun, 3 of the 10 types don't need the JIT on either branch, because MAUI's own image has their instantiations. | 10 value types, median of 41 fresh processes | main | This PR | Change | |---|---:|---:|---:| | First apply, JIT | 6,776 µs | 2,665 µs | −4,081 µs (95% CI −4,136 to −4,041), −60% | | First apply, ReadyToRun | 5,227 µs | 1,864 µs | −3,336 µs (95% CI −3,469 to −3,241), −64% | | Updates and removal, JIT | 1,144 µs | 759 µs | −372 µs (95% CI −424 to −359), −33% | | Updates and removal, ReadyToRun | 521 µs | 279 µs | −245 µs (95% CI −248 to −240), −47% | | First `string` binding, including MAUI's own first use, JIT | 8,209 µs | 8,195 µs | −57 µs (95% CI −221 to +81) | | First `string` binding, including MAUI's own first use, ReadyToRun | 5,569 µs | 5,519 µs | −89 µs (95% CI −133 to +136) | **Android.** A CollectionView app with 1,000 rows was built twice in Release for android-arm64, with MAUI's default partial ReadyToRun and startup profiles. Its rows bind with `x:DataType` to `string`, `int`, `double`, `bool`, `DateTime`, `FontAttributes` and `Color` properties. Both APKs were built from an older tree, with main's `TypedBinding.cs` and `TypedBindingListeners.cs`; the second one only swaps in this PR's `TypedBinding.cs`. The app logs `JitInfo` counters when its first frame is ready. There were 50 pairs of cold starts, in ABBA order, on an API 35 arm64 emulator. | Before the first frame, median of 50 cold starts | main | This PR | Change | |---|---:|---:|---:| | JIT-compiled methods | 973 | 949 | −25 (95% CI −25 to −24) | | JIT-compiled IL | 73,723 B | 67,749 B | −5,976 B (−8.1%) | | JIT time | 70.8 ms | 65.7 ms | −3.8 ms (95% CI −7.8 to +0.3) | The host was heavily loaded during these runs (load average up to 34). This made the JIT time noisy, and the time to the first frame showed no significant difference. MAUI's startup profiles predate #40819. They list `ApplyCore` with its old signature, so main doesn't precompile it either. A crossgen2 map of this PR's APK shows that the moved methods that the profiles list, like `Unapply` and `ApplyToResolvedSource`, are still precompiled. The new base-class methods, like `BeginApply` and `UpdateTarget`, aren't, so they're JIT-compiled once per process until the profiles are refreshed. The numbers above include that. **Steady state.** A console app ran the same MAUI builds interleaved; each value is the best of 11 runs. | Operation | main | This PR | Change | |---|---:|---:|---:| | A `string` source property changes, path of 1 | 21.9 ns | 21.7 ns | −0.7% | | A `string` source property changes, path of 3 | 26.4 ns | 26.5 ns | +0.3% | | An `int` source property changes | 24.6 ns | 24.8 ns | +0.8% | | A `TwoWay` `double` target changes and updates the source | 64.9 ns | 65.0 ns | +0.2% | | The binding context of a path of 3 changes | 100.0 ns | 99.7 ns | −0.3% | | Create, apply and remove a `OneWay` binding, path of 1 | 256.9 ns | 258.8 ns | +0.7% | | Create, apply and remove a `OneWay` binding, path of 3 | 401.0 ns | 402.2 ns | +0.3% | | Create, apply and remove a `OneTime` binding | 130.4 ns | 129.3 ns | −0.9% | | Create, apply and remove an `int` binding | 271.2 ns | 271.8 ns | +0.2% | Allocations are identical. A rerun of the property changes with 21 pairs measured +0.18 ns for `int` and +0.78 ns for the `TwoWay` update (paired medians). This is consistent with the virtual call to `ApplyCore` and the calls to the base-class helpers. `Microsoft.Maui.Controls.dll` grows by 512 B of IL (1,773,568 to 1,774,080 B). Its osx-arm64 ReadyToRun image shrinks by 52 KB (5,236,224 to 5,184,000 B). All measurements ran on Apple Silicon with .NET 12 (`12.0.100-alpha.1.26523.103`). #### Changes - `TypedBinding.cs`: moves the state and every method that depends on neither `TSource` nor `TProperty` from `TypedBinding<TSource, TProperty>` to `TypedBindingBase`, as described above. - `TypedBindingUnitTests.cs`: `BindingDoesNotStayAliveForDeadTarget` reads the `_subscriptions` field from `TypedBindingBase`, which now declares it. #### Validation These were run on macOS arm64 with the pinned SDK. Each project was built first with `dotnet build <project> -c Debug -p:MauiPlatforms= -p:IncludePreviousTfms=false -p:PublicApiType=Validate`. | Command | Result | | --- | --- | | `dotnet test --project src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj -c Debug --no-build` | 7,684 passed, 30 skipped, 31 failed. The failures are the leak tests that #40824 broke, the same set as on main. | | `dotnet test --project src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj -c Debug --no-build` | 934 passed, 71 skipped | | `dotnet test --project src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj -c Debug --no-build` | 2,341 passed, 8 skipped | | `dotnet test --project src/Controls/tests/BindingSourceGen.UnitTests/Controls.BindingSourceGen.UnitTests.csproj -c Debug --no-build`, with #40844 applied locally | 157 passed | | `dotnet format whitespace --folder --include <changed files> --verify-no-changes` | No changes | Until #40844 merges, the unit-test legs of this PR's CI will fail on `BindingSourceGen.UnitTests`. They'll also fail on the 31 leak tests from #40824 until those are fixed. ### Issues Fixed <!-- Please make sure that there is a bug logged for the issue being fixed. The bug should describe the problem and how to reproduce it. --> No issue is filed. This is a follow-up to #40819. ### Let AI finish this PR - [ ] **Let the MAUI agent address review feedback and fix remaining issues on this PR.** Maintainers still decide whether it is merged. For PRs from forks, keep "Allow edits by maintainers" on so the agent can push to your branch; otherwise it opens a follow-up PR that keeps your commits. <!-- Verify the target branch follows the release workflow in docs/ReleaseBranchWorkflow.md. Infrastructure and documentation changes should target the branch where they apply. --> Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
<!-- copilot-assessment:v1 --> ### Agent assessment Self-reported assessment, not an independent review. Assessed revision: `2481e06d64f2246b4362b5b7b768ac7c531a0e64` | Dimension | Assessment | Rationale | |---|---|---| | Change confidence | 8.5/10 | ↑ The Controls.Core, BindingSourceGen, SourceGen and XAML unit tests pass locally at this revision, including the new test. The 31 Controls.Core failures, all leak tests, also fail on main without this change.<br>↑ The subscribers of C# expressions in XAML pass an `object?` local. They compile against `Listen<object>`, and their tests pass.<br>↑ Each walk through a struct allocates exactly one boxed `Rect` less. Allocations are unchanged in all 44 benchmark cases whose paths only go through objects that notify. These were measured at 4de66a2, whose measured subscribers already called `Listen<T>`.<br>↑ Copilot code review found no issues at 4de66a2.<br>↓ Code compiled against `Listen(object?)` from #40819 must be recompiled, and a hand-written call that passes a `null` literal no longer compiles.<br>↓ There are no device, UI, AOT or CI runs yet, because the PR pipelines are disabled. | <!-- /copilot-assessment --> <!-- Please let the below note in for people that find this PR --> > [!NOTE] > Are you waiting for the changes in this PR to be merged? > It would be very helpful if you could [test the resulting artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). This is .NET 12 performance work on the compiled bindings from #40819, which is on `main`. For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change <!-- Enter description of the fix in this section --> This is a follow-up to #40819. A compiled binding observes its path through a subscriber that the source generators emit for `SetBinding`, `BindingBase.Create` and XAML compiled bindings. The subscriber reports each object on the path with `TypedBindingListeners.Listen(object? part, string propertyName)`. The generators leave out structs that can't notify in any version, such as `DateTime`. They still report structs from other assemblies or from the app, such as `Rect`, `Point`, `Size` or `Thickness`, because some version of them could implement `INotifyPropertyChanged`. Passing such a struct as an `object` boxes it, only for the binding to find that the box can't notify. The binding runs the subscriber on every apply and whenever an observed property changes. So a binding to `Bounds.Width` allocated a boxed `Rect` (48 B) every time `Bounds` changed, the binding context changed, or the binding was applied. This replaces `TypedBindingListeners.Listen(object? part, string propertyName)` with `TypedBindingListeners.Listen<T>(T part, string propertyName)`: - For each struct type, the JIT evaluates `typeof(T).IsValueType && part is not INotifyPropertyChanged` once. A struct that can't notify occupies its position without being boxed. - If an earlier walk reported an object that notifies at that position, its handler is removed, as `Listen(object?)` did. Generated subscribers always report the same type at a given position, so this only matters for hand-written subscribers. - For reference types, the JIT removes the check, so paths through objects that notify run the same code as before. - A struct that implements `INotifyPropertyChanged` is boxed and observed, as before. The generators don't change. When subscribers are recompiled, their calls bind to `Listen<T>`. Subscribers for C# expressions in XAML store each object of the path in an `object?` local, so they call `Listen<object>`, which runs the same code as `Listen(object?)` did. `Listen(object?)` is unshipped .NET 12 API that #40819 added, so this removes it instead of keeping it next to `Listen<T>`. Code compiled against it must be recompiled. Two kinds of hand-written calls no longer compile: a `null` literal, from which C# can't infer `T`, and a ref struct that converts to an object, which can't be a type argument here. Generated subscribers pass neither.  **Left:** time per update for a binding that observes the property being replaced. Each bar is the best of 9 runs of 2,000,000 updates in each of 11 interleaved main/PR process pairs. Paths through objects that notify are unchanged. Paths through a struct are 9–13% faster, and their updates no longer allocate. **Right:** bytes allocated per operation by the new `TypedBindingStructPathBenchmarker`. It uses a source-generated `Bounds.Width` binding to a `double` property. The 24 B left per update is the boxed `double` that the target stores. <details> <summary>All numbers</summary> **Interleaved probe.** This is a console app that isn't part of this PR. It binds a `string` property through subscribers with the generated shape, compiled against each build, and replaces the observed property in a loop. Each row is 11 interleaved process pairs, best of 9 runs of 2,000,000 updates. | Path | main best (median) | PR best (median) | Change (best) | main B per update | PR B per update | | --- | ---: | ---: | ---: | ---: | ---: | | `Name` | 22.17 ns (22.48) | 22.01 ns (22.37) | −0.7% | 0 | 0 | | `Child.Name` | 25.69 ns (26.16) | 25.53 ns (26.29) | −0.6% | 0 | 0 | | `Child.Child.Name` | 27.40 ns (28.10) | 27.24 ns (28.10) | −0.6% | 0 | 0 | | `Point.Name`, through a struct | 28.48 ns (29.86) | 24.67 ns (25.71) | −13.4% | 32 | 0 | | `Holder.Point.Name`, through a struct | 31.20 ns (33.70) | 28.31 ns (29.36) | −9.3% | 32 | 0 | | `Bounds.Width.ToString()`, through `Rect` | 51.80 ns (52.84) | 46.29 ns (49.18) | −10.6% | 80 | 32 | **BenchmarkDotNet, `TypedBindingStructPathBenchmarker`.** Paired runs ordered main, PR, PR, main. "main" includes the new benchmark. Values are per iteration, and each operation runs 100 iterations. | Benchmark | main min (median) | PR min (median) | Change (min) | main B | PR B | | --- | ---: | ---: | ---: | ---: | ---: | | `StructUpdate` | 40.3 ns (43.3) | 35.4 ns (37.2) | −12.1% | 72 | 24 | | `ContextSwap` | 108.4 ns (123.1) | 103.1 ns (143.8) | −4.9% | 112 | 64 | | `CreateApplyAndRemove` | 383.9 ns (467.6) | 342.0 ns (419.0) | −10.9% | 880 | 832 | The same runs included the 44 cases of `TypedBindingDepthBenchmarker` and `TypedBindingIntermediateBenchmarker`, both generated and legacy bindings, as a control. Their allocations are identical on both sides. The host was heavily loaded during the runs, with a load average of about 40–50. BenchmarkDotNet times moved by up to ±20% even in the legacy cases, whose code this PR doesn't change. So these times, including the `ContextSwap` median, are only indicative. The interleaved probe above is the timing evidence. </details> #### Changes - `TypedBindingListeners.cs` replaces `Listen(object?)` with `TypedBindingListeners.Listen<T>`, and adds `TypedBindingSubscriptions.ListenToNothing` and `Listener.IsDetached`. - `PublicAPI.Unshipped.txt` replaces `Listen(object?)` with `Listen<T>` for all six target frameworks. - A new test in `TypedBindingCompatibilityTests`, `ValueThatCannotNotifyRemovesHandlerAtItsPosition`, checks that a struct that can't notify, reported where an object that notifies was, removes that object's handler. - New benchmark `TypedBindingStructPathBenchmarker`: updates through `Rect`, binding context changes, and creating, applying and removing such a binding. It's the first commit, so it can be run on main. #### Validation These were run on macOS arm64 with the pinned SDK 12.0.100-alpha.1.26523.103. Each test project was built first with `dotnet build <project> -c Debug -p:MauiPlatforms= -p:IncludePreviousTfms=false -p:PublicApiType=Validate`. Xaml.UnitTests also needs the build tasks, from `dotnet build Microsoft.Maui.BuildTasks.slnf -p:MauiPlatforms= -p:IncludePreviousTfms=false`. The tests ran again at 2481e06, after `Listen(object?)` was removed. | Command | Result | | --- | --- | | `dotnet test --project src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj -c Debug --no-build` | 7,685 passed, 30 skipped, 31 failed. The new test passes. The same 31 async leak tests fail on main without this change. They have failed since #40824, whose PR build [1704502](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1704502) failed them on all four unit-test legs. | | `dotnet test --project src/Controls/tests/BindingSourceGen.UnitTests/Controls.BindingSourceGen.UnitTests.csproj -c Debug --no-build`, with #40844 applied | 157 passed. Without #40844, this project doesn't build on main (xUnit1051). | | `dotnet test --project src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj -c Debug --no-build` | 934 passed, 71 skipped | | `dotnet test --project src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj -c Debug --no-build` | 2,341 passed, 8 skipped | | `Core.Benchmarks.dll --filter '*TypedBindingStructPathBenchmarker*' '*TypedBindingDepthBenchmarker*' '*TypedBindingIntermediateBenchmarker*' --iterationCount 10 --iterationTime 120 --warmupCount 3 --launchCount 1`, in Release, paired as above | See "All numbers" above. These ran at 4de66a2, before `Listen(object?)` was removed. The measured subscribers called `Listen<T>` there too. | Until #40844 merges, the unit-test legs of this PR's CI will fail on `BindingSourceGen.UnitTests`. They'll also fail on the 31 leak tests from #40824 until those are fixed. ### Issues Fixed <!-- Please make sure that there is a bug logged for the issue being fixed. The bug should describe the problem and how to reproduce it. --> No issue is filed. This is a follow-up to #40819. ### Let AI finish this PR - [ ] **Let the MAUI agent address review feedback and fix remaining issues on this PR.** Maintainers still decide whether it is merged. For PRs from forks, keep "Allow edits by maintainers" on so the agent can push to your branch; otherwise it opens a follow-up PR that keeps your commits. <!-- Verify the target branch follows the release workflow in docs/ReleaseBranchWorkflow.md. Infrastructure and documentation changes should target the branch where they apply. --> --------- Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
Agent assessment
Self-reported assessment, not an independent review.
Assessed revision:
4c07c58ee4f39fb46833e04176934d2c179d0548↑ The 106 compatibility tests run every scenario with both constructors. Of their 105 test cases that also run on main, 61 pass on main as well and 44 fail there and pass with this PR.
↑ Ten review rounds by three models ended with no objections.
↑ Paired BenchmarkDotNet runs against the merge base.
↓ Core binding infrastructure with a large blast radius. No device, UI or integration tests, and no CI run yet.
↓ Leaf updates through the legacy constructor, which code compiled before this PR (including XamlC output) calls, are 3–11% slower (about 2 ns per update).
Note
Are you waiting for the changes in this PR to be merged?
It would be very helpful if you could test the resulting artifacts from this PR and let us know in a comment if this change resolves your issue. Thank you!
Target Branch
mainnet11, for reviewFor .NET 11 fixes, only a maintainer retargets the approved PR to the active
inflight lane and merges it after CI validates that final base. Do not merge
individual fixes directly into
net11; agents must not retarget or merge.Description of Change
Compiled bindings (
TypedBinding<TSource, TProperty>) come from BindingSourceGen (SetBindingandBindingBase.Createlambdas), the XAML source generator and the deprecated XamlC. All three call the constructor that takes an array of handlers. Today these bindings observe every object on their path through onePropertyChangedProxyand oneWeakPropertyChangedProxyper path part. When an observed object changes, those proxies subscribe again, allocating new weak references and delegates. Each part also has its own finalizer, and nothing handles user code that changes the path while the binding observes it.This PR replaces the proxies with one subscription store per binding. It adds a constructor that generated code uses to report the observed objects without a delegate per part, and switches both source generators to that constructor. The handler-array constructor keeps working, on the same engine, for code compiled before this change.
Runtime (
TypedBinding.cs, newTypedBindingListeners.cs)TypedBindingSubscriptions, created on its first apply. A position of the path keeps its listener and event handler while the same object and property are reported there. So leaf changes, context swaps and intermediate replacements don't allocate.TypedBinding(getter, setter, int listenerCount, TypedBindingSubscriber<TSource> subscriber). The subscriber reads the path and callsTypedBindingListeners.Listen(part, propertyName)for each observed property, in order, and returns at the first null object. When a binding observes only its source, notifications from the source don't run the subscriber again.SetBinding,RemoveBinding, theBindingContextsetter, or the property setter that raised the change. The rest of the path stays observed, and the next walk retries the failed subscription.Generators
stringandDateTime. Value types declared in source are observed, because IL weavers can make them notify.{= ...}) emit a subscriber that evaluates each member chain independently. So a null object,Nullable<T>.Valuewithout a value, or a member that throws in one chain doesn't stop the binding from observing the others. A chain whose owner type can't be resolved is read through its original expression and is always observed.Behavior changes
TypedBindingCompatibilityTestshas 106 tests, which run every scenario with both constructors. I compiled a copy against main with only the handler-array constructor. It leaves out 6 tests that need the new constructor and 4 cycles that overflow the stack or hang on main. Of its 105 test cases, 61 pass on main as well. 44 fail on main and pass with this PR:INotifyPropertyChanged;The other 61 cases and the existing binding tests cover behavior that doesn't change.
API
New types in
Microsoft.Maui.Controls.Internals, hidden from IntelliSense like the rest of the typed binding API, for generated code:TypedBindingSubscriber<TSource>;TypedBindingListeners, aref structwithListen(object? part, string propertyName);TypedBindingconstructor above.PublicAPI.Unshipped.txtis updated for all six targets.Performance
BenchmarkDotNet,
src/Core/tests/Benchmarks: the newTypedBindingDepthBenchmarkerandTypedBindingIntermediateBenchmarker, plusTypedBindingScenarioBenchmarker. The benchmark sources are identical on both sides. Runs went main, this PR, this PR, main, and the charts show the minimum. Apple Silicon, .NET 12.BindingBase.Create); on main its output uses the handler-array constructor.Leaf updates through the handler-array constructor cost about 1–2.3 ns more per notification (+3–11%). That is the bookkeeping that keeps reentrant changes and accessor exceptions safe. Generated bindings, which the source generators now produce, are at parity. Libraries compiled before this PR, including XamlC output, keep the handler-array constructor until they're rebuilt.
A context swap allocates 40 B at every depth, which doesn't depend on the path. Replacing an intermediate object allocates nothing. Creating, applying and removing a binding allocates 15–42% less from depth 2 on. At depth 1, a generated binding allocates 80 B less and a legacy binding 16 B more.
The scenario benchmark uses handler-array bindings:
All numbers
Time per operation; main → this PR:
Bytes allocated per operation; main → this PR. Leaf property changes allocate nothing on either side.
Scenario benchmark, per operation:
Tests
All on macOS (Apple Silicon) with
-c Debug -f net12.0 -p:MauiPlatforms= -p:IncludePreviousTfms=false -p:PublicApiType=Validate:dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csprojdotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csprojdotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csprojdotnet test src/Controls/tests/BindingSourceGen.UnitTests/Controls.BindingSourceGen.UnitTests.csprojTypedBindingCompatibilityTests: binding scenarios, both constructors.MayNotifyPropertyChangedTestsand the updated BindingSourceGen snapshots.CSharpExpressionListenersTests: generated subscribers.CSharpExpressionListeners.sgen.xaml: C# expression bindings at run time.BindingsCompilerruns with every inflator, so XamlC output also runs on the new engine, through the handler-array constructor.Benchmarks: from
artifacts/bin/Core.Benchmarks/Release/net12.0of each worktree:Commits
Issues Fixed
This supersedes #32382, which targeted
net11.0, is out of date withmainand still has changes requested.The compatibility tests also cover the scenarios of #34428, #34496, #36444, #37095, #38056, #38667, #39470 and #40157, which main already fixes.
Let AI finish this PR