Skip to content

Reduce FlexLayout per-pass allocations and redundant work - #40852

Merged
kubaflo merged 5 commits into
mainfrom
simonrozsival-flex-layout-optimization
Nov 30, 2026
Merged

kubaflo merged 5 commits into
mainfrom
simonrozsival-flex-layout-optimization

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Nov 30, 2026 •

Copy link
Copy Markdown
Member

Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: 65721113b9557f803cb39b17606b7df69b372691

Dimension Assessment Rationale
Change confidence 8/10 ↑ Current focused Controls Flex tests pass 41/41 and Core Flex tests pass 61/61.
↑ The netstandard2.0 Core build passes with PublicApiType=Validate.
↑ Reentrant layout test validates the per-pass buffer lease; Opus 5.5 review found no issues in the wrapper.
↑ Benchmark comparison shows lower allocations in all eight cases.
↓ Benchmarks predate the modern-target range-check helper in this revision; timings are single-machine and show one multimodal case.
↓ No device or UI tests were run.

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

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 .NET 12 layout performance change. It reduces per-pass work and allocations in the measured Controls FlexLayout scenarios. There are no public API changes.

1. Remove the unconstrained-measure hack (PrepareMeasureHack / RestoreValues)

  • Before layout, FlexLayout.Layout() set Shrink and AlignSelf on each child's flex item. It then immediately called EnsureFlexItemPropertiesUpdated(), which wrote the real attached values back over the same items, so the hack never had any effect.
  • It cost an extra loop and closure/list allocation on every unconstrained pass.
  • The two related entries are removed from maui-sc.aotprofile.txt.

2. Stable child ordering and reusable storage in Flex.cs

  • The old code ordered children with LINQ OrderBy, allocating on every pass when any child had a non-zero Order.
  • The new code packs each child into a long key, ((long)Order << 32) | (uint)index, then sorts keys with Array.Sort. This orders first by Order, then by insertion index, preserving stable order for equal values, including negative and extreme int values. If children are already in non-decreasing Order, sorting is skipped.
  • OrderedKeysBuffer encapsulates the backing array and active _count. It retains capacity when child count stays the same or shrinks, and grows only when count exceeds capacity. Sorting and index access use the active count, preventing spare capacity from being treated as valid keys.
  • Each layout pass leases the buffer from its Item and returns it in cleanup(item). A child's SelfSizing callback can re-enter layout; leasing prevents the nested pass from overwriting the outer pass's keys.

3. Skip redundant per-pass refresh of attached flex properties

  • For BindableObject children, attached-property change handlers (Order, Grow, Shrink, AlignSelf, Basis) already keep the Flex.Item in sync. EnsureFlexItemPropertiesUpdated no longer re-runs InitFlexProperties for them on every pass.
  • Children that aren't BindableObject still get the full refresh. UpdateItemProperties (margin, visibility, and similar) still runs for every child.

4. Standalone benchmark

  • Adds FlexLayoutPassBenchmarker to Core.Benchmarks using BenchmarkDotNet MemoryDiagnoser. It repeats measure and arrange passes on a wrapping FlexLayout with fixed-size children, with and without FlexLayout.Order. There are no performance assertions in unit tests.

Measured impact

  • Setup: Apple M5 Max, macOS 26.7.3, .NET 12.0.0 (SDK 12.0.100-alpha.1.26551.101), Arm64; BenchmarkDotNet 0.13.10, InProcessEmitToolchain, Release.
  • Revisions compared: baseline Flex.cs and FlexLayout.cs from main at 62130d92cd20df7195efa051b0912679781c206b; measured after source revision 1179bf8bd1a38c14a5c6d95f500dd03cc93e2ca2. Current PR head is 65721113b9557f803cb39b17606b7df69b372691; it adds documented packed-key encoding and ArgumentOutOfRangeException guard helpers on .NET 8+ (with the equivalent existing check for netstandard), plus removes a baseline-passing characterization test. Those latest changes were not part of the timing run.
  • Layout: Wrap = FlexWrap.Wrap, 400 wide, fixed 20×20 children. Reordered children set Order = (Items - i) % 3.
  • Methods: MeasureAndArrange measures at 400×∞ then arranges; UnconstrainedMeasure measures at ∞×∞.
  • Timing: baseline 11:13:43–11:17:01 CET; after 11:17:18–11:21:16 CET, 2026-11-30. These runs used the coordinated timing lease; no overlapping benchmark is known.
