Skip to content

[Testing] Fix the BindingSourceGen.UnitTests build on main (xUnit1051) - #40844

Merged
kubaflo merged 1 commit into
mainfrom
simonrozsival-typed-binding-v2
Nov 30, 2026
Merged

kubaflo merged 1 commit into
mainfrom
simonrozsival-typed-binding-v2

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Nov 30, 2026 •

Copy link
Copy Markdown
Member

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.
↑ Test-only change. The assertions are unchanged.
↓ 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.
↑ #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.

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

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

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

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) 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 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

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.

#40819 added these tests on a branch from before #40661 moved
BindingSourceGen.UnitTests to xUnit v3. The v3 analyzers report the two
calls that take a CancellationToken as xUnit1051 errors, so the project
no longer builds and the unit-test legs of maui-pr fail on main.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 30, 2026 08:31
@github-actions

This comment has been minimized.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues are recorded for the test-only cancellation-token update.

No open issues 🎉

What changed in this PR

Fixes the BindingSourceGen unit-test build errors introduced when tests from #40819 met the xUnit v3 analyzer requirements added by #40661.

Changes:

  • Passes TestContext.Current.CancellationToken to CSharpSyntaxTree.ParseText and Compilation.GetDiagnostics to resolve xUnit1051 errors.
  • Leaves test assertions and production code unchanged.
File Description
src/​Controls/​tests/​BindingSourceGen.UnitTests/​MayNotifyPropertyChangedTests.cs Adds test cancellation tokens to both Roslyn calls flagged by xUnit1051.

Review effort: Balanced

@kubaflo

This comment has been minimized.

@kubaflo

This comment has been minimized.

@github-actions

Copy link
Copy Markdown
Contributor

Selected Tests

@kubaflo — AI-selected UI tests and device tests (GPT-6.2 Sol + MAI Code 2) for commit 21f7caeb.

Result NOTHING TO RUN Platforms none Tests 0 UI, 0 device Commit 21f7caeb


🧪 Test selection — click to expand
Suite Result Selected Build
UI tests ➖ nothing to run none —
Device tests ➖ nothing to run none —
🧪 UI tests — nothing to run

ℹ️ The AI found no changes relevant to UI tests, so no maui-pr-uitests run was queued.

GPT-6.2 Sol: No UI tests are needed for this BindingSourceGen unit-test-only fix.
MAI Code 2: Unit-test-only cancellation-token fix; no UI tests are affected.

🧪 Running — nothing

No UI tests run for this PR.

🧪 Device tests — nothing to run

ℹ️ The AI found no changes relevant to device tests, so no maui-pr-devicetests run was queued.

GPT-6.2 Sol: No device tests are needed for this BindingSourceGen unit-test-only fix.
MAI Code 2: Unit-test-only cancellation-token fix; no device tests are affected.

🧪 Running — nothing

No device tests run for this PR.

⏭️ Skipped — what neither suite runs

UI tests — 77 categories, 4 platforms

Platforms not run: Android, iOS, MacCatalyst, Windows

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 — 105 categories, 4 platforms

Platforms not run: Android, iOS, MacCatalyst, Windows

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 — —
iOS — —
MacCatalyst — —
Windows — —

GPT-6.2 Sol — No UI tests are needed for this BindingSourceGen unit-test-only fix.

  • MayNotifyPropertyChangedTests.cs passes xUnit’s cancellation token to two Roslyn calls.
  • No product code or UI test app changes; omit all UI platforms and categories.

MAI Code 2 — Unit-test-only cancellation-token fix; no UI tests are affected.

  • The only changed file is under BindingSourceGen.UnitTests and updates analyzer-compliant test cancellation usage.
  • No product UI, handlers, controls, UI test host, or shared UI infrastructure changes, so no UI pipeline coverage is needed.

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 — —
iOS — —
MacCatalyst — —
Windows — —

GPT-6.2 Sol — No device tests are needed for this BindingSourceGen unit-test-only fix.

  • The xUnit1051 fix is confined to MayNotifyPropertyChangedTests.cs.
  • No product code or device test changes; omit all device platforms and categories.

MAI Code 2 — Unit-test-only cancellation-token fix; no device tests are affected.

  • The diff changes only BindingSourceGen.UnitTests and does not alter runtime product code.
  • Assertions and tested behavior remain unchanged, and no device-test code or shared test infrastructure is touched.

Generated by /review run-tests. A targeted run is a fast signal, not full-suite certification.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Expert Review — No findings

Reviewed commit 21f7cae.

@kubaflo
kubaflo merged commit cdeb857 into main Nov 30, 2026
25 of 26 checks passed
@kubaflo
kubaflo deleted the simonrozsival-typed-binding-v2 branch November 30, 2026 11:47
kubaflo added a commit that referenced this pull request Nov 30, 2026
#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 page assembly is 21% smaller as IL and 13% smaller with
ReadyToRun. The first page creation is 681 µs faster with JIT and 56 µs
faster with
ReadyToRun.](https://github.com/user-attachments/assets/07bd5400-fe08-4c1c-835b-151aacc27009)

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>
kubaflo added a commit that referenced this pull request Nov 30, 2026
…#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 JIT compiles 2 instead of 9 methods per value type when a binding
is first applied, and 1 instead of 3 when it updates. The first apply of
10 value-type bindings is 4.1 ms (60%) faster with JIT and 3.3 ms (64%)
faster with
ReadyToRun.](https://github.com/user-attachments/assets/0d51199f-fe86-4ad9-9bc8-c8220c35a635)

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>
kubaflo added a commit that referenced this pull request Nov 30, 2026
<!-- 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.

![Time per update through objects that notify is unchanged; through a
struct it's 9–13% lower. Allocations through Rect drop by 48 B per
update, binding context change, and
create-apply-remove.](https://github.com/user-attachments/assets/e6236b6b-a70c-4b2d-a023-d845676733a7)

**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>

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — 21f7caeb Deployed Nov 30, 2026 by simonrozsival via conclusion #3496
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants