Repository navigation
[net11] Fix CollectionView crash during incremental loading - #40578
Merged
Merged
Conversation
kubaflo
temporarily deployed
to
copilot-pat-pool
November 24, 2026 13:56 — with
GitHub Actions
Inactive
Contributor
|
🚀 Dogfood this PR with:
curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 40578Or
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 40578" |
kubaflo
temporarily deployed
to
copilot-pat-pool
November 24, 2026 13:57 — with
GitHub Actions
Inactive
This comment has been minimized.
This comment has been minimized.
kubaflo
temporarily deployed
to
copilot-pat-pool
November 24, 2026 13:58 — with
GitHub Actions
Inactive
kubaflo
marked this pull request as ready for review
November 24, 2026 14:00
kubaflo
temporarily deployed
to
copilot-pat-pool
November 24, 2026 14:00 — with
GitHub Actions
Inactive
kubaflo
temporarily deployed
to
copilot-pat-pool
November 24, 2026 14:04 — with
GitHub Actions
Inactive
kubaflo
temporarily deployed
to
copilot-pat-pool
November 24, 2026 14:05 — with
GitHub Actions
Inactive
This was referenced Nov 24, 2026
KarthikRajaKalaimani
pushed a commit
to KarthikRajaKalaimani/maui
that referenced
this pull request
Nov 26, 2026
…0578) <!-- 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 <!-- Enter description of the fix in this section --> Backport dotnet#40481 from `release/11.0.1xx-sr2` to `net11`. The change prevents re-entrant CollectionView remaining-items threshold notifications and skips threshold evaluation when the scrolled event replaces the items source. It includes the original iOS/MacCatalyst device tests. Source commit: `4858add2c0fdb0fc6ccfff39ee2dfde40b61e78d`. **Validation** - `git diff --cached --check` - passed. - `git diff --cached | git patch-id --stable` - matched the patch ID of source commit `4858add2c0fdb0fc6ccfff39ee2dfde40b61e78d`. - Building `Microsoft.Maui.BuildTasks.slnf` failed locally with `NETSDK1140`: the installed Apple workload accepts platform version 27.2 while the projects request 27.0. - iOS and MacCatalyst device tests were not run locally; CI validation is required. ### 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. --> Relates to dotnet#40467. <!-- Verify the target branch follows the release workflow in docs/ReleaseBranchWorkflow.md. Infrastructure and documentation changes should target the branch where they apply. -->
1 of 2 tasks
kubaflo
added a commit
that referenced
this pull request
Nov 30, 2026
…ng only when something uses them (#40896) <!-- copilot-assessment:v1 --> ### Agent assessment Self-reported assessment, not an independent review. Assessed revision: `ca4a1c046566a164211ecc150ee188c142d068df` | Dimension | Assessment | Rationale | |---|---|---| | Change confidence | 8.5/10 | ↑ `Scrolled` event args matched main's algorithm on all 1,810 callbacks across 9 layouts (temporary check, not committed).<br>↑ New Mac Catalyst device tests pass; the "nothing listens" case fails on main, and two broken variants of the skip path fail the delta test.<br>↑ Controls unit tests for ItemsView, CollectionView, CarouselView and SwipeView: 96/96 pass.<br>↑ Benchmark over 12 paired rounds: −4,028 B/row (exact) and −4.9% UI-thread CPU [−8.2% .. −2.9%].<br>↓ Subclasses of `ItemsViewDelegator2` that override `GetVisibleItemsIndex` or `GetVisibleItemsIndexPath` are no longer called on scroll when nothing listens.<br>↓ A broad Mac Catalyst device-test run under heavy host load had 2 timing failures; both passed in isolation and weren't rerun on main.<br>↓ Not run on an iOS simulator or device; CI pending. | <!-- /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 <!-- Enter description of the fix in this section --> On iOS and Mac Catalyst, `ItemsViewDelegator2.Scrolled` found the visible items on every scroll callback. It sorted `IndexPathsForVisibleItems` with LINQ (`OrderBy`/`ThenBy`/`ToList`), asked the layout for the attributes of everything in the viewport, queried and sorted `IndexPathsForVisibleItems` a second time for the center item's fallback, and wrapped every attribute and index path in a new managed peer. It did all that even when nothing read the result: no `Scrolled` handler, no `OnScrolled` override, and `RemainingItemsThreshold` at its default of -1. In a Mac Catalyst trace of the [CollectionView scroll benchmark](https://github.com/dotnet/maui/tree/simonrozsival-collectionview-scroll-benchmark/src/Controls/tests/CollectionViewScrollBenchmark) on main, which has no `Scrolled` subscriber, that was about 10% of the UI thread's allocations and 6% of its CPU time. **Changes** - `ItemsViewDelegator2.Scrolled` finds the visible items only when the `Scrolled` event (a handler, or an override of `ItemsView.OnScrolled`) or the remaining items threshold uses them. Otherwise it only updates the offsets that the deltas of the next `Scrolled` event are measured from, exactly as before: the content offset plus the inset, or 0 while no item is visible (#34153). It checks for visible items with `VisibleCells.Length`. That counts the same cells as `IndexPathsForVisibleItems`, but the cells already have managed peers, which the index paths would need new ones for. - When the visible items are needed, they're found without LINQ: one pass over `IndexPathsForVisibleItems` finds the first and last items by section and row, and the first by row (the center's fallback), breaking ties the way the stable sorts did. The second `IndexPathsForVisibleItems` query is gone. The layout-attribute scan (#34240, #33719, #40131) is unchanged, except that it reads each attribute's frame and index path once. - `ItemsView.HasScrolledObservers` (internal) is true when `Scrolled` has a handler or `OnScrolled` is overridden. The override check is cached and works like `Page.HasBackButtonPressedOverride`, through a delegate to the virtual method, which is safe for trimming and AOT. If the declaring type couldn't be read, the check counts as an override and takes the full path. No public API changes. **Why it's safe** - Only `ItemsView.SendScrolled` (the `Scrolled` event and `OnScrolled`) and the threshold check read the visible items: - CarouselView takes its position from the compositional layout's `VisibleItemsInvalidationHandler`, and `CarouselViewDelegator2.Scrolled` still updates `IsScrolling` after `base.Scrolled`. - SwipeView and the Shell flyout subscribe to `Scrolled`, so they take the full path. - No built-in `ItemsView` subclass overrides `OnScrolled`. - The scroll anchor still runs first. - Whenever something listens, the event args are the same as before. A handler that subscribes later gets the same first deltas too. - The threshold behavior and its re-entrancy guard (#40578) are unchanged. **Behavior change for subclasses** When nothing listens, `Scrolled` no longer calls the protected virtual `GetVisibleItemsIndex` and `GetVisibleItemsIndexPath`. A subclass of `ItemsViewDelegator2` that overrides them to observe scrolling isn't called then. Overrides of `Scrolled` itself still run on every callback. **Results** The benchmark scrolls a CollectionView of 1,000 items with a 13-binding row template on every frame. Release builds of main bd40bc6 (`base`) and this PR ca4a1c0 (`fix`) ran on Mac Catalyst (macOS 26.7.3, M5 Max, 18 cores, CoreCLR .NET 12.0.0-alpha.1.26523.103, SDK 12.0.100-alpha.1.26523.103): - 12 interleaved rounds, a fresh process per launch, alternating the order. - Each launch is reduced to the median of its 5 warm passes. - Paired medians of the differences, with 95% sign-test intervals. - The host's load average was 43–65 during the run, so the timing intervals are wide. | Per row bound, warm passes | main | this PR | Difference [95% CI] | |---|---|---|---| | Allocated by the UI thread | 29,207 B | 25,178 B | −4,028 B (−13.8%), exact | | Gen0 GCs per pass | 1 | 0 | −1 | | GC pause per pass | 2.8 ms | 0.0 ms | −2.8 ms [−3.1 .. −2.7] | | UI-thread CPU | 3,275.9 µs | 3,105.6 µs | −161.7 µs [−269.3 .. −94.1] (−4.9%) | | Frame interval p50 / p95 | 16.7 / 16.7 ms | 16.7 / 16.7 ms | 0 | | Cold pass: allocated per row | 49,717 B | 37,870 B | −11,847 B (−23.8%), exact | | Cold pass: UI-thread CPU | 1,737.9 ms | 1,654.3 ms | −65.9 ms [−110.0 .. −44.3] | | Cold pass: methods JIT-compiled or prepared by the interpreter on the UI thread | 5 | 1 | −4 | Rebind time per row also came out 18.8 µs lower [−29.9 .. −1.2]. `Scrolled` isn't part of the rebind, so that's probably the missing GC pause plus noise; I don't claim it. The benchmark has no `Scrolled` subscriber. To measure the path with one, a temporary device test (not committed) timed `ItemsViewDelegator2.Scrolled` itself on Mac Catalyst: - Release device-test app; a CollectionView of 1,000 labels with 12 visible. - 240 non-animated scrolls of 100 pt, each followed by `LayoutIfNeeded`; medians of 6 rounds. - Bytes from `GC.GetAllocatedBytesForCurrentThread`; wall-clock time under host load. | Per `Scrolled` callback | main | this PR | |---|---|---| | Nothing listens | 2,251 B, 127.8 µs | 123 B, 10.9 µs | | A `Scrolled` handler | 2,251 B, 127.5 µs | 309 B, 80.0 µs | The 123 B left when nothing listens is the `VisibleCells` array. **Tests added** - `ItemsViewTests.HandlersOfScrolledObserveScrolled` and `OverridesOfOnScrolledObserveScrolled`: unit tests for `HasScrolledObservers`. - `CollectionViewTests.ScrolledFindsTheVisibleItemsOnlyWhenSomethingUsesThem` (iOS and Mac Catalyst device test) counts calls to `GetVisibleItemsIndex`, with 4 cases: nothing listens, a `Scrolled` handler, an `OnScrolled` override, `RemainingItemsThreshold`. On main, the "nothing" case fails (expected 0, actual 1). - `CollectionViewTests.ScrolledMeasuresDeltasFromScrollsNothingListenedTo` (iOS and Mac Catalyst device test) checks the offset and delta of the first event a late handler gets, with items visible and with only a header visible. Two broken variants of the skip path fail it: - Without the offset tracking, the items-visible case fails (delta 600 instead of 100). - Treating the view as always having visible items, the header case fails (delta −500 instead of 0). **Tests run** (macOS 26.7.3, SDK 12.0.100-alpha.1.26523.103; the local `-RepoRoot`, `-DotnetPath` and `-OutputDirectory` arguments are omitted) ```bash dotnet build src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --no-build \ --filter "FullyQualifiedName~ItemsView|FullyQualifiedName~CarouselView|FullyQualifiedName~CollectionView|FullyQualifiedName~SwipeView" # Passed: 96, Failed: 0 # The new tests, the existing Scrolled and threshold tests, and the temporary equivalence check (TempVisibleItemsMatchTheOriginalAlgorithm, not committed) pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform maccatalyst -SkipXcodeVersionCheck \ -IncludeClasses Microsoft.Maui.DeviceTests.CollectionViewTests \ -IncludeMethods ScrolledFindsTheVisibleItemsOnlyWhenSomethingUsesThem,ScrolledMeasuresDeltasFromScrollsNothingListenedTo,TempVisibleItemsMatchTheOriginalAlgorithm,ScrolledSourceChangeUsesCurrentSourceForThreshold,RemainingItemsThresholdLoadsPagesWhileScrolling # Passed: 18, Failed: 0 pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform maccatalyst -SkipXcodeVersionCheck \ -IncludeClasses Microsoft.Maui.DeviceTests.CollectionViewTests,Microsoft.Maui.DeviceTests.CarouselViewTests,Microsoft.Maui.DeviceTests.SwipeViewTests,Microsoft.Maui.DeviceTests.CollectionViewNestedScrollingTests # Passed: 261, Skipped: 4, Failed: 2 of 267 (host load average ~60) ``` The 2 failures in the broad run: - `ScrollToEndFromScrolledAsScrollToStartGoesTheRestOfTheWayReachesTheEnd` stopped 130 pt short of the end. - `RemainingItemsThresholdLoadsPagesWhileScrolling` hit the 15 s harness timeout. Both subscribe to `Scrolled` or set `RemainingItemsThreshold`, so they take the full path, whose output is unchanged. Run on their own, they passed 10 of 10 and 2 of 2 times. I didn't run the broad set on main under the same load. The temporary equivalence check compared `FirstVisibleItemIndex`, `CenterItemIndex` and `LastVisibleItemIndex` from a `Scrolled` handler, on every callback, with a verbatim copy of main's algorithm: - It scrolled down and up through 9 configurations: vertical list, 3-column grid and horizontal list; grouped and ungrouped; with and without a header taller than the viewport. - 1,810 callbacks, 1,738 of them with visible items; 125 used the center fallback and 4 the first/last fallback. No differences. - `VisibleCells.Length` equaled `IndexPathsForVisibleItems.Length` on every callback. **Not run** - iOS simulators or devices. The changed code is the same for iOS and Mac Catalyst. - The full device-test suite and UI tests. - `dotnet format` on the whole solution: only `dotnet format whitespace` on the changed files, which changed nothing. Android and Windows don't use `HasScrolledObservers`. The obsolete `Items/iOS/ItemsViewDelegator.cs` has the same pattern and is unchanged. The benchmark (pushed for reference, not part of this PR): ```bash S=src/Controls/tests/CollectionViewScrollBenchmark/scripts pwsh $S/Build-ScrollBenchmark.ps1 -Variant base -Platform maccatalyst -MauiRoot <checkout of bd40bc6> -BuildTasks pwsh $S/Build-ScrollBenchmark.ps1 -Variant fix -Platform maccatalyst -MauiRoot <checkout of this PR> -BuildTasks pwsh $S/Invoke-ScrollBenchmark.ps1 -Variants base,fix -Platform maccatalyst -Rounds 12 pwsh $S/Compare-ScrollBenchmark.ps1 <results>.jsonl -Baseline base -Candidate fix ``` ### 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 is a performance change. Related: #34153, #34240, #33719, #40131 and #40578 changed this code, and their behavior is kept. #40881 reduces scrolling allocations on Android, measured with the same benchmark. ### 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 branch was previously deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Note
Are you waiting for the changes in this PR to be merged?
It would be very helpful if you could test the resulting artifacts from this PR and let us know in a comment if this change resolves your issue. Thank you!
Target Branch
mainnet11, for reviewFor .NET 11 fixes, only a maintainer retargets the approved PR to the active
inflight lane and merges it after CI validates that final base. Do not merge
individual fixes directly into
net11; agents must not retarget or merge.Description of Change
Backport #40481 from
release/11.0.1xx-sr2tonet11. The change prevents re-entrant CollectionView remaining-items threshold notifications and skips threshold evaluation when the scrolled event replaces the items source. It includes the original iOS/MacCatalyst device tests.Source commit:
4858add2c0fdb0fc6ccfff39ee2dfde40b61e78d.Validation
git diff --cached --check- passed.git diff --cached | git patch-id --stable- matched the patch ID of source commit4858add2c0fdb0fc6ccfff39ee2dfde40b61e78d.Microsoft.Maui.BuildTasks.slnffailed locally withNETSDK1140: the installed Apple workload accepts platform version 27.2 while the projects request 27.0.Issues Fixed
Relates to #40467.