Method Items Reordered Before mean ± StdDev After mean ± StdDev Mean Δ Before alloc After alloc Alloc Δ
MeasureAndArrange 10 false 1,410.4 ± 41.1 ns 935.9 ± 7.4 ns −33.6% 248 B 120 B −51.6%
MeasureAndArrange 10 true 1,613.2 ± 47.7 ns 1,058.4 ± 19.4 ns −34.4% 1,352 B 120 B −91.1%
MeasureAndArrange 100 false 14,951.0 ± 242.4 ns 9,837.6 ± 172.0 ns −34.2% 584 B 456 B −21.9%
MeasureAndArrange 100 true 17,913.0 ± 490.2 ns 11,284.5 ± 508.5 ns −37.0% 4,568 B 456 B −90.0%
UnconstrainedMeasure 10 false 733.2 ± 12.3 ns 462.2 ± 16.7 ns −37.0% 560 B 456 B −18.6%
UnconstrainedMeasure 10 true 838.8 ± 13.4 ns 502.3 ± 11.0 ns −40.1% 1,112 B 456 B −59.0%
UnconstrainedMeasure 100 false 7,293.2 ± 226.3 ns 4,704.6 ± 153.9 ns −35.5% 3,320 B 3,216 B −3.1%
UnconstrainedMeasure 100 true 8,306.1 ± 96.3 ns 5,242.0 ± 76.8 ns −36.9% 5,312 B 3,216 B −39.5%

Per-operation allocations for reordered children matched the non-reordered cases at the same child count in this warm, repeated-pass benchmark. Since the latest GetItemIndex guard change was not benchmarked, treat these figures as measurements of revision 1179bf8bd1, not exact current-head performance.

  • Commands, run once per revision:
    dotnet build src/Core/tests/Benchmarks/Core.Benchmarks.csproj -c Release --disable-build-servers -p:IncludeAndroidTargetFrameworks=false -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false
    cd artifacts/bin/Core.Benchmarks/Release/net12.0
    dotnet Core.Benchmarks.dll --filter '*FlexLayoutPassBenchmarker*' --inProcess --artifacts "$S/bench3-<baseline-or-final>"
    $S is the session's persistent files directory. Full logs, result files, source hashes and timing metadata are retained there under bench3-{baseline,final} and bench3-metadata.txt.

Limitations: Each revision was measured once, sequentially and in-process on one desktop machine, with repeated iterations within each run. BenchmarkDotNet could not raise process priority on either run (permission denied). The after run for 100-child unconstrained measure without reordering was flagged as multimodal (mValue = 2.88), and the reordered 100-child measure-and-arrange case had a 508.5 ns standard deviation. Timing reductions are indicative rather than a cross-device guarantee. No Android/iOS device measurements were run. The obsolete Compatibility FlexLayout keeps its own copy of the hack and is untouched.

Review

  • A read-only review with Claude Opus 5.5 (long context) found no significant issues, examining hack removal, stable ordering, buffer leasing/reentrancy, attached-property synchronization and item lifecycle.
  • Earlier coordination raised two points, both addressed: per-pass buffer leasing prevents reentrant corruption, and stale aotprofile entries were removed.
  • A follow-up Opus 5.5 review found no issues in capacity/count handling, key decoding, ownership or reentrant leasing.
  • Inline review follow-ups clarified why packed keys use 64 bits, documented the original-index encoding, and replaced the manual range guard with .NET 8+ ArgumentOutOfRangeException.ThrowIf... helpers; netstandard retains its equivalent check.

Tests added (FlexLayoutTests)

  • OrderChangesAfterLayoutAreAppliedAndRevertWhenReset
  • EqualOrderValuesKeepInsertionOrder
  • FlexPropertyChangesAfterLayoutAreApplied
  • CoreViewFlexPropertyChangesAfterLayoutAreApplied
  • ReentrantLayoutWithOrderChangesDoesNotCorruptOuterPassOrder

