Repository navigation
[net12][Proposal] Batch handler updates per dispatcher turn - #37337
StephaneDelcroix wants to merge 7 commits into
Conversation
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.
MauiBot
left a comment
There was a problem hiding this comment.
Expert Review — 7 findings
See inline comments for details.
This comment has been minimized.
This comment has been minimized.
MauiBot
left a comment
There was a problem hiding this comment.
Expert Review — 1 findings
See inline comments for details.
This comment has been minimized.
This comment has been minimized.
| var property = node.Property!; | ||
| _pendingPropertyUpdateHead = node.Next; | ||
| indices.Remove(property); | ||
| InvokeCurrentPropertyMapper(property); |
There was a problem hiding this comment.
[major] Logic and Correctness Verification - Flushing an earlier property can overwrite the managed values of properties still queued. With explicit batching enabled, use a connected Windows Entry displaying "a", then call BatchBegin(); Text = "abcdef"; CursorPosition = 2; SelectionLength = 2; BatchCommit();. Text maps first; Controls' Windows TextBoxExtensions.UpdateText sets native text and calls Select(cursorPosition, 0). EntryHandler.OnPlatformSelectionChanged synchronously writes the resulting caret and zero selection length back into the virtual view, overwriting the requested selection before its queued mappers read it. The final state loses the requested selection, unlike the unbatched sequence where the selection assignments follow the native Text callbacks. Preserve pending selection values across native feedback and cover this with a real Entry regression test; the added counter-only mappers cannot detect it.
There was a problem hiding this comment.
MAUI Autopilot · round 1
❌ Not changed. The Windows Entry fix and regression tests could not be published: the append-only push was rejected because existing PR history includes a documentation path outside the allowed paths. The Windows tests still need a Windows runner.
|
|
||
| bool IPropertyUpdateBatchingElement.IsAutomaticPropertyUpdateBatchingEnabled => false; | ||
|
|
||
| bool IPropertyUpdateBatchingElement.IsPropertyUpdateBatchingExplicitlyScoped => true; |
There was a problem hiding this comment.
[moderate] Regression Prevention and Test Coverage - These fixtures replace VisualElement's switch-backed batching contract, and the explicit-only fixture reports an open scope before BatchBegin. Making the production enabled property always false would therefore leave these batching assertions unchanged; removing the explicit-only BeginPropertyUpdateBatch notification is also masked by the already-open fixture scope. The existing Controls TestBatching checks only the counter/event without a handler, and the benchmark overrides the interface too. Add isolated switch-initialization coverage with an unmodified control and attached handler, checking primary-switch-only batching, updates outside the scope, nested commits, and the disabled case.
There was a problem hiding this comment.
MAUI Autopilot · round 1
❌ Not changed. The isolated startup-switch test passed locally without changing production switch caching, but the append-only push was rejected because existing PR history includes a documentation path outside the allowed paths.
| handler = new HandlerStub(mapper); | ||
| var view = new AlwaysBatchingButton(); | ||
|
|
||
| handler.SetVirtualView(view); |
There was a problem hiding this comment.
[moderate] Regression Prevention and Test Coverage - This test ends explicit batching during setup: SetVirtualView executes the initial First mapper, which calls FlushPendingPropertyUpdates and clears _isExplicitPropertyUpdateBatching. After mapped.Clear(), both UpdateValue calls consequently map immediately and the final flush is empty. The First/Second assertion never exercises a reentrant commit while Second remains queued, so it cannot detect dropped work in the active-drain scenario named by the test. Suppress the commit during initialization, begin a fresh batch afterward, and assert no mapping occurred before triggering the flush. The reflection-based companion covers the different outside-drain scenario.
There was a problem hiding this comment.
MAUI Autopilot · round 1
❌ Not changed. The corrected reentrant-commit test passed locally, but the append-only push was rejected because existing PR history includes a documentation path outside the allowed paths.
|
/review run-tests |
Selected UI Tests
🧪 Test selection — click to expand❌ maui-pr-uitests #1691867 failed. See the failing checks below or the run for details. GPT-6.1 Sol: Shared VisualElement and base-handler batching, native-view access and teardown changes require all UI categories on Android, iOS, MacCatalyst and Windows. 🧪 Ran — 77 categories on Android, iOS, MacCatalyst, WindowsThe complete 📊 Results — failed: 126 passed, 7 failed of 133 jobs
Failed tests (15)
🤖 Why these tests — AI rationale (GPT-6.1 Sol + Claude Opus 5.5)Each model chose independently; every test that runs was selected by at least one of them.
GPT-6.1 Sol — Shared VisualElement and base-handler batching, native-view access and teardown changes require all UI categories on Android, iOS, MacCatalyst and Windows.
Claude Opus 5.5 — Adds handler property-update batching to the base ElementHandler, ViewHandler and VisualElement; runs the full UI test suite on all platforms.
Generated by /review run-tests. A targeted run is a fast signal, not full-suite certification. |
…p the zero-spacing item decoration (#40901) <!-- copilot-assessment:v1 --> ### Agent assessment Self-reported assessment, not an independent review. Assessed revision: `949b79d0638d22483c94bae3f804090cd6646aca` | Dimension | Assessment | Rationale | |---|---|---| | Change confidence | 8.5/10 | ↑ Android CollectionViewTests and CarouselViewTests pass on this revision: 314 passed, 1 skipped by its attribute, 0 failed (Android 15 emulator).<br>↑ New device tests cover the selection of recycled rows (Single and Multiple, default color and Selected visual state) and spacing changes between zero and non-zero (linear in both orientations, grid).<br>↑ A trace shows the removed work gone (selection 2.2% and GetItemOffsets 0.8% of UI-thread samples, both to 0), with allocations unchanged.<br>↓ No speed-up is measurable on the emulator, and the A/B included a third commit that is no longer part of this PR.<br>↓ Android UI tests, CI and physical devices not run yet.<br>↓ OnSelectedChanged is no longer called on bind or recycle when the selection doesn't change, which a custom SelectableViewHolder subclass could notice. | <!-- /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, so it targets `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 --> When a CollectionView scrolls on Android, every row that comes into view is bound and every row that leaves it is recycled. Two parts of that work called into Java (or were called from Java) for every row without changing anything. This PR removes those calls. What the user sees doesn't change. #### 1. Don't reapply an unchanged selection Files: `SelectableViewHolder.cs`, `SelectableItemsViewAdapter.cs`, `TemplatedItemViewHolder.cs` `SelectableItemsViewAdapter` sets `SelectableViewHolder.IsSelected` for every item it binds and every holder it recycles. The setter always applied the value: - It set the item view's `Foreground`, `Background`, `Activated` and `Selected`. Each of these is a JNI call after a JNI read of `ViewHolder.ItemView`. - It scanned the content's visual state groups and set `IsItemSelected`. With `SelectionMode.None` the value is always `false`. So for every row it scrolled, a list made 8 JNI field reads (with peer lookups) and 8 JNI property sets that changed nothing. Binding and recycling now call a new internal `UpdateIsSelected`, which skips a value that the item view and its content already show. - A holder applies its selection the first time it is bound. - It applies it again after `TemplatedItemViewHolder` replaces its content: new content isn't selected yet, and its visual states decide whether the default selection color applies. - Selection changes still set `IsSelected` as before: `MarkPlatformSelection`, `ClearPlatformSelection` and clicks, including the unconditional re-sync from #31591. The public `IsSelected` setter is unchanged. #### 2. No item decoration without item spacing File: `MauiRecyclerView.cs` (`UpdateItemSpacing`) `UpdateItemSpacing` always added a `SpacingItemDecoration`, even when the spacing is zero, which is the default. Its `GetItemOffsets` then offsets nothing. RecyclerView still calls it from Java for every row it binds, and each call looks up the peers of its four arguments and calls back into Java for `base.GetItemOffsets`. Now no decoration is added without spacing; the RecyclerView's padding is still reset as before. - Changing the spacing to or from zero removes or adds the decoration. - A decoration from an overridden `CreateSpacingDecoration` is always added, including a subclass of `SpacingItemDecoration`. - CarouselView uses its own decoration and is not affected. #### Why it's safe - **Selection:** the check only skips writing values that are already applied. It is reset whenever a holder's content is replaced. Holders that RecyclerView keeps in its view cache stay in `_currentViewHolders`, so selection changes still reach them. - **Decoration:** - A decoration whose offsets are all zero has the same effect as no decoration. - RecyclerView's `willNotDraw` stays `false`, because CollectionView doesn't set `OverScrollMode.Never`. - `InvalidateItemDecorations()` becomes a no-op when there's nothing to invalidate. #### Behavior changes - `SelectableViewHolder.OnSelectedChanged()` (protected virtual) is no longer called when binding or recycling a holder doesn't change its selection. A custom subclass that used it as a per-bind hook would see fewer calls. - Selection visuals are reapplied only when the selection changes or the holder's content is replaced, not at every bind. - With zero spacing, `MauiRecyclerView.ItemDecorationCount` is 0 instead of 1. #### Results The numbers come from the CollectionView scroll benchmark ([source](https://github.com/dotnet/maui/tree/simonrozsival-collectionview-scroll-benchmark/src/Controls/tests/CollectionViewScrollBenchmark), pushed for reference; it isn't part of this or any PR). - What it scrolls: a CollectionView of 1,000 items. Each row is a Grid with a BoxView, 7 Labels, a ProgressBar and a CheckBox, with 13 compiled bindings and the default `SelectionMode.None` and zero spacing. - How it scrolls: 100 dp per frame for 240 frames per pass, which binds about 267 rows per pass. - Method: base and candidate launches are interleaved. Each launch is reduced to the median of its 5 warm passes, launches are paired by round, and the result is the median paired difference with a 95% sign-test interval. Setup: - Base is main bd40bc6. - The candidate is this PR plus a third commit that coalesced layout requests during a rebind. I dropped that commit from this PR because it added machinery to Core without a measurable gain. **So the A/B measured all three changes together.** - Device: an Android 15 emulator (Pixel 6 profile, android-35 google_apis arm64-v8a, 4 cores, 4 GB) on a shared, heavily loaded Mac (load average 15–64). - Runtime: CoreCLR .NET 12.0.0-alpha.1.26523.103, Release builds. **Allocations are unchanged:** 20,009 B/row in both (difference 0 [0 .. 0]), with 2 gen0 GCs per pass. **Timing: no significant difference.** The emulator resolves only differences of about 20% or more. | Run (rounds) | Rebind, UI-thread CPU per row | UI-thread CPU per row | Wall time per pass | |---|---|---|---| | 1, vs main build (12) | +5.5% [−24.1 .. 56.1 µs] | +7.5% [−70 .. 390 µs] | +20.6% [34 .. 2,584 ms] * | | 2, vs main build, reversed order (12) | +6.6% [−17.0 .. 28.8 µs] | +8.8% [−116 .. 170 µs] | +0.7% [−81 .. 211 ms] | | 3, vs main built in the same checkout (10) | +1.5% [−15.9 .. 10.6 µs] | −2.6% [−88.6 .. 60.8 µs] | 0.0% [−86 .. 3 ms] | | 3, control: main vs main, two builds (10) | +2.8% [−3.1 .. 15.6 µs] | +2.6% [−22.0 .. 139.8 µs] | +0.1% [−1 .. 85 ms] | In run 1, the candidate's slow passes also took more UI-thread CPU for the same rows. That points to the emulator losing CPU to the host rather than to the change, and runs 2 and 3 didn't reproduce it. Run 3's control shows the same small lean between two builds of the same commit. **Trace evidence for the two changes in this PR.** I traced the candidate with the EventPipe sample profiler over 8 warm passes (2,136 rows) and compared it with a trace of main. The traces were taken at different times, so compare shares, not totals. | UI-thread samples | main | candidate | |---|---|---| | Total | 1,434 | 1,095 | | `SelectableViewHolder` frames (`SetSelectionStates`, the `IsSelected` setter) | 32 (2.2%) | 0 | | … of which JNI reads of `ViewHolder.ItemView` (`GetObjectField`) | 18 (1.3%) | 0 | | `SpacingItemDecoration.GetItemOffsets`, called from Java | 11 (0.8%) | 0 | Per bound row, the two changes remove: - 8 JNI property sets and 8 JNI field reads, when the selection doesn't change; - 1 call from Java into .NET with 4 peer lookups, plus 1 call back into Java, when there's no spacing. #### Tests New device tests in `CollectionViewTests.Android.cs`: - `RecycledItemsShowTheirOwnSelection` (4 cases). Single and Multiple selection, each with the default selection color and with a template that colors selection through a `Selected` visual state. It scrolls so that rows are recycled, changes the selection while the selected item is out of view, and turns selection off. Every row in view must show the selection of the item it is bound to: `IsSelected`, `Activated`, `Selected`, `IsItemSelected`, the default color and the visual state. - `LinearItemSpacingChangesBetweenZeroAndNonZero` (vertical, horizontal). It checks the decoration count and item bounds as the spacing goes 0 → 40 px → 0 → 40 px. - `GridItemOffsetsExcludeCrossAxisOuterSpacing` (existing, 4 cases) now also checks the decoration count and the non-zero → zero transition. Run on this revision, on an Android 15 (API 35) emulator, Release: ``` pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform android -DeviceUdid emulator-5620 -DotnetPath $PWD/.dotnet/dotnet -IncludeClasses 'Microsoft.Maui.DeviceTests.CollectionViewTests,Microsoft.Maui.DeviceTests.CarouselViewTests' -Timeout 01:30:00 ``` Result: **Passed.** 315 total, 314 passed, 1 skipped (`CellSizeAccountsForMargin`, skipped by its attribute), 0 failed. `dotnet format whitespace --folder --verify-no-changes` on the changed files reports nothing new. `SelectableItemsViewAdapter.cs` has 27 whitespace issues that are also on main; I left them, because #40881 reformats that file. Not run: - Android UI tests (Appium), including the selection screenshot tests; left to CI. - Physical devices. - iOS, Mac Catalyst and Windows, which these Android-only files don't affect. - Unit tests, since no shared code changed. #### Overlap with #40881 #40881 also edits `SelectableItemsViewAdapter.cs`. Merging the two conflicts in `OnViewRecycled`, where each PR changes one of two adjacent lines. The bind path merges cleanly. The resolution keeps both: ```csharp selectable.Clicked -= SelectableClickedHandler; selectable.UpdateIsSelected(false); ``` ### 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. --> None; this was found by profiling. Related: - #40881 also edits `SelectableItemsViewAdapter.cs`; see above. - #40318 (inflight/11.0.1xx-sr3) composes with the decoration change: its checks treat a missing decoration like a zero-spacing one. - #37337 is opt-in handler update batching. - #31591 re-syncs selection on click; that path is unchanged here. - #38969 and #39661 also changed the spacing decoration (its cost and its outer-edge spacing). ### 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>
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> # Conflicts: # src/Core/src/Handlers/Element/ElementHandler.cs # src/Core/src/Handlers/IElementHandler.cs # src/Core/tests/UnitTests/AbstractViewHandlerTests.cs
| var property = node.Property!; | ||
| _pendingPropertyUpdateHead = node.Next; | ||
| indices.Remove(property); | ||
| InvokeCurrentPropertyMapper(property); |
There was a problem hiding this comment.
[major] Logic and Correctness Verification - Earlier queued mappers can overwrite values that later queued mappers are supposed to apply. With the primary batching switch enabled before VisualElement initialization, take a connected Windows Entry displaying "a" and execute BatchBegin(); Text = "abcdef"; CursorPosition = 2; SelectionLength = 2; BatchCommit();. The Text mapper runs first through Controls' Windows TextBoxExtensions.UpdateText, which changes native text and calls Select(cursorPosition, 0). EntryHandler.OnPlatformSelectionChanged writes that caret and zero selection length back through ITextInput into the managed properties, overwriting the requested selection before its pending mappers read it. Without batching, the selection assignments follow Text's native callbacks and survive. Preserve pending selection intent across native feedback and add a real Windows Entry regression test; the added list/counter-only mapper tests cannot detect this lost selection.
There was a problem hiding this comment.
MAUI Autopilot · round 1
❌ Not changed. The Windows Entry fix and regression tests could not be published: the append-only push was rejected because existing PR history includes a documentation path outside the allowed paths. The Windows tests still need a Windows runner.
|
|
||
| bool IPropertyUpdateBatchingElement.IsAutomaticPropertyUpdateBatchingEnabled => false; | ||
|
|
||
| bool IPropertyUpdateBatchingElement.IsPropertyUpdateBatchingExplicitlyScoped => true; |
There was a problem hiding this comment.
[moderate] Regression Prevention and Test Coverage - These fixtures replace VisualElement's switch-backed batching contract, and AlwaysBatchingButton reports an open explicit scope before BatchBegin. Returning false from the production enabled property would leave the batching assertions unchanged; removing the explicit-only BeginPropertyUpdateBatch notification is also masked by this pre-opened scope. The benchmark overrides the interface too, while Controls' TestBatching has no attached handler. Add isolated switch-initialization coverage with an unmodified control and attached handler, checking the disabled case, primary-switch-only batching, automatic batching, updates outside a scope, and nested commits.
There was a problem hiding this comment.
MAUI Autopilot · round 1
❌ Not changed. The isolated startup-switch test passed locally without changing production switch caching, but the append-only push was rejected because existing PR history includes a documentation path outside the allowed paths.
| handler = new HandlerStub(mapper); | ||
| var view = new AlwaysBatchingButton(); | ||
|
|
||
| handler.SetVirtualView(view); |
There was a problem hiding this comment.
[moderate] Regression Prevention and Test Coverage - SetVirtualView executes the initial First mapper, whose FlushPendingPropertyUpdates call ends explicit batching during setup. After mapped.Clear(), both UpdateValue calls therefore execute immediately and the final flush is empty. The First/Second assertion never exercises a reentrant commit with Second still queued, so it cannot detect dropped work in the active-drain scenario. Suppress the commit during initialization, begin a fresh batch afterward, and assert that nothing mapped before triggering the flush. The reflection-based companion covers the different outside-drain scenario.
There was a problem hiding this comment.
MAUI Autopilot · round 1
❌ Not changed. The corrected reentrant-commit test passed locally, but the append-only push was rejected because existing PR history includes a documentation path outside the allowed paths.
| // BatchedPropertyUpdatesResolveChainedMapperAtFlushTime); switching this to the | ||
| // cached path would silently drop any chained-mapper customization applied | ||
| // between when a property was queued and when it is flushed. | ||
| _mapper.GetProperty(property)?.Invoke(this, VirtualView!); |
There was a problem hiding this comment.
[minor] Complexity Reduction - This separate mapper-invocation path duplicates existing infrastructure and drops its instrumentation. With HANDLER_INSTRUMENTATION enabled and an ActivityListener attached, explicit-batch flushes and automatic trailing updates execute without the MapProperty activities emitted by PropertyMapper.UpdateProperty, so their mapper work disappears from attribution. The historical reason in the comment no longer applies to this pinned source: PropertyMapper.Merged validates ChainVersion across chained mappers and rebuilds after parent customization. Reuse the existing UpdateProperty invocation path for queued updates to preserve both live chained customization and instrumentation.
There was a problem hiding this comment.
MAUI Autopilot · round 1
❌ Not changed. The local instrumentation test failed on the original direct mapper path and passed with the shared path, but the append-only push was rejected because existing PR history includes a documentation path outside the allowed paths.
|
MAUI Autopilot · round 1 No fixes were published: the push was rejected because the existing PR history includes |
This comment has been minimized.
This comment has been minimized.
…hout a proposal (#40919) <!-- copilot-assessment:v1 --> ### Agent assessment Self-reported assessment, not an independent review. Assessed revision: `11c30c44a06a0739ce0715e1b6f5aecbd44f3fc9` | Dimension | Assessment | Rationale | |---|---|---| | Change confidence | 9/10 | ↑ Replayed the job condition on real run results: MAI run 46558270750 (agent success, no proposal) now hands over; normal runs and agent-failure-after-proposal unchanged.<br>↑ `review-run-tests-dispatch.yml` already handles one or both proposals missing and posts a result.<br>↑ Both workflows compile.<br>↓ Live check pending merge. | | Diagnosis confidence | 9.5/10 | ↑ MAI agent log: "Unable to complete because I did not call the required test-selection output tool"; `agent_output.json` has 0 items; `run_selected_ui_tests` and `run-tests-fallback` both skipped; no dispatch run for #37337. | | Evidence fit | 9.5/10 | ↑ #37337 has sat in `s/autopilot-testing` since 01:59 with no test comment for its head. | <!-- /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! ### Description of Change `/review run-tests` selects tests with two models in sequence, then `review-run-tests-dispatch.yml` combines their proposals and posts the result. The fallback that hands over without a proposal ran only when the agent job **failed**. For #37337 the MAI Code 2 agent **succeeded** but never called the selection tool, so `run_selected_ui_tests` and `run-tests-fallback` were both skipped. Nothing was dispatched, no result comment was posted, and MAUI Autopilot waits in `testing` forever. The fallback in both `copilot-review-run-tests` and `copilot-review-run-tests-mai` now also runs when the agent succeeded but nothing was dispatched. Validation: replayed the job condition against real run results; `gh aw compile` succeeds for both workflows. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
MAUI Autopilot — Stopped@kubaflo ❌ The last fix round found nothing more it could fix. Decide how to continue, or comment WhyNo fixes were published. The PR is still on the same head that the append-only push rejected because its existing diff includes |
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 work. The branch has been rebased onto
mainat331056d8a2and the GitHub base is nowmain.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 an opt-in experiment that coalesces repeated .NET MAUI handler property updates before they cross into the platform control.
The application surface does not change: apps continue to use ordinary XAML, controls, bindings, events, and handler mapper customization. Once automatic batching is enabled, no method calls or XAML changes are required.
The goal is to avoid repeatedly assigning transient values to the same native properties during a synchronous update burst when only the final value can become visible.
Enabling the experiment
Set both switches before MAUI initializes
VisualElement:The values are cached during
VisualElementtype initialization.Enabling only
Microsoft.Maui.Experimental.HandlerUpdateBatchingapplies coalescing to existingBatchBegin()/BatchCommit()scopes without enabling automatic dispatcher batching.What it does
Explicit batches
Property notifications received between
BatchBegin()andBatchCommit()are deduplicated and flushed synchronously at commit.Automatic batches
A, B, Aflushes asB, A.A dispatcher turn means the interval before the queued callback executes. It is an event-loop boundary, not a 10 ms window or a guarantee of one display frame.
Correctness model
Only top-level notifications are deferred.
UpdateValuecalls made by a mapper execute synchronously, preserving dependency order for formatting, container creation, clipping, shadows, borders, and similar mappings.InvalidateMeasure, flushes pending properties first; measure invalidation remains synchronous and is not coalesced.PlatformViewandContainerViewaccess flush pending top-level work, except while a mapper is executing.AppendToMapping/PrependToMappingcustomization is used.CanInvokeMappers()before touching a potentially disposed Java peer.Implementation and hot paths
The pending queue is bounded by the number of distinct pending properties and supports O(1) enqueue and move-to-last operations using:
The dispatcher callback and queue storage are reused after the first batch. Steady-state batches do not allocate.
When batching is inactive, initial mapping,
UpdateValue, and command invocation use the existing direct mapper path. Platform-view access reduces to a zero pending-count check.Benchmark results
The committed BenchmarkDotNet benchmark contains no logging, string formatting,
ConcurrentDictionary, or metric aggregation inside timed mapper callbacks. It compares:On an Apple M3 Pro with deliberately no-op mappers:
These results show the batching machinery itself, not native mapper savings:
The earlier 18.1x instrumented Sandbox result overstated elapsed speedup because the timed mapper callbacks performed logging and shared metric aggregation. It remains useful as a qualitative demonstration of mapper-call reduction, not as a representative performance claim.
Demonstration
This synchronized recording shows the earlier instrumented prototype applying the same 100-round update workload in stock and batched modes:
ios-stock-vs-batched-side-by-side.mp4
The recording demonstrates that native values converge to the same final state. Its displayed elapsed times are not the final benchmark evidence.
Validation
Current rebase and review fixes (November 19, 2026)
Rebased onto
mainat331056d8a2, retaining upstream handler instrumentation. No Sandbox changes are included.Non-platform build/test commands below use these MSBuild properties:
Results: prerequisite builds passed; Core 1,154 passed normally and 1,161 passed with instrumentation; targeted Controls 156 passed; benchmark project Release build passed. All reported builds completed with zero warnings and zero errors.
Regression proof: disabling just the teardown guard and outstanding-callback fix produces 10 failures in
AbstractViewHandlerTests; restoring them passes all 43 handler cases within the full Core suite. Five barrier variants each reproduce 100 callbacks before / 1 callback after for 100 synchronous barrier cycles. Explicit/automatic container teardown and virtual-view replacement/reconnect are covered.Android Release build commands:
Results: Core and Controls Android Release builds passed, zero warnings/errors. The generator restores repair an existing restore-graph issue where
-fpropagates the Android framework into generator assets.Remaining validation limitations: iOS and Mac Catalyst Release builds targeting the repository's
27.0fail withNETSDK1140: this host's installed Apple workloads support only26.5. The actual SDK used here is11.0.100-rc.2.26475.136, not the bootstrapped11.0.100-rtm.26514.118recorded undertools.dotnetinglobal.json. Apple builds and device/UI rendering validation still require a matching provisioned host/CI. No new runtime or benchmark timing claims are made by this rebase.Published head:
b433f51c71. Freshmaui-prbuild 1689766 is in progress on the finalmainbase. Device/UI checks initially reportedACTION_REQUIRED/ "Skipped due to merge conflicts" from before retargeting; those are not passing validation and require fresh runs.Historical validation before this rebase
Rollout
Performance status: no representative end-to-render or frame-time improvement has been established. The historical no-op benchmarks show fixed automatic-batching overhead, not a native performance win. This remains a draft experiment with
do-not-mergewhile the benefit/complexity tradeoff is evaluated.Issues Fixed
Experimental proposal; no issue is closed by this PR.