Repository navigation
[Android] CollectionView GridItemsLayout: resolve span index and row from the items source instead of walking every position - #39063
Conversation
…e items source GridLayoutManager resolves the span index / row of a position it has not cached yet by calling getSpanSize() for every position from the nearest cached key up to the target. Each call is a JNI round-trip into GridLayoutSpanSizeLookup, so ScrollTo into a cold region of a large grid (or laying out rows while scrolling back up past the cached keys) costs O(n) per lookup: 200 000 grouped items, ScrollTo last group = 12.8 s. Override GetSpanIndex/GetSpanGroupIndex. The items source already knows where full-span items (header, footer, group headers/footers) sit, so the layout is a short list of blocks - a full-span item or a run of regular items that starts on a fresh row - and span index / row inside a block is arithmetic. The block table is rebuilt lazily after any AdapterDataObserver notification (GridLayoutManager invalidates its own caches on the same notifications) or span count change, and adjacent groups without a separating header/footer are merged into one run because they share rows. Unknown adapters fall back to the base implementation. Add a device test that checks GetSpanIndex/GetSpanGroupIndex against the greedy span assignment GridLayoutManager derives from GetSpanSize, for grouped and flat sources, all header/footer combinations, spans 1-4 and an empty group; a test that the table follows item and group insertions; and a UI test page with 200 000 items where ScrollTo end/middle/start must each finish within 5 s. Fixes dotnet#38926
|
Azure Pipelines: There may be pipelines that require an authorized user to comment /azp run to run. |
|
Hey there @@unrateddi! Thank you so much for your PR! Someone from the team will get assigned to your PR shortly and we'll get it reviewed. |
|
Hey there @unrateddi! Thank you so much for your PR! Someone from the team will get assigned to your PR shortly and we'll get it reviewed. |
This comment has been minimized.
This comment has been minimized.
|
/azp run |
|
Azure Pipelines: Successfully started running 3 pipeline(s). |
|
Note 🔍
|
MauiBot
left a comment
There was a problem hiding this comment.
AI Review Summary
@unrateddi — new AI review results are available based on commit
39cb50c.
🗂️ Review Sessions — click to expand
🚦 Gate — Test Before & After Fix
Gate Result: ✅ PASSED
Platform: ANDROID · Base: inflight/current · Merge base: 5533dd7b
| Test | Without Fix (expect FAIL) | With Fix (expect PASS) |
|---|---|---|
📱 CollectionViewTests (GridSpanLookupMatchesGreedySpanAssignment, GridSpanLookupTracksGroupedSourceChanges) Category=CollectionView |
✅ PASS — 454s | |
🖥️ Issue38926 Issue38926 |
✅ FAIL — 986s | ✅ PASS — 605s |
🔴 Without fix — 📱 CollectionViewTests (GridSpanLookupMatchesGreedySpanAssignment, GridSpanLookupTracksGroupedSourceChanges): ⚠️ ENV ERROR · 1291s
No log file found
🟢 With fix — 📱 CollectionViewTests (GridSpanLookupMatchesGreedySpanAssignment, GridSpanLookupTracksGroupedSourceChanges): PASS ✅ · 454s
(no coded error found; showing last 1200 chars)
"totalMemoryBytes": 8322998272
},
"target": {
"kind": "emulator",
"name": "sdk_gphone_x86_64",
"identifier": "emulator-5554",
"operatingSystem": "Android",
"operatingSystemVersion": "11",
"apiLevel": 30,
"architecture": "x86_64",
"supportedArchitectures": [
"x86_64",
"x86",
"arm64-v8a",
"armeabi-v7a",
"armeabi"
],
"manufacturer": "Google",
"model": "sdk_gphone_x86_64",
"productName": "sdk_gphone_x86_64",
"buildFingerprint": "google/sdk_gphone_x86_64/generic_x86_64_arm64:11/RSR1.201211.001/7027799:user/release-keys",
"cpuModel": "0",
"cpuMaxFrequencyHertz": 2000,
"totalMemoryBytes": 2077544448
}
}
}
<<XHARNESS_RESULT_END>>
info: Attempting to remove apk 'com.microsoft.maui.controls.devicetests'..
info: Successfully uninstalled com.microsoft.maui.controls.devicetests
XHarness exit code: 0
Passed: 65
Failed: 0
Skipped: 0
Total: 65
Tests completed successfully
🔴 Without fix — 🖥️ Issue38926: FAIL ✅ · 986s
Error-relevant lines (filtered from the build log):
at OpenQA.Selenium.WebDriver.UnpackAndThrowOnError(Response errorResponse, String commandToExecute)
at OpenQA.Selenium.WebDriver.ExecuteAsync(String driverCommandToExecute, Dictionary`2 parameters)
at OpenQA.Selenium.WebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
at OpenQA.Selenium.Appium.AppiumDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
at OpenQA.Selenium.WebDriver.FindElements(String mechanism, String value)
at OpenQA.Selenium.Appium.AppiumDriver.FindElements(String selector, String value)
at OpenQA.Selenium.Appium.MobileBy.FindElements(ISearchContext context)
at OpenQA.Selenium.WebDriver.FindElements(By by)
at OpenQA.Selenium.Appium.AppiumDriver.FindElements(By by)
at UITest.Appium.AppiumQuery.FindElements(AppiumApp appiumApp) in /_/src/TestUtils/src/UITest.Appium/AppiumQuery.cs:line 125
at UITest.Appium.AppiumQueryable.ById(String id) in /_/src/TestUtils/src/UITest.Appium/AppiumQueryable.cs:line 16
at UITest.Appium.AppiumAndroidQueryable.ById(String id) in /_/src/TestUtils/src/UITest.Appium/AppiumAndroidQueryable.cs:line 17
at UITest.Appium.AppiumApp.FindElements(String id) in /_/src/TestUtils/src/UITest.Appium/AppiumApp.cs:line 101
at UITest.Appium.HelperExtensions.WaitForTextToBePresentInElement(IApp app, String automationId, String text, Nullable`1 timeout) in /_/src/TestUtils/src/UITest.Appium/HelperExtensions.cs:line 1094
at Microsoft.Maui.TestCases.Tests.Issues.Issue38926.ScrollToColdRegionOfLargeGroupedGridIsFast() in /_/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue38926.cs:line 29
at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)
at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)
🟢 With fix — 🖥️ Issue38926: PASS ✅ · 605s
(no coded error found; showing last 1200 chars)
0:00.13] Discovering: Controls.TestCases.Android.Tests
[xUnit.net 00:00:00.38] Discovered: Controls.TestCases.Android.Tests
NUnit Adapter 4.5.0.0: Test execution started
Running selected tests in /home/vsts/work/1/s/artifacts/bin/Controls.TestCases.Android.Tests/Debug/net10.0/Controls.TestCases.Android.Tests.dll
NUnit3TestExecutor discovered 2 of 2 NUnit test cases using Current Discovery mode, Non-Explicit run
>>>>> 10/01/2026 20:30:54 FixtureSetup for Issue38926(Android)
>>>>> 10/01/2026 20:30:56 ScrollToColdRegionOfLargeFlatGridIsFast Start
>>>>> 10/01/2026 20:31:06 ScrollToColdRegionOfLargeFlatGridIsFast Stop
Passed ScrollToColdRegionOfLargeFlatGridIsFast [9 s]
>>>>> 10/01/2026 20:31:06 ScrollToColdRegionOfLargeGroupedGridIsFast Start
>>>>> 10/01/2026 20:31:12 ScrollToColdRegionOfLargeGroupedGridIsFast Stop
Passed ScrollToColdRegionOfLargeGroupedGridIsFast [6 s]
NUnit Adapter 4.5.0.0: Test execution complete
Results File: /home/vsts/work/1/s/CustomAgentLogsTmp/UITests/TestResults/Issue38926.trx
Test Run Successful.
Total tests: 2
Passed: 2
Total time: 30.5280 Seconds
>>> TRX_RESULT_FILE: /home/vsts/work/1/s/CustomAgentLogsTmp/UITests/TestResults/Issue38926.trx
⚠️ Failure Details
⚠️ CollectionViewTests (GridSpanLookupMatchesGreedySpanAssignment, GridSpanLookupTracksGroupedSourceChanges) without fix:XHarness did not produce the expected fresh result 'testResults-17b683125f6f438a804fd1ee9ae09cbd.xml' for requested class(es) 'Microsoft.Maui.DeviceTests.CollectionViewTests' (the target tests did not run).
📁 Fix files reverted (2 files)
src/Controls/src/Core/Handlers/Items/Android/Adapters/ItemsViewAdapter.cssrc/Controls/src/Core/Handlers/Items/Android/GridLayoutSpanSizeLookup.cs
📋 Pre-Flight — Context & Validation
PR #39063 Pre-Flight
Context
- Title:
[Android] CollectionView GridItemsLayout: resolve span index and row from the items source instead of walking every position - Base:
inflight/currentat5533dd7bb7522d91f1ea316a0ec8ddc4c3261af1 - PR head:
39cb50c9998d48b5c013b34fe1a9f2d6822c8701 - Local review commit:
d114571559f32fcd43db141a6befbe2c303cbbe0 - Platform: Android;
Handlers/Items/Androidis the sole Android CollectionView handler. - Issue: #38926. AndroidX
GridLayoutManagerfalls back to walking positions and invoking managedGetSpanSizethrough JNI when span-index/group caches are cold. Large-gridScrollTotherefore blocks the UI thread for seconds.
Existing PR Approach
The PR overrides GetSpanIndex and GetSpanGroupIndex in GridLayoutSpanSizeLookup. It exposes the adapter's IItemsViewSource through a new internal IItemsViewAdapter, lazily builds a block table for full-span items and regular runs, binary-searches that table, and invalidates it through AdapterDataObserver notifications or span-count changes.
This mechanism must not be repeated by an alternative candidate: no equivalent source-derived lazy block table plus binary search and observer invalidation under different names.
Changed Files
Production files, and the complete try-fix modification allow-list:
src/Controls/src/Core/Handlers/Items/Android/Adapters/ItemsViewAdapter.cssrc/Controls/src/Core/Handlers/Items/Android/GridLayoutSpanSizeLookup.cs
PR tests remain read-only during try-fix:
src/Controls/tests/DeviceTests/Elements/CollectionView/CollectionViewTests.Android.cssrc/Controls/tests/TestCases.HostApp/Issues/Issue38926.cssrc/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue38926.cs
Validation Boundary
Gate verification is already complete and must not be repeated. It established:
Issue38926fails without the production fix and passes with it.GridSpanLookupMatchesGreedySpanAssignmentandGridSpanLookupTracksGroupedSourceChangespass with the production fix.
Each candidate gets one implementation/test pass and at most one focused correction/retest. Run no full suite. The only permitted checks are:
- Primary performance/reproduction test:
pwsh .github/scripts/BuildAndRunHostApp.ps1 -Platform android -TestFilter "Issue38926" - Mandatory correctness/invalidation regression checks:
pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform android -TestFilter "Category=CollectionView"
The device filter runs the bounded CollectionView category because the runner filters device tests by category; the relevant methods are GridSpanLookupMatchesGreedySpanAssignment and GridSpanLookupTracksGroupedSourceChanges.
Repository and Safety Constraints
- Establish and restore the broken baseline only with
.github/scripts/EstablishBrokenBaseline.ps1. - After baseline establishment, modify only
RevertedFilesfrom.github/.baseline-state.json. - Preserve the unrelated pre-existing
.githubworktree changes. - Read and apply the Android, CollectionView Android, handler-detection, handler-pattern, performance-hotpath, public-API, device-test, and try-fix instructions.
- Perform the try-fix skill's expert self-review inline; do not launch a reviewer agent.
🔬 Code Review — Deep Analysis
Code Review — PR #39063
Independent Assessment
What this changes: The Android GridLayoutSpanSizeLookup now computes uncached span indices and span-group rows from a lazily rebuilt block table derived from the active items source, instead of inheriting AndroidX's position-by-position walk through GetSpanSize. The adapter exposes its source through an internal non-generic interface, and an AdapterDataObserver invalidates the block table after source notifications.
Inferred motivation: Avoid repeated managed/JNI callbacks proportional to the target adapter position when a GridItemsLayout jumps into an uncached region, while preserving the greedy row assignment used by GridLayoutManager.
Approach: Sound. Full-span headers and footers become one-item blocks, ordinary items become arithmetic runs, adjacent groups without separators are merged so rows may continue across group boundaries, and unsupported adapters retain the AndroidX fallback.
Findings
No actionable correctness, lifecycle, performance, API-surface, or test-quality findings. inline-findings.json is an empty JSON array.
The reviewer identified one optional coverage improvement: add a grouped-source Reset mutation case. Existing coverage already exercises the core layout matrix and item/group insertions, so this is not a merge blocker.
Blast Radius Assessment
- Runs for all instances: No. The behavior is restricted to Android CollectionView instances using
GridItemsLayout; unknown adapter types fall back to the base implementation. - Startup impact: None.
- Static/shared state: None. The block cache and observer are per span-lookup instance.
- Lifecycle: Adapter swaps detach the observer before registering the replacement, and disposing the lookup stops observation.
- Empty/default behavior:
EmptyViewAdapterremains a dedicated all-full-span path; invalid positions and invalid span counts fall back to AndroidX behavior.
Failure-Mode Probing
- Flat and grouped sources with collection, group, header, and footer boundaries: block arithmetic matches the greedy
GetSpanSizeassignment in the submitted device-test matrix. - Empty groups and adjacent groups without separators: empty runs are omitted and adjacent ordinary runs are merged, preserving rows that straddle group boundaries.
- Item and group insertion after the cache has been built: adapter notifications mark the table dirty and the next lookup rebuilds from the live source.
- Adapter replacement and disposal: observation is transferred or removed, avoiding stale callbacks and retained adapters.
- Unsupported adapters: the optimized path declines the lookup and delegates to the existing base implementation.
External Output Contract
Not applicable.
Trim/AOT Evidence Chain
Not applicable.
Gate Status
The trusted gate supplied to this review passed: regression tests fail without the fix and pass with it. The gate was not re-run.
Verdict: LGTM
Confidence: medium
Summary: The submitted implementation is internally consistent with Android GridLayoutManager semantics, scopes its cache correctly, and has targeted correctness and performance coverage. Confidence is capped at medium because this is platform-specific CollectionView handler plumbing.
🛠️ Try-Fix — Analysis & Comparison
PR #39063 Alternative Fix Candidates
Pre-flight context: ../pre-flight/content.md
Candidate 1 — Span-Metadata Fast Path
Model: gpt-5.3-codex
Proposed approach: Eagerly materialize per-position span-index and span-group arrays for O(1) lookup after each invalidation epoch, instead of building and binary-searching source-derived blocks.
Result: Blocked before implementation
The approach would have replaced segmented block construction and lookup with final span metadata indexed directly by adapter position. It explicitly avoided the PR's IItemsViewSource exposure, lazy source-derived block table, binary search, and observer-driven invalidation protocol.
EstablishBrokenBaseline.ps1 rejected the pre-existing dirty tracked worktree. No baseline state was created and no production file changed.
Validation:
BuildAndRunHostApp.ps1 -Platform android -TestFilter "Issue38926"— not run because baseline setup failed.Run-DeviceTests.ps1 -Project Controls -Platform android -TestFilter "Category=CollectionView"— not run because baseline setup failed.
Failure analysis: The baseline script requires a clean tracked worktree, while the unrelated existing .github changes had to be preserved. Inline self-review recorded zero findings because there was no candidate diff. The required restore command completed with No baseline state found / Restored=False, the expected no-state path.
Full narrative: ../try-fix-1/content.md
Artifacts: attempt-1/
Candidate 2 — Live Arithmetic Span Resolution
Model: gpt-5.6-sol
Approach: Add an internal geometry resolver to ItemsViewAdapter. Flat sources compute span index and group in O(1). Grouped sources walk current group boundaries rather than item positions while carrying partial-row occupancy across adjacent groups; full-span headers and footers close partial rows. GridLayoutSpanSizeLookup delegates cold queries to this live resolver and handles EmptyViewAdapter directly.
Prior mechanisms avoided: Candidate 2 uses neither candidate 1's per-position arrays nor the PR's source exposure, materialized block table, binary search, adapter observer, cache, or invalidation state. Each query reads current source counts, so mutations are reflected without rebuilding metadata. It trades the PR's cached O(log blocks) grouped query for uncached O(groups), while eliminating AndroidX's original O(position) JNI callback chain. Flat queries remain O(1).
Files changed in the captured candidate diff:
src/Controls/src/Core/Handlers/Items/Android/Adapters/ItemsViewAdapter.cssrc/Controls/src/Core/Handlers/Items/Android/GridLayoutSpanSizeLookup.cs
Result: Fail — validation did not reach candidate compilation
Validation:
BuildAndRunHostApp.ps1 -Platform android -TestFilter "Issue38926"— exit 1. It foundemulator-5554, but all internal build/deploy attempts stopped atMaui.InTree.targets(34,5)because required MSBuild tasks were missing or out of date.Run-DeviceTests.ps1 -Project Controls -Platform android -TestFilter "Category=CollectionView"— exit 1 at the same MSBuild-task prerequisite.
Both commands ran in the one permitted test pass. No focused correction or retest was performed because the candidate never reached compilation and a manual prerequisite build was outside the allowed command set. Consequently, this diff has no empirical correctness or performance result.
Self-review: Zero findings after applying the overarching, logic/correctness, regression, complexity, performance-hotpath, memory/lifecycle, CollectionView Android, and Android platform checks.
Restore: EstablishBrokenBaseline.ps1 -Restore returned Restored True; both allow-listed files returned to HEAD, baseline state was removed, and the isolated worktree was clean.
Full narrative: ../try-fix-2/content.md
Captured diff and logs: attempt-2/fix.diff, attempt-2/test-output.log
Aggregate Outcome
Two candidates total were attempted. Candidate 1 was blocked before producing a diff; candidate 2 produced a distinct captured diff but could not be compiled or executed under the bounded validation contract. Neither candidate is a validated passing alternative.
🏁 Report — Final Recommendation
✅ Final Recommendation: APPROVE
Winner: pr
The submitted PR is the strongest candidate because it is the only minimal, complete implementation backed by both the trusted Gate and a clean expert review. The Gate established that the regression tests fail without the production fix and pass with it. The expert reviewer found no actionable correctness, lifecycle, performance, API, or test-quality issue, produced [] in inline-findings.json, and rated the Android CollectionView implementation LGTM with medium confidence.
Comparative Ranking
| Rank | Candidate | Implementation | Regression evidence | Review assessment | Disposition |
|---|---|---|---|---|---|
| 1 | pr |
Lazily builds source-derived full-span/run blocks, binary-searches them, and invalidates on adapter notifications or span changes. | PASS: trusted Gate proves fail-without-fix/pass-with-fix for the reproduction and targeted correctness coverage. | Expert LGTM; no blocking errors, warnings, discussion items, or inline findings. |
Winner. Correct, performant, focused, and already adequately tested. |
| 2 | pr-plus-reviewer |
Same production fix, plus one grouped-source Reset invalidation assertion. |
PASS: Issue38926 host-app validation and Android Category=CollectionView device validation both exited 0 from the mandated sandbox. |
Useful optional hardening; no production correction. | Valid runner-up. The extra test is not needed to establish correctness and does not outweigh the raw PR's smaller submitted scope. |
| 3 | try-fix-2 |
Computes flat geometry in O(1) and grouped geometry by walking live group boundaries in O(groups), without block caching or observers. | UNVALIDATED / command failure: both required commands exited before candidate compilation because that attempt lacked current MAUI build tasks. | Self-review reported no findings, but neither correctness nor performance was executed. It also has weaker grouped-query complexity than the PR. | Below both passing candidates. |
| 4 | try-fix-1 |
Proposed eager per-position span metadata arrays for O(1) lookup. | BLOCKED: baseline establishment rejected the dirty worktree; no implementation, diff, compilation, or tests exist. | No code was available to review. | Not a viable candidate. |
Why pr Wins
The raw PR removes AndroidX's O(position) managed/JNI walk while retaining exact greedy grid semantics for flat, grouped, header/footer, empty-group, and adjacent-group layouts. Its observer lifecycle is scoped per lookup, adapter swaps detach the prior observer, disposal unregisters it, unsupported adapters preserve the base fallback, and no public API is added.
pr-plus-reviewer demonstrates that a Reset-specific assertion can be added safely, but the production observer handles OnChanged identically to its already-covered insertion invalidations and the expert reviewer explicitly considered the extra case non-blocking. Selecting that optional test-only delta would turn a clean approval into a request for unnecessary changes. The two STEP 5a alternatives rank lower because neither has passing candidate validation: try-fix-2 never compiled or ran, and try-fix-1 never produced code.
Residual Risk
The change is Android-specific CollectionView handler plumbing, so confidence remains medium rather than high despite strong targeted evidence. No unresolved failure mode, blocking review finding, or gate failure remains.
📱 UI Tests — CollectionView
Detected UI test categories: CollectionView
[!WARNING]
No UI test results were produced for the detected categories. The PR build itself was
fine — the deep UI stage was skipped or interrupted on infrastructure (the
merge-for-testing step, emulator/simulator boot, or an Appium hang), not by this PR's code.
This is usually transient; the review re-runs on new commits (a maintainer can also re-run it).
🧭 Next Steps — review latest findings
No alternative fix was selected for this run. Review the session findings and CI results before merging.
This comment has been minimized.
This comment has been minimized.
|
The This is an automation failure, not a verdict on the PR tests. Maintainers can retry |
…from the items source instead of walking every position (#39063) > [!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! ### Issue Details After #38969, `GridLayoutManager` still resolves the span index / row of a position it has not cached yet by calling `getSpanSize()` for every position from the nearest cached key to the target — a JNI round-trip each. `ScrollTo` into a cold region of a large grid, or laying out rows while scrolling back up past the cached keys, is O(n) per lookup: 200 000 grouped items, `ScrollTo` last group blocks the UI thread for 12.8 s (6.9 s flat). ### Root Cause `GridLayoutSpanSizeLookup` only overrides `GetSpanSize`; `GetSpanIndex`/`GetSpanGroupIndex` fall back to AndroidX's walk. ### Description of Change Override `GetSpanIndex`/`GetSpanGroupIndex`. The items source already knows where full-span items sit, so the layout is a short list of blocks (a full-span item, or a run of regular items that starts on a fresh row) and the answer is arithmetic plus a binary search. The table is rebuilt lazily after `AdapterDataObserver` notifications (the same ones `GridLayoutManager` uses to drop its own span caches) or a span-count change; adjacent groups without a separating header/footer are merged into one run because they share rows. Unknown adapters fall back to the base implementation. `ItemsViewAdapter` gains an internal `IItemsViewAdapter` view of its source; no public API change.⚠️ Since this is a follow-up PR of #38969, which is only merged to inflight/current, the source branch of this PR is based on inflight/current also. Tests and measurements for baseline are based on inflight/current with the first PR in place to demonstrate the diff on top of that improvement. If needed I can rebase onto main. ### Measurements (HONOR PGT‑N19, Release, 200 000 items, Span=4, UI thread blocked) Step | Grouped before | Grouped after | Flat before | Flat after -- | -- | -- | -- | -- Load | 127 ms | 110 ms | 83 ms | 110 ms ScrollTo end | 13 412 ms | 92 ms | 7 081 ms | 146 ms ScrollTo middle | 2 523 ms | 123 ms | 1 787 ms | 120 ms ScrollTo start | 112 ms | 127 ms | 203 ms | 141 ms | Before | After | |---|---| | <video src="https://github.com/user-attachments/assets/d8206648-bf64-4207-8b4e-dd195d217f8a" width="300"> | <video src="https://github.com/user-attachments/assets/ed798125-b2cc-4092-b1d2-6ad17c86d25b" width="300"> | ### Tests - Device: `GridSpanLookupMatchesGreedySpanAssignment` — 128 combinations checked position-by-position against the greedy assignment `GridLayoutManager` derives from `GetSpanSize`; `GridSpanLookupTracksGroupedSourceChanges` — item and group insertions. - UI: `Issue38926` — 200 000 items grouped and flat; `ScrollTo` end / middle / start must each finish within 5 s (before: 1.8–12.8 s; after: ~100 ms). ### Issues Fixed Fixes #38926
…from the items source instead of walking every position (#39063) > [!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! ### Issue Details After #38969, `GridLayoutManager` still resolves the span index / row of a position it has not cached yet by calling `getSpanSize()` for every position from the nearest cached key to the target — a JNI round-trip each. `ScrollTo` into a cold region of a large grid, or laying out rows while scrolling back up past the cached keys, is O(n) per lookup: 200 000 grouped items, `ScrollTo` last group blocks the UI thread for 12.8 s (6.9 s flat). ### Root Cause `GridLayoutSpanSizeLookup` only overrides `GetSpanSize`; `GetSpanIndex`/`GetSpanGroupIndex` fall back to AndroidX's walk. ### Description of Change Override `GetSpanIndex`/`GetSpanGroupIndex`. The items source already knows where full-span items sit, so the layout is a short list of blocks (a full-span item, or a run of regular items that starts on a fresh row) and the answer is arithmetic plus a binary search. The table is rebuilt lazily after `AdapterDataObserver` notifications (the same ones `GridLayoutManager` uses to drop its own span caches) or a span-count change; adjacent groups without a separating header/footer are merged into one run because they share rows. Unknown adapters fall back to the base implementation. `ItemsViewAdapter` gains an internal `IItemsViewAdapter` view of its source; no public API change.⚠️ Since this is a follow-up PR of #38969, which is only merged to inflight/current, the source branch of this PR is based on inflight/current also. Tests and measurements for baseline are based on inflight/current with the first PR in place to demonstrate the diff on top of that improvement. If needed I can rebase onto main. ### Measurements (HONOR PGT‑N19, Release, 200 000 items, Span=4, UI thread blocked) Step | Grouped before | Grouped after | Flat before | Flat after -- | -- | -- | -- | -- Load | 127 ms | 110 ms | 83 ms | 110 ms ScrollTo end | 13 412 ms | 92 ms | 7 081 ms | 146 ms ScrollTo middle | 2 523 ms | 123 ms | 1 787 ms | 120 ms ScrollTo start | 112 ms | 127 ms | 203 ms | 141 ms | Before | After | |---|---| | <video src="https://github.com/user-attachments/assets/d8206648-bf64-4207-8b4e-dd195d217f8a" width="300"> | <video src="https://github.com/user-attachments/assets/ed798125-b2cc-4092-b1d2-6ad17c86d25b" width="300"> | ### Tests - Device: `GridSpanLookupMatchesGreedySpanAssignment` — 128 combinations checked position-by-position against the greedy assignment `GridLayoutManager` derives from `GetSpanSize`; `GridSpanLookupTracksGroupedSourceChanges` — item and group insertions. - UI: `Issue38926` — 200 000 items grouped and flat; `ScrollTo` end / middle / start must each finish within 5 s (before: 1.8–12.8 s; after: ~100 ms). ### Issues Fixed Fixes #38926
#38925 (#39335) <!-- 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! <!-- !!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING MAIN. !!!!!!! --> ### Description of Change <!-- Enter description of the fix in this section --> **Regression-only backport to `inflight/candidate`, explicitly requested for servicing. This is not a backport of the entire mixed source PR.** Candidate baseline: `3d96e23006ea80f58ff2946017eb4593f63a46c6`. #38925 reports the Android `CollectionView` / `GridItemsLayout` regression from **10.0.90 to 10.0.100**, introduced by #35782. `SpacingItemDecoration.GetItemOffsets` calls the uncached `GetSpanGroupIndex(itemCount - 1)` for every child, scanning the adapter through JNI on repeated layout/scroll passes. Large sources stall ItemsSource/layout and can ANR during flings. Bring over only `SpacingItemDecoration.cs` from #38969 (production file is identical to the rebased source): return immediately for zero spacing; identify the first/last span rows by inspecting only the items that can share those rows, using assigned child span indices with the original lookup fallback. Keep existing adapter-position/count bounds, linear-layout behavior, outer-edge spacing, and full-span header/footer handling. Candidate's other Android fixes remain untouched. Source provenance: - Original GitHub merge SHA: [`c6b0c73ccbc7eebd5c9a683e5b803d786cf37cf7`](c6b0c73). - Current rebased equivalent: [`ad38e20f14fa841bd82b3b569256e84c45e48d4f`](ad38e20). **Deliberately excluded:** #38926's longstanding `ObservableGroupedSource.GetGroupAndIndex` optimization and its focused device test; the source page/test's far-group `ScrollTo` actions and timing expectations; general optimization PR #39063. These are not part of the #38925 servicing regression. No version pins, dependencies, CI configuration, or generated manifests/localization files changed. Adapt the directly relevant Issue38925 HostApp and Android-only CollectionView shard-6 test to load **50 groups × 200 items**, check that the first item is rendered, and assert the app-reported ItemsSource/dispatcher elapsed time is **below 15,000 ms**. The in-app time assertion avoids accepting a slow load merely because Appium's tap returns after the stall. No ScrollTo requirement is retained. **Validation (compilation and non-UI checks only):** used the installed SDK explicitly, without changing `global.json`. Restores were performed only after missing assets/build-task dependency failures. Preliminary missing-assets and missing-task failures were resolved; an initial target-framework mismatch was corrected to Candidate's `net10.0-android36.0` graph. | Exact command | Result | | --- | --- | | `dotnet /usr/local/share/dotnet/sdk/10.0.100/dotnet.dll restore src/Controls/src/Core/Controls.Core.csproj -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -v:q` | Passed | | `dotnet /usr/local/share/dotnet/sdk/10.0.100/dotnet.dll build src/Controls/src/Core/Controls.Core.csproj -f net10.0-android36.0 --no-restore -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -v:q` | Passed; 0 errors, 3 existing Gradle Java-8 source/target deprecation warnings | | `dotnet /usr/local/share/dotnet/sdk/10.0.100/dotnet.dll build Microsoft.Maui.BuildTasks.slnf -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -v:q` | Passed; 0 warnings/errors | | `dotnet /usr/local/share/dotnet/sdk/10.0.100/dotnet.dll restore src/Controls/tests/TestCases.HostApp/Controls.TestCases.HostApp.csproj -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -v:q` | Passed | | `dotnet /usr/local/share/dotnet/sdk/10.0.100/dotnet.dll build src/Controls/tests/TestCases.HostApp/Controls.TestCases.HostApp.csproj -f net10.0-android --no-restore -t:Compile -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -v:q` | Passed; 0 warnings/errors; Compile target only, no app launch | | `dotnet /usr/local/share/dotnet/sdk/10.0.100/dotnet.dll restore src/Controls/tests/TestCases.Android.Tests/Controls.TestCases.Android.Tests.csproj -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -v:q` | Passed | | `dotnet /usr/local/share/dotnet/sdk/10.0.100/dotnet.dll build src/Controls/tests/TestCases.Android.Tests/Controls.TestCases.Android.Tests.csproj --no-restore -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -v:q` | Passed after correcting a nullable timing-text diagnostic; final build 0 warnings/errors; test assembly compilation only | | `dotnet /usr/local/share/dotnet/sdk/10.0.100/dotnet.dll format whitespace . --folder --include src/Controls/src/Core/Handlers/Items/Android/SpacingItemDecoration.cs src/Controls/tests/TestCases.HostApp/Issues/Issue38925.cs src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue38925.cs --verify-no-changes --verbosity quiet` | Passed; only touched files formatted | | `git diff --check` and `git diff --cached --check` | Passed | | `git diff --quiet ad38e20 -- src/Controls/src/Core/Handlers/Items/Android/SpacingItemDecoration.cs` | Passed; exact production-source identity | Additionally, an uncommitted dependency-free managed harness compiled the **exact production source** against minimal Android/RecyclerView stubs. **809,530 offset comparisons passed**, covering empty/single/mixed/full-span rows, both orientations, assigned/fallback span indices, linear layouts, invalid positions, zero-spacing early return, and bounded lookups for a 10,050-position grouped grid. The same harness with unmodified Candidate source failed the bounded-lookup assertion as expected. This checks managed offset logic and lookup counts, **not native Android/JNI performance or rendering**. **Not run:** the added UI test, existing Issue35700/Issue38321 runtime coverage, native device tests, fling/ANR measurements, or screenshot comparison. No XCTest, Appium execution, simulator/emulator, GUI, or browser automation was used, per the user's active-work restriction. No native runtime proof is claimed; Android CI/artifact validation is still 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. --> Fixes #38925 <!-- Are you targeting main? All PRs should target the main branch unless otherwise noted. --> Targeting `inflight/candidate` by explicit servicing-backport request, not `main`. #38926 is intentionally not claimed as fixed. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…from the items source instead of walking every position (#39063) > [!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! ### Issue Details After #38969, `GridLayoutManager` still resolves the span index / row of a position it has not cached yet by calling `getSpanSize()` for every position from the nearest cached key to the target — a JNI round-trip each. `ScrollTo` into a cold region of a large grid, or laying out rows while scrolling back up past the cached keys, is O(n) per lookup: 200 000 grouped items, `ScrollTo` last group blocks the UI thread for 12.8 s (6.9 s flat). ### Root Cause `GridLayoutSpanSizeLookup` only overrides `GetSpanSize`; `GetSpanIndex`/`GetSpanGroupIndex` fall back to AndroidX's walk. ### Description of Change Override `GetSpanIndex`/`GetSpanGroupIndex`. The items source already knows where full-span items sit, so the layout is a short list of blocks (a full-span item, or a run of regular items that starts on a fresh row) and the answer is arithmetic plus a binary search. The table is rebuilt lazily after `AdapterDataObserver` notifications (the same ones `GridLayoutManager` uses to drop its own span caches) or a span-count change; adjacent groups without a separating header/footer are merged into one run because they share rows. Unknown adapters fall back to the base implementation. `ItemsViewAdapter` gains an internal `IItemsViewAdapter` view of its source; no public API change.⚠️ Since this is a follow-up PR of #38969, which is only merged to inflight/current, the source branch of this PR is based on inflight/current also. Tests and measurements for baseline are based on inflight/current with the first PR in place to demonstrate the diff on top of that improvement. If needed I can rebase onto main. ### Measurements (HONOR PGT‑N19, Release, 200 000 items, Span=4, UI thread blocked) Step | Grouped before | Grouped after | Flat before | Flat after -- | -- | -- | -- | -- Load | 127 ms | 110 ms | 83 ms | 110 ms ScrollTo end | 13 412 ms | 92 ms | 7 081 ms | 146 ms ScrollTo middle | 2 523 ms | 123 ms | 1 787 ms | 120 ms ScrollTo start | 112 ms | 127 ms | 203 ms | 141 ms | Before | After | |---|---| | <video src="https://github.com/user-attachments/assets/d8206648-bf64-4207-8b4e-dd195d217f8a" width="300"> | <video src="https://github.com/user-attachments/assets/ed798125-b2cc-4092-b1d2-6ad17c86d25b" width="300"> | ### Tests - Device: `GridSpanLookupMatchesGreedySpanAssignment` — 128 combinations checked position-by-position against the greedy assignment `GridLayoutManager` derives from `GetSpanSize`; `GridSpanLookupTracksGroupedSourceChanges` — item and group insertions. - UI: `Issue38926` — 200 000 items grouped and flat; `ScrollTo` end / middle / start must each finish within 5 s (before: 1.8–12.8 s; after: ~100 ms). ### Issues Fixed Fixes #38926
#38925 (#39335) <!-- 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! <!-- !!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING MAIN. !!!!!!! --> ### Description of Change <!-- Enter description of the fix in this section --> **Regression-only backport to `inflight/candidate`, explicitly requested for servicing. This is not a backport of the entire mixed source PR.** Candidate baseline: `3d96e23006ea80f58ff2946017eb4593f63a46c6`. #38925 reports the Android `CollectionView` / `GridItemsLayout` regression from **10.0.90 to 10.0.100**, introduced by #35782. `SpacingItemDecoration.GetItemOffsets` calls the uncached `GetSpanGroupIndex(itemCount - 1)` for every child, scanning the adapter through JNI on repeated layout/scroll passes. Large sources stall ItemsSource/layout and can ANR during flings. Bring over only `SpacingItemDecoration.cs` from #38969 (production file is identical to the rebased source): return immediately for zero spacing; identify the first/last span rows by inspecting only the items that can share those rows, using assigned child span indices with the original lookup fallback. Keep existing adapter-position/count bounds, linear-layout behavior, outer-edge spacing, and full-span header/footer handling. Candidate's other Android fixes remain untouched. Source provenance: - Original GitHub merge SHA: [`c6b0c73ccbc7eebd5c9a683e5b803d786cf37cf7`](c6b0c73). - Current rebased equivalent: [`ad38e20f14fa841bd82b3b569256e84c45e48d4f`](ad38e20). **Deliberately excluded:** #38926's longstanding `ObservableGroupedSource.GetGroupAndIndex` optimization and its focused device test; the source page/test's far-group `ScrollTo` actions and timing expectations; general optimization PR #39063. These are not part of the #38925 servicing regression. No version pins, dependencies, CI configuration, or generated manifests/localization files changed. Adapt the directly relevant Issue38925 HostApp and Android-only CollectionView shard-6 test to load **50 groups × 200 items**, check that the first item is rendered, and assert the app-reported ItemsSource/dispatcher elapsed time is **below 15,000 ms**. The in-app time assertion avoids accepting a slow load merely because Appium's tap returns after the stall. No ScrollTo requirement is retained. **Validation (compilation and non-UI checks only):** used the installed SDK explicitly, without changing `global.json`. Restores were performed only after missing assets/build-task dependency failures. Preliminary missing-assets and missing-task failures were resolved; an initial target-framework mismatch was corrected to Candidate's `net10.0-android36.0` graph. | Exact command | Result | | --- | --- | | `dotnet /usr/local/share/dotnet/sdk/10.0.100/dotnet.dll restore src/Controls/src/Core/Controls.Core.csproj -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -v:q` | Passed | | `dotnet /usr/local/share/dotnet/sdk/10.0.100/dotnet.dll build src/Controls/src/Core/Controls.Core.csproj -f net10.0-android36.0 --no-restore -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -v:q` | Passed; 0 errors, 3 existing Gradle Java-8 source/target deprecation warnings | | `dotnet /usr/local/share/dotnet/sdk/10.0.100/dotnet.dll build Microsoft.Maui.BuildTasks.slnf -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -v:q` | Passed; 0 warnings/errors | | `dotnet /usr/local/share/dotnet/sdk/10.0.100/dotnet.dll restore src/Controls/tests/TestCases.HostApp/Controls.TestCases.HostApp.csproj -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -v:q` | Passed | | `dotnet /usr/local/share/dotnet/sdk/10.0.100/dotnet.dll build src/Controls/tests/TestCases.HostApp/Controls.TestCases.HostApp.csproj -f net10.0-android --no-restore -t:Compile -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -v:q` | Passed; 0 warnings/errors; Compile target only, no app launch | | `dotnet /usr/local/share/dotnet/sdk/10.0.100/dotnet.dll restore src/Controls/tests/TestCases.Android.Tests/Controls.TestCases.Android.Tests.csproj -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -v:q` | Passed | | `dotnet /usr/local/share/dotnet/sdk/10.0.100/dotnet.dll build src/Controls/tests/TestCases.Android.Tests/Controls.TestCases.Android.Tests.csproj --no-restore -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -v:q` | Passed after correcting a nullable timing-text diagnostic; final build 0 warnings/errors; test assembly compilation only | | `dotnet /usr/local/share/dotnet/sdk/10.0.100/dotnet.dll format whitespace . --folder --include src/Controls/src/Core/Handlers/Items/Android/SpacingItemDecoration.cs src/Controls/tests/TestCases.HostApp/Issues/Issue38925.cs src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue38925.cs --verify-no-changes --verbosity quiet` | Passed; only touched files formatted | | `git diff --check` and `git diff --cached --check` | Passed | | `git diff --quiet ad38e20 -- src/Controls/src/Core/Handlers/Items/Android/SpacingItemDecoration.cs` | Passed; exact production-source identity | Additionally, an uncommitted dependency-free managed harness compiled the **exact production source** against minimal Android/RecyclerView stubs. **809,530 offset comparisons passed**, covering empty/single/mixed/full-span rows, both orientations, assigned/fallback span indices, linear layouts, invalid positions, zero-spacing early return, and bounded lookups for a 10,050-position grouped grid. The same harness with unmodified Candidate source failed the bounded-lookup assertion as expected. This checks managed offset logic and lookup counts, **not native Android/JNI performance or rendering**. **Not run:** the added UI test, existing Issue35700/Issue38321 runtime coverage, native device tests, fling/ANR measurements, or screenshot comparison. No XCTest, Appium execution, simulator/emulator, GUI, or browser automation was used, per the user's active-work restriction. No native runtime proof is claimed; Android CI/artifact validation is still 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. --> Fixes #38925 <!-- Are you targeting main? All PRs should target the main branch unless otherwise noted. --> Targeting `inflight/candidate` by explicit servicing-backport request, not `main`. #38926 is intentionally not claimed as fixed. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…from the items source instead of walking every position (#39063) > [!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! ### Issue Details After #38969, `GridLayoutManager` still resolves the span index / row of a position it has not cached yet by calling `getSpanSize()` for every position from the nearest cached key to the target — a JNI round-trip each. `ScrollTo` into a cold region of a large grid, or laying out rows while scrolling back up past the cached keys, is O(n) per lookup: 200 000 grouped items, `ScrollTo` last group blocks the UI thread for 12.8 s (6.9 s flat). ### Root Cause `GridLayoutSpanSizeLookup` only overrides `GetSpanSize`; `GetSpanIndex`/`GetSpanGroupIndex` fall back to AndroidX's walk. ### Description of Change Override `GetSpanIndex`/`GetSpanGroupIndex`. The items source already knows where full-span items sit, so the layout is a short list of blocks (a full-span item, or a run of regular items that starts on a fresh row) and the answer is arithmetic plus a binary search. The table is rebuilt lazily after `AdapterDataObserver` notifications (the same ones `GridLayoutManager` uses to drop its own span caches) or a span-count change; adjacent groups without a separating header/footer are merged into one run because they share rows. Unknown adapters fall back to the base implementation. `ItemsViewAdapter` gains an internal `IItemsViewAdapter` view of its source; no public API change.⚠️ Since this is a follow-up PR of #38969, which is only merged to inflight/current, the source branch of this PR is based on inflight/current also. Tests and measurements for baseline are based on inflight/current with the first PR in place to demonstrate the diff on top of that improvement. If needed I can rebase onto main. ### Measurements (HONOR PGT‑N19, Release, 200 000 items, Span=4, UI thread blocked) Step | Grouped before | Grouped after | Flat before | Flat after -- | -- | -- | -- | -- Load | 127 ms | 110 ms | 83 ms | 110 ms ScrollTo end | 13 412 ms | 92 ms | 7 081 ms | 146 ms ScrollTo middle | 2 523 ms | 123 ms | 1 787 ms | 120 ms ScrollTo start | 112 ms | 127 ms | 203 ms | 141 ms | Before | After | |---|---| | <video src="https://github.com/user-attachments/assets/d8206648-bf64-4207-8b4e-dd195d217f8a" width="300"> | <video src="https://github.com/user-attachments/assets/ed798125-b2cc-4092-b1d2-6ad17c86d25b" width="300"> | ### Tests - Device: `GridSpanLookupMatchesGreedySpanAssignment` — 128 combinations checked position-by-position against the greedy assignment `GridLayoutManager` derives from `GetSpanSize`; `GridSpanLookupTracksGroupedSourceChanges` — item and group insertions. - UI: `Issue38926` — 200 000 items grouped and flat; `ScrollTo` end / middle / start must each finish within 5 s (before: 1.8–12.8 s; after: ~100 ms). ### Issues Fixed Fixes #38926
#38925 (#39335) <!-- 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! <!-- !!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING MAIN. !!!!!!! --> ### Description of Change <!-- Enter description of the fix in this section --> **Regression-only backport to `inflight/candidate`, explicitly requested for servicing. This is not a backport of the entire mixed source PR.** Candidate baseline: `3d96e23006ea80f58ff2946017eb4593f63a46c6`. #38925 reports the Android `CollectionView` / `GridItemsLayout` regression from **10.0.90 to 10.0.100**, introduced by #35782. `SpacingItemDecoration.GetItemOffsets` calls the uncached `GetSpanGroupIndex(itemCount - 1)` for every child, scanning the adapter through JNI on repeated layout/scroll passes. Large sources stall ItemsSource/layout and can ANR during flings. Bring over only `SpacingItemDecoration.cs` from #38969 (production file is identical to the rebased source): return immediately for zero spacing; identify the first/last span rows by inspecting only the items that can share those rows, using assigned child span indices with the original lookup fallback. Keep existing adapter-position/count bounds, linear-layout behavior, outer-edge spacing, and full-span header/footer handling. Candidate's other Android fixes remain untouched. Source provenance: - Original GitHub merge SHA: [`c6b0c73ccbc7eebd5c9a683e5b803d786cf37cf7`](c6b0c73). - Current rebased equivalent: [`ad38e20f14fa841bd82b3b569256e84c45e48d4f`](ad38e20). **Deliberately excluded:** #38926's longstanding `ObservableGroupedSource.GetGroupAndIndex` optimization and its focused device test; the source page/test's far-group `ScrollTo` actions and timing expectations; general optimization PR #39063. These are not part of the #38925 servicing regression. No version pins, dependencies, CI configuration, or generated manifests/localization files changed. Adapt the directly relevant Issue38925 HostApp and Android-only CollectionView shard-6 test to load **50 groups × 200 items**, check that the first item is rendered, and assert the app-reported ItemsSource/dispatcher elapsed time is **below 15,000 ms**. The in-app time assertion avoids accepting a slow load merely because Appium's tap returns after the stall. No ScrollTo requirement is retained. **Validation (compilation and non-UI checks only):** used the installed SDK explicitly, without changing `global.json`. Restores were performed only after missing assets/build-task dependency failures. Preliminary missing-assets and missing-task failures were resolved; an initial target-framework mismatch was corrected to Candidate's `net10.0-android36.0` graph. | Exact command | Result | | --- | --- | | `dotnet /usr/local/share/dotnet/sdk/10.0.100/dotnet.dll restore src/Controls/src/Core/Controls.Core.csproj -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -v:q` | Passed | | `dotnet /usr/local/share/dotnet/sdk/10.0.100/dotnet.dll build src/Controls/src/Core/Controls.Core.csproj -f net10.0-android36.0 --no-restore -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -v:q` | Passed; 0 errors, 3 existing Gradle Java-8 source/target deprecation warnings | | `dotnet /usr/local/share/dotnet/sdk/10.0.100/dotnet.dll build Microsoft.Maui.BuildTasks.slnf -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -v:q` | Passed; 0 warnings/errors | | `dotnet /usr/local/share/dotnet/sdk/10.0.100/dotnet.dll restore src/Controls/tests/TestCases.HostApp/Controls.TestCases.HostApp.csproj -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -v:q` | Passed | | `dotnet /usr/local/share/dotnet/sdk/10.0.100/dotnet.dll build src/Controls/tests/TestCases.HostApp/Controls.TestCases.HostApp.csproj -f net10.0-android --no-restore -t:Compile -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -v:q` | Passed; 0 warnings/errors; Compile target only, no app launch | | `dotnet /usr/local/share/dotnet/sdk/10.0.100/dotnet.dll restore src/Controls/tests/TestCases.Android.Tests/Controls.TestCases.Android.Tests.csproj -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -v:q` | Passed | | `dotnet /usr/local/share/dotnet/sdk/10.0.100/dotnet.dll build src/Controls/tests/TestCases.Android.Tests/Controls.TestCases.Android.Tests.csproj --no-restore -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -v:q` | Passed after correcting a nullable timing-text diagnostic; final build 0 warnings/errors; test assembly compilation only | | `dotnet /usr/local/share/dotnet/sdk/10.0.100/dotnet.dll format whitespace . --folder --include src/Controls/src/Core/Handlers/Items/Android/SpacingItemDecoration.cs src/Controls/tests/TestCases.HostApp/Issues/Issue38925.cs src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue38925.cs --verify-no-changes --verbosity quiet` | Passed; only touched files formatted | | `git diff --check` and `git diff --cached --check` | Passed | | `git diff --quiet ad38e20 -- src/Controls/src/Core/Handlers/Items/Android/SpacingItemDecoration.cs` | Passed; exact production-source identity | Additionally, an uncommitted dependency-free managed harness compiled the **exact production source** against minimal Android/RecyclerView stubs. **809,530 offset comparisons passed**, covering empty/single/mixed/full-span rows, both orientations, assigned/fallback span indices, linear layouts, invalid positions, zero-spacing early return, and bounded lookups for a 10,050-position grouped grid. The same harness with unmodified Candidate source failed the bounded-lookup assertion as expected. This checks managed offset logic and lookup counts, **not native Android/JNI performance or rendering**. **Not run:** the added UI test, existing Issue35700/Issue38321 runtime coverage, native device tests, fling/ANR measurements, or screenshot comparison. No XCTest, Appium execution, simulator/emulator, GUI, or browser automation was used, per the user's active-work restriction. No native runtime proof is claimed; Android CI/artifact validation is still 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. --> Fixes #38925 <!-- Are you targeting main? All PRs should target the main branch unless otherwise noted. --> Targeting `inflight/candidate` by explicit servicing-backport request, not `main`. #38926 is intentionally not claimed as fixed. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…from the items source instead of walking every position (#39063) > [!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! ### Issue Details After #38969, `GridLayoutManager` still resolves the span index / row of a position it has not cached yet by calling `getSpanSize()` for every position from the nearest cached key to the target — a JNI round-trip each. `ScrollTo` into a cold region of a large grid, or laying out rows while scrolling back up past the cached keys, is O(n) per lookup: 200 000 grouped items, `ScrollTo` last group blocks the UI thread for 12.8 s (6.9 s flat). ### Root Cause `GridLayoutSpanSizeLookup` only overrides `GetSpanSize`; `GetSpanIndex`/`GetSpanGroupIndex` fall back to AndroidX's walk. ### Description of Change Override `GetSpanIndex`/`GetSpanGroupIndex`. The items source already knows where full-span items sit, so the layout is a short list of blocks (a full-span item, or a run of regular items that starts on a fresh row) and the answer is arithmetic plus a binary search. The table is rebuilt lazily after `AdapterDataObserver` notifications (the same ones `GridLayoutManager` uses to drop its own span caches) or a span-count change; adjacent groups without a separating header/footer are merged into one run because they share rows. Unknown adapters fall back to the base implementation. `ItemsViewAdapter` gains an internal `IItemsViewAdapter` view of its source; no public API change.⚠️ Since this is a follow-up PR of #38969, which is only merged to inflight/current, the source branch of this PR is based on inflight/current also. Tests and measurements for baseline are based on inflight/current with the first PR in place to demonstrate the diff on top of that improvement. If needed I can rebase onto main. ### Measurements (HONOR PGT‑N19, Release, 200 000 items, Span=4, UI thread blocked) Step | Grouped before | Grouped after | Flat before | Flat after -- | -- | -- | -- | -- Load | 127 ms | 110 ms | 83 ms | 110 ms ScrollTo end | 13 412 ms | 92 ms | 7 081 ms | 146 ms ScrollTo middle | 2 523 ms | 123 ms | 1 787 ms | 120 ms ScrollTo start | 112 ms | 127 ms | 203 ms | 141 ms | Before | After | |---|---| | <video src="https://github.com/user-attachments/assets/d8206648-bf64-4207-8b4e-dd195d217f8a" width="300"> | <video src="https://github.com/user-attachments/assets/ed798125-b2cc-4092-b1d2-6ad17c86d25b" width="300"> | ### Tests - Device: `GridSpanLookupMatchesGreedySpanAssignment` — 128 combinations checked position-by-position against the greedy assignment `GridLayoutManager` derives from `GetSpanSize`; `GridSpanLookupTracksGroupedSourceChanges` — item and group insertions. - UI: `Issue38926` — 200 000 items grouped and flat; `ScrollTo` end / middle / start must each finish within 5 s (before: 1.8–12.8 s; after: ~100 ms). ### Issues Fixed Fixes #38926
#38925 (#39335) <!-- 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! <!-- !!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING MAIN. !!!!!!! --> ### Description of Change <!-- Enter description of the fix in this section --> **Regression-only backport to `inflight/candidate`, explicitly requested for servicing. This is not a backport of the entire mixed source PR.** Candidate baseline: `3d96e23006ea80f58ff2946017eb4593f63a46c6`. #38925 reports the Android `CollectionView` / `GridItemsLayout` regression from **10.0.90 to 10.0.100**, introduced by #35782. `SpacingItemDecoration.GetItemOffsets` calls the uncached `GetSpanGroupIndex(itemCount - 1)` for every child, scanning the adapter through JNI on repeated layout/scroll passes. Large sources stall ItemsSource/layout and can ANR during flings. Bring over only `SpacingItemDecoration.cs` from #38969 (production file is identical to the rebased source): return immediately for zero spacing; identify the first/last span rows by inspecting only the items that can share those rows, using assigned child span indices with the original lookup fallback. Keep existing adapter-position/count bounds, linear-layout behavior, outer-edge spacing, and full-span header/footer handling. Candidate's other Android fixes remain untouched. Source provenance: - Original GitHub merge SHA: [`c6b0c73ccbc7eebd5c9a683e5b803d786cf37cf7`](c6b0c73). - Current rebased equivalent: [`ad38e20f14fa841bd82b3b569256e84c45e48d4f`](ad38e20). **Deliberately excluded:** #38926's longstanding `ObservableGroupedSource.GetGroupAndIndex` optimization and its focused device test; the source page/test's far-group `ScrollTo` actions and timing expectations; general optimization PR #39063. These are not part of the #38925 servicing regression. No version pins, dependencies, CI configuration, or generated manifests/localization files changed. Adapt the directly relevant Issue38925 HostApp and Android-only CollectionView shard-6 test to load **50 groups × 200 items**, check that the first item is rendered, and assert the app-reported ItemsSource/dispatcher elapsed time is **below 15,000 ms**. The in-app time assertion avoids accepting a slow load merely because Appium's tap returns after the stall. No ScrollTo requirement is retained. **Validation (compilation and non-UI checks only):** used the installed SDK explicitly, without changing `global.json`. Restores were performed only after missing assets/build-task dependency failures. Preliminary missing-assets and missing-task failures were resolved; an initial target-framework mismatch was corrected to Candidate's `net10.0-android36.0` graph. | Exact command | Result | | --- | --- | | `dotnet /usr/local/share/dotnet/sdk/10.0.100/dotnet.dll restore src/Controls/src/Core/Controls.Core.csproj -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -v:q` | Passed | | `dotnet /usr/local/share/dotnet/sdk/10.0.100/dotnet.dll build src/Controls/src/Core/Controls.Core.csproj -f net10.0-android36.0 --no-restore -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -v:q` | Passed; 0 errors, 3 existing Gradle Java-8 source/target deprecation warnings | | `dotnet /usr/local/share/dotnet/sdk/10.0.100/dotnet.dll build Microsoft.Maui.BuildTasks.slnf -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -v:q` | Passed; 0 warnings/errors | | `dotnet /usr/local/share/dotnet/sdk/10.0.100/dotnet.dll restore src/Controls/tests/TestCases.HostApp/Controls.TestCases.HostApp.csproj -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -v:q` | Passed | | `dotnet /usr/local/share/dotnet/sdk/10.0.100/dotnet.dll build src/Controls/tests/TestCases.HostApp/Controls.TestCases.HostApp.csproj -f net10.0-android --no-restore -t:Compile -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -v:q` | Passed; 0 warnings/errors; Compile target only, no app launch | | `dotnet /usr/local/share/dotnet/sdk/10.0.100/dotnet.dll restore src/Controls/tests/TestCases.Android.Tests/Controls.TestCases.Android.Tests.csproj -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -v:q` | Passed | | `dotnet /usr/local/share/dotnet/sdk/10.0.100/dotnet.dll build src/Controls/tests/TestCases.Android.Tests/Controls.TestCases.Android.Tests.csproj --no-restore -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -v:q` | Passed after correcting a nullable timing-text diagnostic; final build 0 warnings/errors; test assembly compilation only | | `dotnet /usr/local/share/dotnet/sdk/10.0.100/dotnet.dll format whitespace . --folder --include src/Controls/src/Core/Handlers/Items/Android/SpacingItemDecoration.cs src/Controls/tests/TestCases.HostApp/Issues/Issue38925.cs src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue38925.cs --verify-no-changes --verbosity quiet` | Passed; only touched files formatted | | `git diff --check` and `git diff --cached --check` | Passed | | `git diff --quiet ad38e20 -- src/Controls/src/Core/Handlers/Items/Android/SpacingItemDecoration.cs` | Passed; exact production-source identity | Additionally, an uncommitted dependency-free managed harness compiled the **exact production source** against minimal Android/RecyclerView stubs. **809,530 offset comparisons passed**, covering empty/single/mixed/full-span rows, both orientations, assigned/fallback span indices, linear layouts, invalid positions, zero-spacing early return, and bounded lookups for a 10,050-position grouped grid. The same harness with unmodified Candidate source failed the bounded-lookup assertion as expected. This checks managed offset logic and lookup counts, **not native Android/JNI performance or rendering**. **Not run:** the added UI test, existing Issue35700/Issue38321 runtime coverage, native device tests, fling/ANR measurements, or screenshot comparison. No XCTest, Appium execution, simulator/emulator, GUI, or browser automation was used, per the user's active-work restriction. No native runtime proof is claimed; Android CI/artifact validation is still 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. --> Fixes #38925 <!-- Are you targeting main? All PRs should target the main branch unless otherwise noted. --> Targeting `inflight/candidate` by explicit servicing-backport request, not `main`. #38926 is intentionally not claimed as fixed. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…from the items source instead of walking every position (#39063) > [!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! ### Issue Details After #38969, `GridLayoutManager` still resolves the span index / row of a position it has not cached yet by calling `getSpanSize()` for every position from the nearest cached key to the target — a JNI round-trip each. `ScrollTo` into a cold region of a large grid, or laying out rows while scrolling back up past the cached keys, is O(n) per lookup: 200 000 grouped items, `ScrollTo` last group blocks the UI thread for 12.8 s (6.9 s flat). ### Root Cause `GridLayoutSpanSizeLookup` only overrides `GetSpanSize`; `GetSpanIndex`/`GetSpanGroupIndex` fall back to AndroidX's walk. ### Description of Change Override `GetSpanIndex`/`GetSpanGroupIndex`. The items source already knows where full-span items sit, so the layout is a short list of blocks (a full-span item, or a run of regular items that starts on a fresh row) and the answer is arithmetic plus a binary search. The table is rebuilt lazily after `AdapterDataObserver` notifications (the same ones `GridLayoutManager` uses to drop its own span caches) or a span-count change; adjacent groups without a separating header/footer are merged into one run because they share rows. Unknown adapters fall back to the base implementation. `ItemsViewAdapter` gains an internal `IItemsViewAdapter` view of its source; no public API change.⚠️ Since this is a follow-up PR of #38969, which is only merged to inflight/current, the source branch of this PR is based on inflight/current also. Tests and measurements for baseline are based on inflight/current with the first PR in place to demonstrate the diff on top of that improvement. If needed I can rebase onto main. ### Measurements (HONOR PGT‑N19, Release, 200 000 items, Span=4, UI thread blocked) Step | Grouped before | Grouped after | Flat before | Flat after -- | -- | -- | -- | -- Load | 127 ms | 110 ms | 83 ms | 110 ms ScrollTo end | 13 412 ms | 92 ms | 7 081 ms | 146 ms ScrollTo middle | 2 523 ms | 123 ms | 1 787 ms | 120 ms ScrollTo start | 112 ms | 127 ms | 203 ms | 141 ms | Before | After | |---|---| | <video src="https://github.com/user-attachments/assets/d8206648-bf64-4207-8b4e-dd195d217f8a" width="300"> | <video src="https://github.com/user-attachments/assets/ed798125-b2cc-4092-b1d2-6ad17c86d25b" width="300"> | ### Tests - Device: `GridSpanLookupMatchesGreedySpanAssignment` — 128 combinations checked position-by-position against the greedy assignment `GridLayoutManager` derives from `GetSpanSize`; `GridSpanLookupTracksGroupedSourceChanges` — item and group insertions. - UI: `Issue38926` — 200 000 items grouped and flat; `ScrollTo` end / middle / start must each finish within 5 s (before: 1.8–12.8 s; after: ~100 ms). ### Issues Fixed Fixes #38926
…from the items source instead of walking every position (#39063) > [!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! ### Issue Details After #38969, `GridLayoutManager` still resolves the span index / row of a position it has not cached yet by calling `getSpanSize()` for every position from the nearest cached key to the target — a JNI round-trip each. `ScrollTo` into a cold region of a large grid, or laying out rows while scrolling back up past the cached keys, is O(n) per lookup: 200 000 grouped items, `ScrollTo` last group blocks the UI thread for 12.8 s (6.9 s flat). ### Root Cause `GridLayoutSpanSizeLookup` only overrides `GetSpanSize`; `GetSpanIndex`/`GetSpanGroupIndex` fall back to AndroidX's walk. ### Description of Change Override `GetSpanIndex`/`GetSpanGroupIndex`. The items source already knows where full-span items sit, so the layout is a short list of blocks (a full-span item, or a run of regular items that starts on a fresh row) and the answer is arithmetic plus a binary search. The table is rebuilt lazily after `AdapterDataObserver` notifications (the same ones `GridLayoutManager` uses to drop its own span caches) or a span-count change; adjacent groups without a separating header/footer are merged into one run because they share rows. Unknown adapters fall back to the base implementation. `ItemsViewAdapter` gains an internal `IItemsViewAdapter` view of its source; no public API change.⚠️ Since this is a follow-up PR of #38969, which is only merged to inflight/current, the source branch of this PR is based on inflight/current also. Tests and measurements for baseline are based on inflight/current with the first PR in place to demonstrate the diff on top of that improvement. If needed I can rebase onto main. ### Measurements (HONOR PGT‑N19, Release, 200 000 items, Span=4, UI thread blocked) Step | Grouped before | Grouped after | Flat before | Flat after -- | -- | -- | -- | -- Load | 127 ms | 110 ms | 83 ms | 110 ms ScrollTo end | 13 412 ms | 92 ms | 7 081 ms | 146 ms ScrollTo middle | 2 523 ms | 123 ms | 1 787 ms | 120 ms ScrollTo start | 112 ms | 127 ms | 203 ms | 141 ms | Before | After | |---|---| | <video src="https://github.com/user-attachments/assets/d8206648-bf64-4207-8b4e-dd195d217f8a" width="300"> | <video src="https://github.com/user-attachments/assets/ed798125-b2cc-4092-b1d2-6ad17c86d25b" width="300"> | ### Tests - Device: `GridSpanLookupMatchesGreedySpanAssignment` — 128 combinations checked position-by-position against the greedy assignment `GridLayoutManager` derives from `GetSpanSize`; `GridSpanLookupTracksGroupedSourceChanges` — item and group insertions. - UI: `Issue38926` — 200 000 items grouped and flat; `ScrollTo` end / middle / start must each finish within 5 s (before: 1.8–12.8 s; after: ~100 ms). ### Issues Fixed Fixes #38926
…from the items source instead of walking every position (#39063) > [!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! ### Issue Details After #38969, `GridLayoutManager` still resolves the span index / row of a position it has not cached yet by calling `getSpanSize()` for every position from the nearest cached key to the target — a JNI round-trip each. `ScrollTo` into a cold region of a large grid, or laying out rows while scrolling back up past the cached keys, is O(n) per lookup: 200 000 grouped items, `ScrollTo` last group blocks the UI thread for 12.8 s (6.9 s flat). ### Root Cause `GridLayoutSpanSizeLookup` only overrides `GetSpanSize`; `GetSpanIndex`/`GetSpanGroupIndex` fall back to AndroidX's walk. ### Description of Change Override `GetSpanIndex`/`GetSpanGroupIndex`. The items source already knows where full-span items sit, so the layout is a short list of blocks (a full-span item, or a run of regular items that starts on a fresh row) and the answer is arithmetic plus a binary search. The table is rebuilt lazily after `AdapterDataObserver` notifications (the same ones `GridLayoutManager` uses to drop its own span caches) or a span-count change; adjacent groups without a separating header/footer are merged into one run because they share rows. Unknown adapters fall back to the base implementation. `ItemsViewAdapter` gains an internal `IItemsViewAdapter` view of its source; no public API change.⚠️ Since this is a follow-up PR of #38969, which is only merged to inflight/current, the source branch of this PR is based on inflight/current also. Tests and measurements for baseline are based on inflight/current with the first PR in place to demonstrate the diff on top of that improvement. If needed I can rebase onto main. ### Measurements (HONOR PGT‑N19, Release, 200 000 items, Span=4, UI thread blocked) Step | Grouped before | Grouped after | Flat before | Flat after -- | -- | -- | -- | -- Load | 127 ms | 110 ms | 83 ms | 110 ms ScrollTo end | 13 412 ms | 92 ms | 7 081 ms | 146 ms ScrollTo middle | 2 523 ms | 123 ms | 1 787 ms | 120 ms ScrollTo start | 112 ms | 127 ms | 203 ms | 141 ms | Before | After | |---|---| | <video src="https://github.com/user-attachments/assets/d8206648-bf64-4207-8b4e-dd195d217f8a" width="300"> | <video src="https://github.com/user-attachments/assets/ed798125-b2cc-4092-b1d2-6ad17c86d25b" width="300"> | ### Tests - Device: `GridSpanLookupMatchesGreedySpanAssignment` — 128 combinations checked position-by-position against the greedy assignment `GridLayoutManager` derives from `GetSpanSize`; `GridSpanLookupTracksGroupedSourceChanges` — item and group insertions. - UI: `Issue38926` — 200 000 items grouped and flat; `ScrollTo` end / middle / start must each finish within 5 s (before: 1.8–12.8 s; after: ~100 ms). ### Issues Fixed Fixes #38926
…from the items source instead of walking every position (#39063) > [!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! ### Issue Details After #38969, `GridLayoutManager` still resolves the span index / row of a position it has not cached yet by calling `getSpanSize()` for every position from the nearest cached key to the target — a JNI round-trip each. `ScrollTo` into a cold region of a large grid, or laying out rows while scrolling back up past the cached keys, is O(n) per lookup: 200 000 grouped items, `ScrollTo` last group blocks the UI thread for 12.8 s (6.9 s flat). ### Root Cause `GridLayoutSpanSizeLookup` only overrides `GetSpanSize`; `GetSpanIndex`/`GetSpanGroupIndex` fall back to AndroidX's walk. ### Description of Change Override `GetSpanIndex`/`GetSpanGroupIndex`. The items source already knows where full-span items sit, so the layout is a short list of blocks (a full-span item, or a run of regular items that starts on a fresh row) and the answer is arithmetic plus a binary search. The table is rebuilt lazily after `AdapterDataObserver` notifications (the same ones `GridLayoutManager` uses to drop its own span caches) or a span-count change; adjacent groups without a separating header/footer are merged into one run because they share rows. Unknown adapters fall back to the base implementation. `ItemsViewAdapter` gains an internal `IItemsViewAdapter` view of its source; no public API change.⚠️ Since this is a follow-up PR of #38969, which is only merged to inflight/current, the source branch of this PR is based on inflight/current also. Tests and measurements for baseline are based on inflight/current with the first PR in place to demonstrate the diff on top of that improvement. If needed I can rebase onto main. ### Measurements (HONOR PGT‑N19, Release, 200 000 items, Span=4, UI thread blocked) Step | Grouped before | Grouped after | Flat before | Flat after -- | -- | -- | -- | -- Load | 127 ms | 110 ms | 83 ms | 110 ms ScrollTo end | 13 412 ms | 92 ms | 7 081 ms | 146 ms ScrollTo middle | 2 523 ms | 123 ms | 1 787 ms | 120 ms ScrollTo start | 112 ms | 127 ms | 203 ms | 141 ms | Before | After | |---|---| | <video src="https://github.com/user-attachments/assets/d8206648-bf64-4207-8b4e-dd195d217f8a" width="300"> | <video src="https://github.com/user-attachments/assets/ed798125-b2cc-4092-b1d2-6ad17c86d25b" width="300"> | ### Tests - Device: `GridSpanLookupMatchesGreedySpanAssignment` — 128 combinations checked position-by-position against the greedy assignment `GridLayoutManager` derives from `GetSpanSize`; `GridSpanLookupTracksGroupedSourceChanges` — item and group insertions. - UI: `Issue38926` — 200 000 items grouped and flat; `ScrollTo` end / middle / start must each finish within 5 s (before: 1.8–12.8 s; after: ~100 ms). ### Issues Fixed Fixes #38926
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!
Issue Details
After #38969,
GridLayoutManagerstill resolves the span index / row of a position it has not cached yet by callinggetSpanSize()for every position from the nearest cached key to the target — a JNI round-trip each.ScrollTointo a cold region of a large grid, or laying out rows while scrolling back up past the cached keys, is O(n) per lookup: 200 000 grouped items,ScrollTolast group blocks the UI thread for 12.8 s (6.9 s flat).Root Cause
GridLayoutSpanSizeLookuponly overridesGetSpanSize;GetSpanIndex/GetSpanGroupIndexfall back to AndroidX's walk.Description of Change
Override
GetSpanIndex/GetSpanGroupIndex. The items source already knows where full-span items sit, so the layout is a short list of blocks (a full-span item, or a run of regular items that starts on a fresh row) and the answer is arithmetic plus a binary search. The table is rebuilt lazily afterAdapterDataObservernotifications (the same onesGridLayoutManageruses to drop its own span caches) or a span-count change; adjacent groups without a separating header/footer are merged into one run because they share rows. Unknown adapters fall back to the base implementation.ItemsViewAdaptergains an internalIItemsViewAdapterview of its source; no public API change.Measurements (HONOR PGT‑N19, Release, 200 000 items, Span=4, UI thread blocked)
38926_before.mp4
38926_after.mp4
Tests
GridSpanLookupMatchesGreedySpanAssignment— 128 combinations checked position-by-position against the greedy assignmentGridLayoutManagerderives fromGetSpanSize;GridSpanLookupTracksGroupedSourceChanges— item and group insertions.Issue38926— 200 000 items grouped and flat;ScrollToend / middle / start must each finish within 5 s (before: 1.8–12.8 s; after: ~100 ms).Issues Fixed
Fixes #38926