Validation

  • dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj -p:IncludeAndroidTargetFrameworks=false -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false --filter "FullyQualifiedName~FlexLayoutTests|FullyQualifiedName~FlexOrderTests|FullyQualifiedName~FlexLayoutMarginTests": 41/41 passed at current head.
  • The same project with --filter "FullyQualifiedName~FlexLayoutTests" on main's Flex.cs and FlexLayout.cs: 28/28 passed.
  • dotnet test src/Core/tests/UnitTests/Core.UnitTests.csproj -p:IncludeAndroidTargetFrameworks=false -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false --filter "FullyQualifiedName~Flex": 61/61 passed.
  • dotnet build src/Core/src/Core.csproj -f netstandard2.0 --no-restore -p:PublicApiType=Validate -p:IncludeAndroidTargetFrameworks=false -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false: succeeded.
  • git diff --check: clean.

Issues Fixed

None. This is proactive layout performance work.

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.

- Remove FlexLayout's unconstrained-measure hack (PrepareMeasureHack/RestoreValues).
  EnsureFlexItemPropertiesUpdated always overwrote the values it set before layout,
  so it had no effect besides extra work and a per-pass allocation.
- Order children with packed (Order, index) keys sorted in a reusable buffer leased
  per layout pass instead of LINQ OrderBy, and skip sorting when children are already
  in non-decreasing Order. Stable for equal Order values; reentrant-safe.
- Skip the per-pass InitFlexProperties refresh for bindable children whose flex item
  is kept in sync by the attached-property change handlers.
- Remove stale aotprofile entries, add focused tests and a FlexLayout pass benchmark.

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

This comment has been minimized.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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.

🟡 Changes recommended

Flex-property synchronization is not notification- and reentrancy-safe, allowing PropertyChanged subscribers to measure stale values or leave layout ordering inconsistent with the attached property.

1 open issue
What changed in this PR

This PR reduces allocations and repeated work in .NET MAUI’s FlexLayout measure and arrange passes without changing the public API.

Changes:

  • Replaces LINQ child ordering with reusable packed-key buffers that preserve stable ordering and isolate reentrant passes.
  • Removes ineffective unconstrained-measure adjustments and skips repeated attached-property refreshes for bindable children.
  • Adds focused regression tests and allocation benchmarks, and removes obsolete AOT profile entries.
File Description
src/​Core/​tests/​Benchmarks/​Benchmarks/​FlexLayoutPassBenchmarker.cs Benchmarks repeated layout passes with default and reordered children.
src/​Core/​src/​Layouts/​Flex.cs Implements reusable ordering buffers and an already-sorted fast path.
src/​Controls/​tests/​Core.UnitTests/​Layouts/​FlexLayoutTests.cs Tests unconstrained measurement, ordering, property updates, and reentrancy.
src/​Controls/​src/​Core/​Layout/​FlexLayout.cs Removes measure adjustments and reduces per-pass property refresh work.
src/​Controls/​src/​Build.Tasks/​nuget/​buildTransitive/​netstandard2.0/​maui-sc.aotprofile.txt Removes entries for the deleted measure-adjustment methods.

Review effort: Balanced

Comment on lines +648 to +653
// For bindable children, the attached property changed handlers keep
// Order, Grow, Shrink, Basis and AlignSelf in sync with the Flex.Item.
if (child is not BindableObject)
{
InitFlexProperties(child, flexItem);
}
@kubaflo

This comment has been minimized.

@kubaflo

This comment has been minimized.

@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 — 1 finding · ⚠️ 1 breaking change

Reviewed commit 1179bf8.

Warning

Existing apps would look or behave differently without opting in. See the Behavioral Change Disclosure findings at:

See inline comments for details.

InitItemProperties(child, flexItem);
// For bindable children, the attached property changed handlers keep
// Order, Grow, Shrink, Basis and AlignSelf in sync with the Flex.Item.
if (child is not BindableObject)

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.

