Repository navigation
Don't box structs in compiled binding subscriptions - #40849
Conversation
Bindings such as Bounds.Width observe the struct on their path, because a struct that another assembly or the app defines could implement INotifyPropertyChanged. The benchmark measures updates of the struct, binding context swaps, and creating, applying and removing such a source-generated binding. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
TypedBindingListeners.Listen took each part as an object, so a subscriber boxed every value type on its path on each walk, only for the binding to find that the value can't notify. Listen is now generic. The JIT decides for each value type whether it implements INotifyPropertyChanged, and removes the check for reference types. A value type that can't notify only occupies its position, and removes a handler that a subscriber attached at that position in an earlier walk. Generated subscribers compile unchanged, because C# infers the type argument. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
With only the generic Listen, C# infers a ref struct as the type argument, which isn't allowed, and can't infer one from a null literal, so such calls that compiled against Listen(object?) no longer did. Both overloads together keep them compiling: overload resolution drops the generic candidate for a ref struct, which converts to an object as before, and a null literal binds to the object overload. Typed arguments still bind to Listen<T>. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
🔵 Needs a closer look
The shared subscription change adds a public generic overload whose boxing savings depend on runtime optimization, but validation is desktop JIT-only, with no supported-device/AOT or independent CI evidence.
No open issues 🎉
What changed in this PR
This .NET 12 performance follow-up to #40819 reduces allocations in MAUI compiled bindings by avoiding boxing for non-notifying structs such as Rect, while retaining the existing object overload.
Changes:
- Adds
Listen<T>and cleanup for subscriptions previously occupying a non-notifying value’s path position. - Records the new overload across six public API baselines and updates XML documentation.
- Adds compatibility tests and benchmarks for struct updates, binding-context swaps, and binding creation/removal.
| File | Description |
|---|---|
src/Core/tests/Benchmarks/Benchmarks/TypedBindingStructPathBenchmarker.cs |
Adds allocation and timing benchmarks for bindings through Rect. |
src/Controls/tests/Core.UnitTests/TypedBindingCompatibilityTests.cs |
Tests handler cleanup and ref-struct conversion compatibility. |
src/Controls/src/Core/TypedBindingListeners.cs |
Adds the generic overload and non-notifying-position cleanup. |
src/Controls/src/Core/TypedBinding.cs |
Updates an XML documentation reference to the generic overload. |
src/Controls/src/Core/PublicAPI/netstandard/PublicAPI.Unshipped.txt |
Records the overload for .NET Standard. |
src/Controls/src/Core/PublicAPI/net/PublicAPI.Unshipped.txt |
Records the overload for .NET. |
src/Controls/src/Core/PublicAPI/net-windows/PublicAPI.Unshipped.txt |
Records the overload for Windows. |
src/Controls/src/Core/PublicAPI/net-maccatalyst/PublicAPI.Unshipped.txt |
Records the overload for Mac Catalyst. |
src/Controls/src/Core/PublicAPI/net-ios/PublicAPI.Unshipped.txt |
Records the overload for iOS. |
src/Controls/src/Core/PublicAPI/net-android/PublicAPI.Unshipped.txt |
Records the overload for Android. |
Review effort: Balanced
|
/review expert-review |
This comment has been minimized.
This comment has been minimized.
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>
This comment has been minimized.
This comment has been minimized.
| [MethodImpl(MethodImplOptions.AggressiveInlining)] | ||
| public void Listen(object? part, string propertyName) => | ||
| _subscriptions?.Listen(_walk, _position++, part, propertyName); | ||
| public void Listen<T>(T part, string propertyName) |
There was a problem hiding this comment.
MAUI Autopilot · round 1
❌ Not changed. Restoring Listen(object?, string) would reverse the deliberate removal of an unshipped overload in 2481e06. The null-literal source break is real, but generated subscribers do not use that call, and no shipped API signature is being removed. Roslyn also rejects a direct user-defined ref-struct conversion to object (CS0553). Whether to preserve compatibility for prerelease callers is a maintainer decision.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
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 API change relies on runtime specialization, but validation covers only desktop JIT, requiring human review of device/AOT behavior and the intentional recompilation requirement.
Review effort: Balanced
…d merge patch (#40871) <!-- copilot-assessment:v1 --> ### Agent assessment Self-reported assessment, not an independent review. Assessed revision: `01e5f4f46f9721c66177dd5b48ccd9eef6a39f22` | Dimension | Assessment | Rationale | |---|---|---| | Change confidence | 8.5/10 | ↑ Regenerated the reviewed patch from #40849's real bundle (run 46427489688): the 381-line deletion is excluded and nothing else changes.<br>↑ The changed publish_direct script ran against that data with the push pointed at a copy of the PR branch, for both an empty and a missing reviewed patch: it pushed the same merge commit.<br>↑ gh aw compile passes.<br>↓ Leaving the deletion out means threat detection no longer sees it; that is safe only because both sides apply the same rule (missing from the merge and from the base) and publish_direct still requires every changed path to be under src/.<br>↓ Not yet run live. | | Diagnosis confidence | 9.5/10 | ↑ The detection log shows malicious_patch: true with the reason "The patch deletes all 381 lines of src/Controls/src/Core/PublicAPI/netstandard/PublicAPI.Unshipped.txt without a replacement". | | Evidence fit | 9.5/10 | ↑ That deletion is the only change in #40849's reviewed patch, and main deleted that file. | <!-- /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! ### 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). Infrastructure change to the MAUI Autopilot workflow, which runs from `main`. ### Description of Change Follow-up to #40866. The patch that threat detection reviews for a conflict merge is the merge minus Git's own merge of the PR head and the base. Git's own merge keeps a `PublicAPI.Unshipped.txt` that the base deleted and the PR changed. So when setup deletes that file, which it does since #40866, the deletion showed up in the reviewed patch as the agent deleting a 381-line API baseline. Detection flagged #40849's merge as malicious, and `publish_direct` correctly refused to push it ([run 46427489688](https://github.com/dotnet/maui/actions/runs/46427489688)). The bundling step and `publish_direct` now both leave out a `PublicAPI.Unshipped.txt` that is missing from both the merge and the base. That is a deletion the base made, not something the agent authored. `publish_direct` still requires every changed path to stay under `src/` with no protected files. It treats a missing reviewed patch as empty, because a merge whose only change is such a deletion produces an empty patch. Validation: - `gh aw compile maui-expert-autopilot` - regenerated #40849's patch from its real bundle - ran the changed publish script against that data, pushing to a copy of the PR branch, as described in the assessment. ### Issues Fixed Fixes # ### 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. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
Expert Review — No more findings
Reviewed commit c8395b6.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
| [MethodImpl(MethodImplOptions.NoInlining)] | ||
| void DetachSlow(int walk, int position, Listener listener) | ||
| { | ||
| if (walk == _walk && TryDetach(listener, position) is { } failure) |
There was a problem hiding this comment.
[moderate] Regression Prevention and Test Coverage - The new walk-ownership guard has no discriminating superseded-walk test through ListenToNothing. A handwritten subscriber can read a Frame through a getter that raises a root notification: the nested walk observes a notifying child at that position, then the outer walk resumes with Listen<Frame>. That stale call must leave the newer child's handler intact. Without this guard it detaches the handler, so subsequent child changes stop updating the target. The new theory exercises only current walks; WalkSupersededByNestedWalkKeepsItsSubscriptions uses object-returning PathPart delegates and never reaches DetachSlow. Add a typed-Frame reentrancy case asserting that the child remains subscribed and still updates the target.
Selected Tests
🧪 Test selection — click to expand
🧪 UI tests —
|
| Platform | Categories |
|---|---|
| Android | CollectionView6 |
| iOS | CollectionView6 |
| MacCatalyst | CollectionView6 |
| Windows | CollectionView6 |
🧪 Device tests — Controls.Memory, Controls.Xaml on Android, iOS, MacCatalyst, Windows
❌ Could not queue maui-pr-devicetests: Azure Pipelines did not start maui-pr-devicetests for the dispatch branch run-devicetests/pr40849-46470189132 within 10 minutes. Comment /review run-tests again, or use /azp run maui-pr-devicetests for the full suite.
GPT-6.2 Sol: Run Controls XAML and Memory device tests on all four platforms for the shared compiled-binding subscription change.
MAI Code 2: Compiled-binding runtime allocation optimization is covered by unit and benchmark tests; no device suites are needed.
🧪 Running — 2 categories on Android, iOS, MacCatalyst, Windows
| Platform | Categories |
|---|---|
| Android | Controls.Memory, Controls.Xaml |
| iOS | Controls.Memory, Controls.Xaml |
| MacCatalyst | Controls.Memory, Controls.Xaml |
| Windows | Controls.Memory, Controls.Xaml |
⏭️ Skipped — what neither suite runs
UI tests — 76 categories, 0 platforms
Categories not run: Accessibility, ActionSheet, ActivityIndicator, Animation, AppLinks, Border, BoxView, Brush, Button, CarouselView, CollectionView1, CollectionView2, CollectionView3, CollectionView4, CollectionView5, CollectionView7, Cells, CheckBox, ContextActions, CustomRenderers, DatePicker, Dispatcher, DisplayAlert, DisplayPrompt, DragAndDrop, Entry, Editor, Effects, Essentials, FlyoutPage, Focus, Fonts, Frame, Gestures, GraphicsView, Image, ImageButton, IndicatorView, InputTransparent, IsEnabled, IsVisible, Label, Layout, Lifecycle, ManualReview, Maps, Navigation, Page, Performance, Picker, ProgressBar, RadioButton, RefreshView, SafeAreaEdges, Shadow, ScrollView, SearchBar, Shape, Slider, SoftInput, Stepper, Switch, SwipeView, Shell1, Shell2, TabbedPage, TableView, TimePicker, TitleView, ToolbarItem, Triggers, ViewBaseTests, VisualStateManager, Window, WebView, Material3
Each skipped platform and category is listed as a maui-pr-uitests (skipped) … status on this commit. Use /azp run maui-pr-uitests for the full suite.
Device tests — 103 categories, 0 platforms
Categories not run: 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.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, 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 | CollectionView6 |
— |
| iOS | CollectionView6 |
— |
| MacCatalyst | CollectionView6 |
— |
| Windows | CollectionView6 |
— |
GPT-6.2 Sol — Run CollectionView shard 6 on all four platforms as an end-to-end check of the shared compiled-binding listener change.
- TypedBindingListeners.cs changes compiled subscription walks across platforms.
- CollectionView6 covers typed XAML bindings in Issue27200 and Issue28827 where enabled.
- No control handlers or UI test infrastructure changed; skip other categories.
MAI Code 2 — Compiled-binding allocation optimization with focused unit and benchmark coverage; no UI or device test lanes needed.
TypedBindingListeners.Listen<T>only avoids boxing non-notifying value types; existing notification and detachment semantics are covered by the changed Controls.Core unit test.- Public API baseline updates only reflect the generic listener signature; they do not change a platform-specific UI path.
- The added benchmark targets allocation counts, not visual or device behavior.
- No changed UI/device tests, control-specific handlers, layouts, or shared test infrastructure require pipeline coverage.
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 |
— |
| iOS | Controls.Xaml, Controls.Memory |
— |
| MacCatalyst | Controls.Xaml, Controls.Memory |
— |
| Windows | Controls.Xaml, Controls.Memory |
— |
GPT-6.2 Sol — Run Controls XAML and Memory device tests on all four platforms for the shared compiled-binding subscription change.
- Listen(T) changes the generated binding call contract; Controls.Xaml provides a device XAML smoke check.
- ListenToNothing changes listener detachment; Controls.Memory checks object lifetime.
- No Core handler or other device project changed.
MAI Code 2 — Compiled-binding runtime allocation optimization is covered by unit and benchmark tests; no device suites are needed.
- The change is in shared compiled-binding subscription internals and does not alter any device control handler or platform implementation.
- Focused unit coverage verifies subscription removal when a path position becomes a non-notifying struct.
- The new benchmark validates the allocation objective; device test projects are not changed or implicated.
Generated by /review run-tests. A targeted run is a fast signal, not full-suite certification.

Agent assessment
Self-reported assessment, not an independent review.
Assessed revision:
2481e06d64f2246b4362b5b7b768ac7c531a0e64↑ The subscribers of C# expressions in XAML pass an
object?local. They compile againstListen<object>, and their tests pass.↑ Each walk through a struct allocates exactly one boxed
Rectless. 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 calledListen<T>.↑ Copilot code review found no issues at 4de66a2.
↓ Code compiled against
Listen(object?)from #40819 must be recompiled, and a hand-written call that passes anullliteral no longer compiles.↓ There are no device, UI, AOT or CI runs yet, because the PR pipelines are disabled.
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 reviewThis 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
This is a follow-up to #40819.
A compiled binding observes its path through a subscriber that the source generators emit for
SetBinding,BindingBase.Createand XAML compiled bindings. The subscriber reports each object on the path withTypedBindingListeners.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 asRect,Point,SizeorThickness, because some version of them could implementINotifyPropertyChanged. Passing such a struct as anobjectboxes 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.Widthallocated a boxedRect(48 B) every timeBoundschanged, the binding context changed, or the binding was applied.This replaces
TypedBindingListeners.Listen(object? part, string propertyName)withTypedBindingListeners.Listen<T>(T part, string propertyName):typeof(T).IsValueType && part is not INotifyPropertyChangedonce. A struct that can't notify occupies its position without being boxed.Listen(object?)did. Generated subscribers always report the same type at a given position, so this only matters for hand-written subscribers.INotifyPropertyChangedis 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 anobject?local, so they callListen<object>, which runs the same code asListen(object?)did.Listen(object?)is unshipped .NET 12 API that #40819 added, so this removes it instead of keeping it next toListen<T>. Code compiled against it must be recompiled. Two kinds of hand-written calls no longer compile: anullliteral, from which C# can't inferT, 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-generatedBounds.Widthbinding to adoubleproperty. The 24 B left per update is the boxeddoublethat the target stores.All numbers
Interleaved probe. This is a console app that isn't part of this PR. It binds a
stringproperty 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.NameChild.NameChild.Child.NamePoint.Name, through a structHolder.Point.Name, through a structBounds.Width.ToString(), throughRectBenchmarkDotNet,
TypedBindingStructPathBenchmarker. Paired runs ordered main, PR, PR, main. "main" includes the new benchmark. Values are per iteration, and each operation runs 100 iterations.StructUpdateContextSwapCreateApplyAndRemoveThe same runs included the 44 cases of
TypedBindingDepthBenchmarkerandTypedBindingIntermediateBenchmarker, 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
ContextSwapmedian, are only indicative. The interleaved probe above is the timing evidence.Changes
TypedBindingListeners.csreplacesListen(object?)withTypedBindingListeners.Listen<T>, and addsTypedBindingSubscriptions.ListenToNothingandListener.IsDetached.PublicAPI.Unshipped.txtreplacesListen(object?)withListen<T>for all six target frameworks.TypedBindingCompatibilityTests,ValueThatCannotNotifyRemovesHandlerAtItsPosition, checks that a struct that can't notify, reported where an object that notifies was, removes that object's handler.TypedBindingStructPathBenchmarker: updates throughRect, 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, fromdotnet build Microsoft.Maui.BuildTasks.slnf -p:MauiPlatforms= -p:IncludePreviousTfms=false. The tests ran again at 2481e06, afterListen(object?)was removed.dotnet test --project src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj -c Debug --no-builddotnet test --project src/Controls/tests/BindingSourceGen.UnitTests/Controls.BindingSourceGen.UnitTests.csproj -c Debug --no-build, with #40844 applieddotnet test --project src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj -c Debug --no-builddotnet test --project src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj -c Debug --no-buildCore.Benchmarks.dll --filter '*TypedBindingStructPathBenchmarker*' '*TypedBindingDepthBenchmarker*' '*TypedBindingIntermediateBenchmarker*' --iterationCount 10 --iterationTime 120 --warmupCount 3 --launchCount 1, in Release, paired as aboveListen(object?)was removed. The measured subscribers calledListen<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
No issue is filed. This is a follow-up to #40819.
Let AI finish this PR