[major] Logic and Correctness - Removing this refresh can leave attached values and Flex.Item permanently inconsistent. BindableObject.OnBindablePropertySet raises public PropertyChanged before the attached-property callback, and ClearValue invokes its callback synchronously. With two default-order children, have the first child's Order subscriber clear OrderProperty when GetOrder returns 1, then call SetOrder(child, 1). The nested clear stores Item.Order=0, but the outer callback subsequently stores 1. GetOrder returns 0 while subsequent measure/arrange passes still put that child last; the previous per-pass refresh repaired this mismatch. Retain the refresh or make synchronization notification- and reentrancy-safe. Add tests for measuring and clearing attached properties inside PropertyChanged; the added reset and MeasureOverride-reentrancy tests cover neither notification path.

[major] Behavioral Change Disclosure - Existing apps measuring synchronously from PropertyChanged also observe changed behavior on every platform: setting Grow from 0 to 1 on the first of two 10-wide children and measuring a 100-wide row inside the notification previously produced widths 90 and 10, but now produces 10 and 10 because the callback has not yet synchronized the item. Preserve the prior behavior; if this timing change is intentional, disclose it and provide an explicit opt-in/opt-out retaining the existing behavior. Neither is supplied.

@github-actions

This comment has been minimized.

kubaflo
kubaflo previously approved these changes Nov 30, 2026
@kubaflo

kubaflo commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

/review tests

Use ArgumentOutOfRangeException guard helpers on modern targets.\n\nCo-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 30, 2026 13:44

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.

🔵 Needs a closer look

Removing the per-pass refresh allows layout during PropertyChanged notifications to use stale Flex.Item values and can leave child ordering permanently out of sync after reentrant property changes.

1 open issue
1 previously missed issue

In code that hasn't changed since last review

Low severity Test child-count changes and buffer resizing in ordering

src/​Core/​src/​Layouts/​Flex.cs:269

The ordering tests all keep the child count fixed, leaving the new active-count/capacity behavior untested. Add a unit test that warms the buffer with reordered children, removes children while retaining a nontrivial order, measures again, then adds enough children to exceed the previous capacity and verifies their positions. This should exercise both spare-capacity reuse and resizing; the current order-change and reentrancy tests cannot catch stale keys being treated as active after a count change.

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 65721113.

Result NOT QUEUED Platforms Android, iOS, MacCatalyst, Windows Tests 1 UI, 1 device Commit 65721113


🧪 Test selection — click to expand
Suite Result Selected Build
UI tests ❌ not queued 1 of 77 categories —
Device tests ❌ not queued 1 of 105 units —
🧪 UI tests — Layout on Android, iOS, MacCatalyst, Windows

❌ Could not queue maui-pr-uitests: This PR has merge conflicts with main, so there is no test-merge commit to build. Resolve the conflicts, then comment /review run-tests again.

GPT-6.2 Sol: Run Layout UI tests on all four platforms for the shared FlexLayout measure and child-ordering changes.
MAI Code 2: Shared FlexLayout engine and property synchronization changes; runs Layout UI tests on all platforms.

🧪 Running — 1 category on Android, iOS, MacCatalyst, Windows

Platform Categories
Android Layout
iOS Layout
MacCatalyst Layout
Windows Layout
🧪 Device tests — Controls.FlexLayout on Android, iOS, MacCatalyst, Windows

❌ Could not queue maui-pr-devicetests: This PR has merge conflicts with main, so there is no test-merge commit to build. Resolve the conflicts, then comment /review run-tests again.

GPT-6.2 Sol: Run Controls.FlexLayout device tests on all four platforms to exercise the shared FlexLayout implementation.
MAI Code 2: Shared FlexLayout engine and Controls property changes; runs FlexLayout device tests on all platforms.

🧪 Running — 1 category on Android, iOS, MacCatalyst, Windows

Platform Categories
Android Controls.FlexLayout
iOS Controls.FlexLayout
MacCatalyst Controls.FlexLayout
Windows Controls.FlexLayout
⏭️ 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, CollectionView6, 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, 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 — 104 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.FlyoutPage, Controls.Frame, Controls.Gesture, Controls.HybridWebView, Controls.Image, Controls.Label, Controls.Layout, Controls.Lifecycle, Controls.Map, Controls.Mapper, Controls.Memory, Controls.MenuFlyout, Controls.Modal, Controls.NavigationPage, Controls.Page, Controls.PageTransitions, Controls.Path, Controls.Picker, Controls.RadioButton, Controls.RefreshView, Controls.ScrollView, Controls.SearchBar, Controls.Shape, Controls.Shell, Controls.Slider, Controls.SwipeView, Controls.Switch, Controls.TabbedPage, Controls.TemplatedView, Controls.TextInput, Controls.Toolbar, Controls.View, Controls.VisualElement, Controls.VisualElementTree, Controls.WebView, Controls.Window, Controls.WindowOverlay, Controls.Xaml, 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 Layout Layout
iOS Layout Layout
MacCatalyst Layout Layout
Windows Layout Layout

GPT-6.2 Sol — Run Layout UI tests on all four platforms for the shared FlexLayout measure and child-ordering changes.

  • FlexLayout.cs changes flex child property refresh and unconstrained measure; Flex.cs changes child ordering on all four platforms.
  • No layout base or platform pipeline changes; the AOT profile only drops entries for removed methods.

MAI Code 2 — Shared FlexLayout engine and property synchronization changes; runs Layout UI tests on all platforms.

  • FlexLayout.cs and the shared Flex.cs engine change FlexLayout measure, ordering, and property propagation on every platform.
  • Select the Layout UI category because the inventory has no FlexLayout-specific UI category.
  • Leave other UI categories out; the diff does not change general handlers, startup, resources, or shared test infrastructure.

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.FlexLayout Controls.FlexLayout
iOS Controls.FlexLayout Controls.FlexLayout
MacCatalyst Controls.FlexLayout Controls.FlexLayout
Windows Controls.FlexLayout Controls.FlexLayout

GPT-6.2 Sol — Run Controls.FlexLayout device tests on all four platforms to exercise the shared FlexLayout implementation.

  • Controls.FlexLayout includes tagged tests for nested stack layouts and a button with an image in a wrapping FlexLayout.
  • Flex.cs is FlexLayout-specific; no generic layout handler changed, so broader Controls.Layout and Core.Layout runs are not needed.

MAI Code 2 — Shared FlexLayout engine and Controls property changes; runs FlexLayout device tests on all platforms.

  • FlexLayout.cs and Flex.cs are shared code affecting FlexLayout behavior across all device platforms.
  • Controls.FlexLayout directly covers ordering, sizing, margins, and reentrant layout behavior changed by the PR.
  • Leave broader Controls/Core suites out because the changes are confined to FlexLayout rather than base layout or handler infrastructure.

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 — 1 finding · ⚠️ 1 breaking change

Reviewed commit 6572111.

Warning

Existing apps would look or behave differently without opting in. See the Behavioral Change Disclosure findings at:

Previously reported findings were not duplicated.

@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/autopilot-running MAUI Autopilot loop is running; remove this label to stop it label Nov 30, 2026
@github-actions

This comment has been minimized.

@github-actions github-actions Bot added the s/autopilot-fixing MAUI Autopilot: fixing review findings or failing tests (GPT-6.2 Sol vs MAI Code 2) label Nov 30, 2026
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

# Conflicts:
#	src/Core/src/Layouts/Flex.cs
Copilot AI balanced review requested due to automatic review settings November 30, 2026 22:08
@github-actions github-actions Bot added s/autopilot-reviewing MAUI Autopilot: MAUI expert review in progress and removed s/autopilot-fixing MAUI Autopilot: fixing review findings or failing tests (GPT-6.2 Sol vs MAI Code 2) labels Nov 30, 2026

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.

🔵 Needs a closer look

Synchronous measurement from a PropertyChanged subscriber can observe stale Flex item values, returning the old ordering after the bindable Order property has already changed.

1 open issue

Review effort: Balanced

@kubaflo
kubaflo merged commit e467e2f into main Nov 30, 2026
5 of 6 checks passed
@kubaflo
kubaflo deleted the simonrozsival-flex-layout-optimization branch November 30, 2026 22:18
@github-actions github-actions Bot added the s/autopilot-retrying maui-expert-autopilot: retrying a step that failed once label Nov 30, 2026
@github-actions

Copy link
Copy Markdown
Contributor

MAUI Autopilot — Retrying

@kubaflo ❌ The MAUI expert review failed. The loop retries it once. Run.

@kubaflo kubaflo removed s/autopilot-running MAUI Autopilot loop is running; remove this label to stop it s/autopilot-reviewing MAUI Autopilot: MAUI expert review in progress s/autopilot-retrying maui-expert-autopilot: retrying a step that failed once labels Dec 1, 2026
kubaflo added a commit that referenced this pull request Dec 1, 2026
)

<!-- copilot-assessment:v1 -->
### Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: `54f080994407a59cd73d16f38f8136277f2cf9fc`

| Dimension | Assessment | Rationale |
|---|---|---|
| Change confidence | 8.5/10 | ↑ Layouts and Flex unit tests pass
154/154 locally.<br>↑ Two Claude Opus 5.5 code reviews found no
significant issues.<br>↓ No device or UI tests run.<br>↓ No perf
benchmark run to confirm the per-pass saving is kept.<br>↓ CI not yet
inspected. |
| Diagnosis confidence | 9.5/10 | ↑ 3 new tests fail on main and pass
against the pre-#40852 FlexLayout.cs (62130d9).<br>↑ Source order in
BindableObject confirms PropertyChanged is raised before the property
callback, and ClearValue is not queued. |
| Evidence fit | 8/10 | ↑ Matches the concern in review thread
r4738447796 on #40852.<br>↓ Found by code review; no user-reported
symptom yet. |
<!-- /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).

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 fixes a regression from #40852 that was raised in review thread
#40852 (comment). The
base is `main` because #40852 is only on `main`.

#40852 stopped re-reading `Order`, `Grow`, `Shrink`, `Basis` and
`AlignSelf` for bindable children on every layout pass. Instead, the
attached-property `propertyChanged` callbacks copied `newValue` into the
`Flex.Item`. However, `BindableObject` raises the public
`PropertyChanged` event before it runs the property's own callback. So:

- **Cleared value lost:** If a `PropertyChanged` subscriber calls
`ClearValue`, the cleared value is stored first, and then the outer
callback writes the stale value back. Layout never corrects it. This
doesn't happen with `SetValue`, because nested `SetValue` calls are
queued and `ClearValue` calls are not.
- **Old value measured:** A measure run synchronously from a
`PropertyChanged` subscriber sees the old value.

**Fix**
- `Flex.Item` gets an internal `NeedsFlexPropertiesUpdate` flag. It is
set in both the `propertyChanging` and `propertyChanged` callbacks of
the five attached properties.
- `EnsureFlexItemPropertiesUpdated` re-reads those five values from the
`BindableObject` only for items marked as changed. Unchanged items are
skipped, which keeps the per-pass saving from #40852.
- Nested `FlexLayout`s are laid out as part of the root pass, because
their own `Layout()` returns early. The root pass now refreshes changed
flex properties for their children too. It does not refresh margin, size
or visibility for nested children, which matches previous behavior.

**Tests** (`Controls.Core.UnitTests`, `FlexLayoutTests`)
- `OrderClearedFromPropertyChangedHandlerIsApplied`,
`FlexPropertiesClearedFromPropertyChangedHandlerAreApplied` and
`MeasureFromPropertyChangedHandlerSeesNewOrder` fail on `main` and pass
with this fix. They also pass against the pre-#40852 `FlexLayout.cs`
(62130d9).
- `FlexPropertyChangesInNestedFlexLayoutAreApplied` guards the nested
refresh that this lazy approach needs. It passes on `main` and on the
baseline.

**Validation**
- `dotnet test
src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj
-p:IncludeAndroidTargetFrameworks=false
-p:IncludeIosTargetFrameworks=false
-p:IncludeMacCatalystTargetFrameworks=false
-p:IncludeMacOSTargetFrameworks=false --filter
"FullyQualifiedName~Layouts|FullyQualifiedName~Flex"`: passed, 154/154.
- Not run: device tests, UI tests, perf benchmark.

### Issues Fixed

Fixes a regression introduced by #40852 (review thread
#40852 (comment)). No
separate issue is filed.

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