Repository navigation
[Android] Fix ScrollToAsync UI-thread livelock caused by the MapRequestScrollTo retry loop - #39213
Conversation
…#39190) <!-- 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 --> Regenerate only `issue-triage.lock.yml` using gh-aw v0.86.2 against deployed main `8c974ad7037c6e171e951883c752bbcea1514cc3`, following dotnet#39065. Shared `pat_pool.md` frontmatter changed before merge, leaving the triage lock stale. Actual production runs [37503999448](https://github.com/dotnet/maui/actions/runs/37503999448) and [37503998307](https://github.com/dotnet/maui/actions/runs/37503998307) failed before inference/publication with `E009 CONFIG_HASH_MISMATCH`. The compiler changes only `frontmatter_hash` in the first metadata line: - Previous: `d2c371bf924eb254532ec722f31d817ebdb42fd4e5565b4952a40e09e465e0d1` - Regenerated: `eb116514f337eb247c8767becceaefdd9cfb69da65044098b5cdc510e7c2d153` The new value matches the actual activation runtime recomputation in run 37503999448. All bytes after that metadata line are unchanged: authorization, GPT-only inference, permission boundaries, publication, hash checks, action/container pins and job conditions are preserved. Add a deployment note requiring dependent lock recompilation after shared import frontmatter changes. No workflow source, shared import, script or C# changes. Configuration validation: - `git merge-base --is-ancestor 8c974ad HEAD` — passed before editing; initial HEAD was exactly that deployed squash merge. - `gh aw compile issue-triage --strict --no-check-update` — passed; 1 workflow succeeded, 0 warnings, compiler v0.86.2. - `gh aw hash-frontmatter .github/workflows/issue-triage.md` — passed; output equals regenerated metadata and actual runtime hash above. - `test "$(gh aw hash-frontmatter .github/workflows/issue-triage.md)" = "$(head -n 1 .github/workflows/issue-triage.lock.yml | sed 's/^# gh-aw-metadata: //' | jq -r .frontmatter_hash)"` — passed. - `cmp <(git show HEAD:.github/workflows/issue-triage.lock.yml | tail -n +2) <(tail -n +2 .github/workflows/issue-triage.lock.yml)` — passed before committing; compiled lock excluding metadata is byte-identical to deployed main. - `actionlint -ignore 'unexpected key "queue" for "concurrency" section' .github/workflows/issue-triage.lock.yml` — passed with actionlint 1.7.12; only the existing narrow compiler-generated queue exception. - `git diff --check` — passed. No pipeline/Pester/snapshot/synthetic fixture tests or product builds were added or run. No production commands, dispatches or issue-label mutations were performed for this correction. Post-merge production outcome audit remains separate; local validation does not claim hosted end-to-end success. ### 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. --> Follow-up to dotnet#39065. No issue is closed: the reproduced defect is the activation failure in the linked actual production runs, not the underlying product reports used as smoke-test targets. <!-- Are you targeting main? All PRs should target the main branch unless otherwise noted. -->
…dotnet#39188) <!-- 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 --> Fix a confirmed startup-deadline regression in the CI-fix Azure DevOps dispatcher introduced by dotnet#39147, and correct a separate, pre-existing producer prompt contradiction that blocks mandatory safe-output registration. **Production evidence:** [run 37477952193](https://github.com/dotnet/maui/actions/runs/37477952193) spent approximately 533 seconds between starting the 420-second deadline and completing trusted checkout; [run 37485076087](https://github.com/dotnet/maui/actions/runs/37485076087) spent approximately 494 seconds. Both then failed with `The variable cannot be validated because the value 0 is not a valid value for the DispatcherBudgetSeconds variable.` **Root cause:** The script parameter `[ValidateRange(1, 540)][int]$DispatcherBudgetSeconds` and top-level `$script:DispatcherBudgetSeconds` are the same validated PowerShell variable. Clamping valid caller input `420` against an already-expired absolute deadline assigns `0` to that variable, triggering validation before explicit budget-exhaustion reporting can run. Extracted helper tests did not exercise this entrypoint initialization. **Correction:** - Store the clamped runtime allowance in the distinct `EffectiveDispatcherBudgetSeconds` variable and update remaining-budget helpers and their extracted-test state consistently. Caller budget `0` remains invalid. - Fail startup explicitly with `[dispatcher-budget-exhausted]` when preparation has consumed the deadline, before PR discovery, authentication, HTTP, or sleep. Write a failed preparation/deadline job summary and state `No queue POST was attempted.` This also fails rather than claiming successful no-work reconciliation when the deadline is expired. - Limit trusted checkout to the standalone `/.github/scripts/Queue-CiFixAzdoValidation.ps1` using non-cone sparse checkout. The existing SHA-pinned checkout v7.0.1 supports exact patterns and automatically uses `blob:none` for sparse fetches. Preserve `github.sha`, `fetch-depth: 1`, and `persist-credentials: false`; never fetch or execute PR code. - Document preparation behavior and limitations. Keep the absolute pre-checkout 420-second deadline and ten-minute hard job timeout unchanged; do not restart or extend either allowance. **Validation:** Baseline dispatcher suite: 73 passed. Before the script correction, the six new actual-entrypoint cases produced four expected expired-deadline failures with the original validation exception and two passing caller-validation/future-deadline cases. After correction, all **79 tests passed**, including existing helper/queue regressions. Expired cases assert the preparation summary, explicit prefix, no-POST message, and zero HTTP/sleep calls; a native PowerShell process asserts nonzero exit. The valid future deadline still produces the three verified offline pipeline payloads. Exact final commands and results: ```powershell pwsh -NoProfile -Command '$env:PSModulePath = "/Users/shneuvil/.copilot/session-state/237fbb01-6532-4170-9f5e-6af14fa3a5e0/files/powershell-modules" + [IO.Path]::PathSeparator + $env:PSModulePath; Import-Module Pester -ErrorAction Stop; Invoke-Pester -Path .github/scripts/Queue-CiFixAzdoValidation.Tests.ps1 -Output Normal -CI' # Passed: 79; failed/skipped: 0. Reused existing Pester; no dependency installation. pwsh -NoProfile -Command '$files = @(".github/scripts/Queue-CiFixAzdoValidation.ps1", ".github/scripts/Queue-CiFixAzdoValidation.Tests.ps1"); foreach ($file in $files) { $tokens = $null; $errors = $null; [void][System.Management.Automation.Language.Parser]::ParseFile((Join-Path $PWD $file), [ref]$tokens, [ref]$errors); if ($errors.Count) { $errors | ForEach-Object { Write-Error $_ }; exit 1 }; Write-Output "Parse passed: $file" }' # Passed: both PowerShell files parsed without errors. ``` ```bash actionlint .github/workflows/ci-fix-azdo-validation.yml # Passed. git diff --check # Passed. ``` **Limits:** The sparse-checkout assertion is a static configuration/trust regression, not a hosted checkout timing measurement. Production checkout performance remains unproven; checkout or PowerShell startup exceeding the ten-minute hard guard can still cancel the job before a summary is written. No live Azure queue requests, manual workflow dispatches/reruns, `/azp` requests, or credential/permission/model-policy changes were performed. There is still no successful eligible-PR Azure canary evidence here; this PR does not establish Azure permissions or exact-head check linkage for any of the three pipelines. **Related producer blocker (pre-existing, not introduced by dotnet#39147):** [main producer run 37464881821](https://github.com/dotnet/maui/actions/runs/37464881821) and [net11 producer run 37465231994](https://github.com/dotnet/maui/actions/runs/37465231994) concluded success but emitted `missing_tool` / `report_incomplete`. The net11 diagnostic explicitly says mandatory expectation registration requires PowerShell but the run instructions exclude it. The main diagnostic likewise reports the prompt-specific `no-pwsh` restriction, alongside separate unavailable cited Azure timeline evidence. This is an upstream producer blocker: a compliant PR cannot reach dispatcher validation if required registration is prohibited by its own prompt. Both producers already allow `pwsh` in `tools.bash`, and Hard Rule 11 requires `Register-CiFixSafeOutputExpectation.ps1` or atomic validation/registration via `Test-CiFixTransport.ps1`. Their bottom Environment constraints sections nevertheless said `no pwsh`. The mirrored correction changes only that prose: explicitly identify `pwsh` availability for those deterministic helpers, retain `no gh` / `no python` and `curl` + `jq` API guidance, and reiterate existing fail-closed registration/transport requirements. No tool allowlists, network, permissions, credentials, trust, model policy, or output gates change. Added two assertions in the existing registration test suite protecting both producer twins. Both failed on the old contradictory guidance and pass after correction. Regenerated both locks with retained **gh-aw v0.86.2**, without manual edits or compiler upgrade; **only `body_hash` changes**. Frontmatter and all generated lock runtime content remain identical. Additional exact validation commands and results: ```powershell pwsh -NoProfile -Command '$env:PSModulePath = "/Users/shneuvil/.copilot/session-state/237fbb01-6532-4170-9f5e-6af14fa3a5e0/files/powershell-modules" + [IO.Path]::PathSeparator + $env:PSModulePath; Import-Module Pester -ErrorAction Stop; $config = New-PesterConfiguration; $config.Run.Path = @(".github/scripts/Register-CiFixSafeOutputExpectation.Tests.ps1", ".github/scripts/Test-CiFixTransport.Tests.ps1", ".github/scripts/Queue-CiFixAzdoValidation.Tests.ps1"); $config.Run.Exit = $true; $config.Output.Verbosity = "Normal"; $config.TestResult.Enabled = $true; $config.TestResult.OutputPath = "/Users/shneuvil/.copilot/session-state/1e0cc90a-a521-4055-9e7a-9565cdaf5504/files/producer-and-dispatcher-pester-results.xml"; Invoke-Pester -Configuration $config' # Passed after lock regeneration: 116 tests (6 registration, 31 transport, 79 dispatcher); 0 failed/skipped. pwsh -NoProfile -Command '$file = Join-Path $PWD ".github/scripts/Register-CiFixSafeOutputExpectation.Tests.ps1"; $tokens = $null; $errors = $null; [void][System.Management.Automation.Language.Parser]::ParseFile($file, [ref]$tokens, [ref]$errors); if ($errors.Count) { $errors | ForEach-Object { Write-Error $_ }; exit 1 }; Write-Output "PowerShell parse passed"' # Passed. ``` ```bash /Users/shneuvil/.copilot/session-state/237fbb01-6532-4170-9f5e-6af14fa3a5e0/files/tools/gh-aw-0.86.2/darwin-arm64 compile ci-status-fix ci-status-fix-net11 --strict --no-emit --no-check-update # Passed: 2 workflows, 0 warnings. /Users/shneuvil/.copilot/session-state/237fbb01-6532-4170-9f5e-6af14fa3a5e0/files/tools/gh-aw-0.86.2/darwin-arm64 compile ci-status-fix ci-status-fix-net11 --strict --no-check-update # Passed: 2 workflows, 0 warnings; emitted body-hash-only changes. actionlint .github/workflows/ci-status-fix.lock.yml .github/workflows/ci-status-fix-net11.lock.yml # Nonzero both before and after regeneration: identical six baseline diagnostics. # Each twin: concurrency.queue not recognized, ShellCheck SC2129 style, github.aw expression not recognized. # No new lint findings; baseline/after outputs compared byte-identical. ``` **Producer limits:** These are static prompt/configuration assertions and offline helper tests, not a hosted agent behavior evaluation. Removing the contradiction does not guarantee that an agent will register correctly, find a viable product fix, create a PR, or attach Azure checks. Separate cited-timeline failures and other producer blockers are not fixed here. No live workflow or network validation tests were run. ### 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. --> Follow-up to dotnet#39147 for the production startup regression evidenced by the two linked dispatcher runs, plus the separate pre-existing producer helper-guidance contradiction evidenced by the two producer runs. No separate tracking issue is closed by this PR. <!-- Are you targeting main? All PRs should target the main branch unless otherwise noted. --> --------- Co-authored-by: PureWeen <223556219+Copilot@users.noreply.github.com> Copilot-Session: 1e0cc90a-a521-4055-9e7a-9565cdaf5504
|
🚀 Dogfood this PR with:
curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 39213Or
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 39213" |
|
Azure Pipelines: There may be pipelines that require an authorized user to comment /azp run to run. |
|
Hey there @@philipag! 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 @philipag! Thank you so much for your PR! Someone from the team will get assigned to your PR shortly and we'll get it reviewed. |
|
@dotnet-policy-service agree |
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
The timeout recursively re-arms instead of completing requests for views that never lay out.
Review effort: Balanced
Findings: 1
Open (2)
What changed in this PR
Fixes an Android ScrollToAsync UI-thread livelock caused by repeatedly polling layout state.
Changes:
- Defers only until the first layout.
- Uses a one-shot global-layout listener with a four-second timeout.
- Removes
IsLayoutRequestedfrom the serving condition.
| File | Description |
|---|---|
ScrollViewHandler.Android.cs |
Reworks deferred scroll scheduling and fallback behavior. |
This comment has been minimized.
This comment has been minimized.
|
/azp run |
|
Azure Pipelines: Successfully started running 3 pipeline(s). |
|
Note 🔍
|
kubaflo
left a comment
There was a problem hiding this comment.
Could you please check the ai's suggestions and add test?
This comment has been minimized.
This comment has been minimized.
|
Note 🔍
|
This comment has been minimized.
This comment has been minimized.
MauiBot
left a comment
There was a problem hiding this comment.
Expert Review — 3 findings
See inline comments for details.
| // A view that has been laid out at least once has geometry worth scrolling against: the | ||
| // platform clamps the offsets to the last completed layout. IsLayoutRequested must not gate | ||
| // this decision - see WaitToScrollOnLayout for why waiting on it never ends. | ||
| if (!handler.PlatformView.IsLaidOut) |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[major] Logic and Correctness — Removing IsLayoutRequested from the serve predicate can drop valid add-then-scroll requests: when IsLaidOut is true but a content-growth layout is pending, ServeScrollTo clamps against stale pre-layout extent and no replay occurs after the new layout, so the requested offset is under-shot (repro shape in #10283).
| observer.AddOnGlobalLayoutListener(waiter); | ||
| } | ||
|
|
||
| platformView.PostDelayed(waiter.OnTimeout, LayoutWaitTimeoutMillis); |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[major] Async and Threading Safety — platformView.PostDelayed(waiter.OnTimeout, ...) is not a reliable wall-clock timeout for never-attached/detached views; the runnable can remain queued until attach and never fire, leaving ScrollToAsync incomplete indefinitely on that lifecycle path.
| observer.RemoveOnGlobalLayoutListener(this); | ||
| } | ||
|
|
||
| if (_handler.IsConnected()) |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[major] Handler Mapper and Property Patterns — Deferred request ownership is not cleaned up on disconnect: Fire() drops the serve when !_handler.IsConnected() and there is no handler-level pending-request completion path, so a disconnect/detach before layout/timeout can orphan the corresponding ScrollToAsync task.
MauiBot
left a comment
There was a problem hiding this comment.
AI Review Summary
@philipag — new AI review results are available based on commit
ad2951c.
🗂️ Review Sessions — click to expand
🚦 Gate — Test Before & After Fix
Gate Result: ✅ PASSED
Platform: ANDROID · Base: main · Merge base: b926f057
| Test | Without Fix (expect FAIL) | With Fix (expect PASS) |
|---|---|---|
📱 ScrollViewHandlerTests (ScrollToRequestDeferredBeforeFirstLayoutIsServedByThatLayout, ScrollToRequestForNeverLaidOutViewTerminatesOnceWithoutRetrying) Category=ScrollView |
✅ FAIL — 514s | ✅ PASS — 390s |
🔴 Without fix — 📱 ScrollViewHandlerTests (ScrollToRequestDeferredBeforeFirstLayoutIsServedByThatLayout, ScrollToRequestForNeverLaidOutViewTerminatesOnceWithoutRetrying): FAIL ✅ · 514s
(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.core.devicetests'..
info: Successfully uninstalled com.microsoft.maui.core.devicetests
XHarness exit code: 1 (TESTS_FAILED)
Passed: 0
Failed: 2
Skipped: 0
Total: 2
Tests completed with exit code: 1
🟢 With fix — 📱 ScrollViewHandlerTests (ScrollToRequestDeferredBeforeFirstLayoutIsServedByThatLayout, ScrollToRequestForNeverLaidOutViewTerminatesOnceWithoutRetrying): PASS ✅ · 390s
(no coded error found; showing last 1200 chars)
795000,
"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.core.devicetests'..
info: Successfully uninstalled com.microsoft.maui.core.devicetests
XHarness exit code: 0
Passed: 2
Failed: 0
Skipped: 0
Total: 2
Tests completed successfully
📁 Fix files reverted (1 files)
src/Core/src/Handlers/ScrollView/ScrollViewHandler.Android.cs
📋 Pre-Flight — Context & Validation
Pre-Flight Context
PR snapshot
- PR: #39213 —
[Android] Fix ScrollToAsync UI-thread livelock caused by the MapRequestScrollTo retry loop - State: Open, non-draft; GitHub reports mergeability as blocked.
- Submitted revision:
ad2951c24a68be84ae7bf959afb3c06ec25aa23f - Base revision:
b926f05713b0d1843f8f3bef28b025c6242f1d3c(main) - Scope: 2 files, 325 additions, 6 deletions.
- The immutable diff supplied in the request matches the two files GitHub reports. This context does not assess later worktree state.
Reported problem and relevant existing behavior
The PR reports an Android-specific ScrollView.ScrollToAsync livelock. At the base revision, ScrollViewHandler.MapRequestScrollTo defers while either PlatformView.IsLaidOut is false or PlatformView.IsLayoutRequested is true. Deferral uses PlatformView.Post to invoke the same mapper again.
The reported failure mode is that Android can leave IsLayoutRequested true without scheduling another traversal when RequestLayout() occurs during layout. The reposted mapper then continually sees the same flag and reposts itself, allegedly causing an incomplete ScrollToAsync task, sustained UI-looper traffic, allocations, and CPU/battery use.
Surrounding source supports the completion dependency:
ScrollView.ScrollToAsynccreates aTaskCompletionSourceand returns its task.- The task completes when
IScrollView.ScrollFinished()reachesSendScrollFinished(). - Android’s
MauiScrollView.ScrollTocalls the completion callback immediately after an instant native scroll, or when its one-secondValueAnimatorends for an animated scroll. - The handler calls
VirtualView.ScrollFinished()only while connected. A request that is deferred indefinitely or dropped before that callback can therefore leave the public task incomplete.
The external reproduction archive, raw logs, Android framework internals, and performance measurements cited in the PR description were not independently inspected. Their contents and numerical claims remain unverified context.
Changed files and mechanism
-
src/Core/src/Handlers/ScrollView/ScrollViewHandler.Android.cs- Removes
IsLayoutRequestedfrom the initial defer predicate. A view that has completed any layout is now served immediately against its current geometry. - Extracts the existing conversion, platform scroll, and completion callback into
ServeScrollTo. - For a view not yet laid out, adds
WaitToScrollOnLayout:- Registers a
ViewTreeObserver.IOnGlobalLayoutListenerwhen the observer is alive. - Schedules a four-second fallback with
platformView.PostDelayed. - Calls
RequestLayout()only whenIsLayoutRequestedis false.
- Registers a
- Adds
LayoutWaiter, which usesInterlocked.Exchangeas a one-shot guard shared by the layout and timeout paths. - On firing, removes itself from the current live
ViewTreeObserverand callsServeScrollToonly if the handler remains connected. - The timeout path goes directly to
ServeScrollTo; it does not re-enter the layout predicate.
- Removes
-
src/Core/tests/DeviceTests/Handlers/ScrollView/ScrollViewHandlerTests.Android.cs- Adds a four-second test-side bound corresponding to the private production constant.
- Adds
ScrollToRequestDeferredBeforeFirstLayoutIsServedByThatLayout:- Starts with an attached but
GONE, never-laid-out view. - Makes it visible and induces a layout-requested latch from a global-layout callback.
- Expects the deferred request to be served once before the timeout.
- Expects a later request in
IsLaidOut && IsLayoutRequestedto be served immediately. - Waits beyond the fallback period to check that the original request is not served twice.
- Starts with an attached but
- Adds
ScrollToRequestForNeverLaidOutViewTerminatesOnceWithoutRetrying:- Uses an attached
GONEview that remains unlaid-out. - Expects no immediate completion, one completion around the fallback bound, and no second completion after another timeout period.
- Uses an attached
- Adds a counting
IScrollViewstub usingVolatile.ReadandInterlocked.Increment.
Platform-sensitive paths
The implementation and tests are Android-only. Important Android-specific behavior includes:
View.IsLaidOutandView.IsLayoutRequestedlifecycle semantics.ViewTreeObserver.OnGlobalLayout, which is tree-wide; the waiter filters events by checking whether its own view is laid out.View.PostDelayedbehavior while attached versus detached.RequestLayout()behavior during a traversal.- Native offset clamping against current child extent.
- Handler disconnection, platform-view detachment/reattachment, and possible handler reuse.
- Instant and animated scrolling have different completion paths in
MauiScrollView; the added tests invokeScrollToRequest(..., instant: true)only.
For comparison, the base iOS and Windows handlers explicitly store pending scroll requests as handler state and complete/remove them during DisconnectHandler. The submitted Android waiter is local to each request and is not owned or canceled by DisconnectHandler.
Related issue context
The PR links symptom-adjacent reports, but the available records do not establish that they share this precise root cause:
- #15387: open;
ScrollToAsynccalled from navigation/appearing does not return, labeled for Android and iOS. The issue body available through GitHub is limited. It references closed #16619. - #10283: open; adding children and scrolling in the same method fails. The report says Android completes without scrolling, while Windows remains incomplete until manual scrolling.
- #19835: open; nested Android
ScrollViewrequest is a silent no-op. - #14594: closed as a duplicate; Android scroll-to-element/coordinate no-op.
Current Controls source also has separate logic that parks element-target requests until element geometry exists. How that newer Controls-level behavior interacts with each historical issue is unknown.
Validation requirements and supplied evidence
- Required platform: Android.
- Provided Gate result: Gate ✅ PASSED — tests FAIL without fix, PASS with fix.
- The Gate was not re-run.
- The PR author reports Pixel 8 Pro/API 36 device-test and reproduction measurements, including red/green results and surrounding ScrollView suites. Those figures were not independently verified here.
- GitHub’s aggregate commit-status endpoint currently reports
pendingwith no legacy status entries. GitHub exposed a large check-run set, but it was not exhaustively inspected; overall CI health is therefore unknown, not absent.
Later Android validation should distinguish at least:
- First-layout event completion from timeout completion.
- Attached-but-never-laid-out and never-attached views.
- No repeated posting, duplicate serving, or retained listener after each outcome.
- Disconnect, detach/reattach, and handler/platform-view reuse while waiting.
- Content growth followed immediately by
ScrollToAsync, including final offset after the pending layout. - Instant and animated requests.
- Vertical, horizontal, and bidirectional orientations where relevant.
- Multiple or superseding requests and correct task completion ownership.
Remaining uncertainties
These are unresolved context items, not conclusions:
- An unresolved review thread argues that dropping
IsLayoutRequestedmay serve against stale geometry during a legitimate pending layout, allowing Android to clamp to the old extent and lose an add-then-scroll request such as #10283. - Another thread notes that
LayoutWaiter.Firedoes not complete the request when the handler has disconnected. Because the request has already left Controls’ pending path, the public task may remain incomplete; lifecycle ownership and cleanup need confirmation. - A further thread claims
View.PostDelayedon a detached or never-attached view may not reach the main looper until attachment, defeating the wall-clock timeout. The added timeout test covers an attachedGONEview, not a never-attached view. - The first test records its event-path timing after the request and layout trigger. An unresolved comment argues that elapsed setup time could allow the fallback to fire while the measured interval still appears shorter than four seconds.
- Removing the listener through
_view.ViewTreeObserverassumes the observer used for removal corresponds appropriately to the observer used for registration across detach/reattach. - When layout wins, the delayed callback remains scheduled until its four-second deadline; the one-shot guard prevents a second serve, but temporary object retention and callback cleanup were not characterized.
- The four-second timeout value and user-visible latency are policy choices with no cited shared constant.
- Serving a never-laid-out view completes the task but may apply no offset because the platform has zero scrollable geometry. The PR author explicitly reports that callers needing the offset after a later
GONE → VISIBLEtransition would need another request. - The PR currently has unresolved automated review threads and an earlier human changes-requested review asking that automated suggestions be checked and tests added. Tests were subsequently added, but no later human disposition was observed.
- This is context gathering only, not an exhaustive code review or an adjudication of the submitted approach.
🔬 Code Review — Deep Analysis
Expert PR Evaluation
Verdict: NEEDS_CHANGES
Confidence: low
Independent Assessment
The submitted Android change replaces recursive looper polling before first layout with a one-shot global-layout listener plus a four-second fallback, while serving requests immediately after any completed layout. The one-shot guard prevents the event and timeout paths from serving the same request twice, but the submitted implementation does not preserve request ownership across all layout and handler lifecycle states.
Blocking Findings
-
❌ Stale geometry can under-serve requests during a legitimate pending layout —
src/Core/src/Handlers/ScrollView/ScrollViewHandler.Android.cs:175Dropping
IsLayoutRequestedfrom the defer predicate means an already-laid-out view with pending content growth scrolls against its previous extent. Android can clamp the request before the new extent exists, and the submitted code has no post-layout replay. This leaves the add-content-then-scroll mechanism unresolved. -
❌ The fallback is not a wall-clock timeout for an unattached or detached view —
src/Core/src/Handlers/ScrollView/ScrollViewHandler.Android.cs:236View.PostDelayeduses the view callback queue when the view is not attached. The runnable may not reach the main looper until attachment, so a view that never attaches can still leaveScrollToAsyncincomplete indefinitely. -
❌ Disconnect can orphan a deferred request —
src/Core/src/Handlers/ScrollView/ScrollViewHandler.Android.cs:290LayoutWaiter.Firesuppresses serving afterIsConnected()becomes false, but the handler does not own, cancel, or complete the pending request during disconnect. A disconnect before layout or timeout therefore has no completion handoff for the public task.
Prior Review Reconciliation
The expert reviewer checked top-level reviews, inline review comments, and PR issue comments. Existing concerns corresponding to all three findings remain applicable to submitted revision ad2951c24a68be84ae7bf959afb3c06ec25aa23f.
Blast Radius and Failure Modes
- The mapper runs for every Android
ScrollToAsyncrequest; the change is platform-specific but affects normal, pre-layout, and lifecycle-transition paths. - No new process-wide or static state is introduced.
- Listener one-shot state prevents duplicate serving, but does not solve request ownership after disconnect.
- Multiple requests create independent waiters with no supersession or cancellation policy.
- Added tests exercise attached views and instant scrolling; they do not establish never-attached timeout behavior, disconnect completion, animated completion, or correct final offset after pending content growth.
Evidence Status
- Gate: ✅ PASSED — the supplied tests fail without the submitted fix and pass with it.
- Required-check state was not established as clean; the expert observed failing and in-progress check runs through anonymous submitted-SHA evidence after authenticated required-check retrieval was unavailable.
- Inline findings were persisted to
inline-findings.jsonbefore refinement consideration.
The three concrete mechanisms meet the evidence-first threshold for one consolidated pr-plus-reviewer refinement.
🛠️ Try-Fix — Analysis & Comparison
Alternative generation: not requested
Evidence-first mode intentionally omits routine Try-Fix attempts. This is not a failed
attempt, a completed alternative search, or evidence that alternatives have no value.
The expert review may still produce one evidence-backed PR refinement.
🏁 Report — Final Recommendation
⚠️ Final Recommendation: REQUEST CHANGES
Phase Status
| Phase | Status | Notes |
|---|---|---|
| Pre-Flight | ✅ COMPLETE | Trusted evidence-first context consumed |
| Code Review | NEEDS_CHANGES (low) | 3 blocking errors, 0 warnings |
| Gate | ✅ PASSED | Android; tests fail without the submitted fix and pass with it |
| Try-Fix | not requested | Evidence-first mode intentionally omitted routine alternatives |
| Refinement | ❌ FAILED | One implemented candidate; isolated validation was invalid and its focused build found a compile error |
| Report | ✅ COMPLETE |
Code Review and Candidate Comparison
| Rank | Candidate | Evidence | Blocking status |
|---|---|---|---|
| 1 | pr |
Gate passed for the submitted Android fix | Expert review found stale-geometry, unattached-timeout, and disconnect-completion defects |
| 2 | pr-plus-reviewer |
Implemented one consolidated refinement | Candidate-local SDK provisioning failed, the subsequent raw-worktree SDK fallback is inadmissible, and the focused candidate build failed with CS0234 at ScrollViewHandler.Android.cs:262 |
pr wins the bounded comparison because it is the only candidate with valid passing regression evidence. That does not make it merge-ready: the expert findings independently veto approval. The implemented refinement attempted to wait for legitimate pending layouts, schedule the timeout on the main looper, and make disconnect own completion, but a candidate that does not compile and was not validated in isolation must rank below the Gate-passing submitted fix.
Summary
The submitted fix removes the UI-thread repost loop and the supplied Gate demonstrates the targeted regression, but it leaves three blocking lifecycle/layout mechanisms unresolved. Routine Try-Fix was not requested. The sole evidence-backed refinement was implemented once and validated once as required; provisioning broke isolation and the build exposed a compile error, so it cannot replace or validate the PR.
Root Cause
The original Android mapper treats IsLayoutRequested as proof that another traversal will arrive and recursively reposts itself while that flag remains true. Android can leave the flag latched without scheduling a traversal, producing an unbounded looper retry and preventing ScrollToAsync completion.
Fix Quality
The raw PR replaces polling with a one-shot layout listener and fallback, which addresses the observed livelock and passed the supplied Gate. However, serving immediately whenever IsLaidOut is true can clamp against stale extent during legitimate pending content growth; View.PostDelayed does not provide a wall-clock bound before attachment; and a disconnect can remove the only path that completes a deferred request. These are concrete blocking findings, so the submitted fix requires further changes even though it remains the comparison winner.
📱 UI Tests — ViewBaseTests
Detected UI test categories: ViewBaseTests
✅ Deep UI tests — 118 passed, 0 failed, 1 skipped across 1 category on platform-pool agent (replaces in-process counts above).
🧪 UI Test Execution Results (deep, platform pool)
| Category | Tests | Snapshot diffs |
|---|---|---|
ViewBaseTests |
118/119 (1 skipped) ✓ | — |
📎 Download drop-deep-uitests artifact (TRX + snapshot diffs) |
🧭 Next Steps — review latest findings
No alternative fix was selected for this run. Review the session findings and CI results before merging.
kubaflo
left a comment
There was a problem hiding this comment.
Could you check the ai's suggestions?
This comment has been minimized.
This comment has been minimized.
Tests Failure Analysis🧪 CI Analysis — click to expand📊 maui-pr
🧪 maui-pr-devicetests
🧪 maui-pr-uitests
🧭 Follow-up — actions and refreshNext action: Complete UI/device evidence; inspect Install binlog and unresolved assertions.
|
…stScrollTo retry loop (#39213) ### The bug On Android, `ScrollView.ScrollToAsync` can enter a state where **the returned `Task` never completes and the handler spins the UI thread forever** — thousands of looper messages per second, continuous JNI-bridge allocations, GC churn, battery drain — until the process is killed. The trigger is the handler's own wait condition `!IsLaidOut || IsLayoutRequested` becoming permanently true, which an ordinary app can cause without touching any MAUI internals. ### Cause `MapRequestScrollTo` defers by re-posting itself to the same looper it is running on: ```csharp if (!handler.PlatformView.IsLaidOut || handler.PlatformView.IsLayoutRequested) { handler.PlatformView.Post(() => { if (handler.IsConnected()) MapRequestScrollTo(handler, scrollView, args); }); return; } ``` This treats `IsLayoutRequested == true` as "a traversal is scheduled, so the condition will eventually clear". Android does not guarantee that: `ViewRootImpl` silently swallows `requestLayout()` while it is handling a layout-inside-layout request (`mHandlingLayoutInLayoutRequest`) — routine when a layout callback resizes or scrolls the view itself (parallax, keyboard-adaptive containers, auto-scroll lists). The flag then stays set with **no traversal ever coming**, so every armed retry re-posts forever: one permanent message-loop item plus one `RunnableImplementor`/closure allocation per `ScrollToAsync` call. A flag-polled retry cannot detect or escape this state, because the state is *defined* by the flag no longer meaning what the loop assumes it means. ### Repro Self-contained MAUI app: **[ScrollBug-repro.zip](https://github.com/philipag/maui/releases/download/scrollbug-repro-zip/ScrollBug-repro.zip)** (sources + raw logcat, no build outputs; build with `cd repro && dotnet build`). It uses the stock `ScrollView` and no handler overrides; one test-page hook subscribes to the view's `ViewTreeObserver.GlobalLayout` and calls `RequestLayout()` from inside the callback — precisely the swallowed-request pattern above. The app then *verifies* the latch (40 ms sampling of `IsLaidOut`/`IsLayoutRequested`, reports `STUCK pct=100 laidOutPct=100`), fires 20 × `ScrollToAsync(0, y, false)`, and counts its own UI-thread message flow through a `Looper` printer. Pixel 8 Pro emulator (API 36), stock `Microsoft.Maui.Controls 11.0.0-rc.1.26451.6`: ``` completedInBudget=0/20 — every Task HUNG idleMsgs=1,213/s with the screen on; 5,325/s backgrounded with the screen off (mWakefulness=Dozing) census top: ViewRootImpl$ViewRootHandler <- mono.java.lang.RunnableImplementor x~182,000 per 30 s CPU 115 % of one core, 4.5 MB/s allocated ``` The same app with the scroll calls removed reports 1 msg/s — a healthy `ScrollView` never produces this signature. Raw logcat for every run is in the zip. ### The fix Keep the deferral for the case it exists for (before the **first** layout), but stop gating it on a flag that can lie forever: 1. **Serve once the view has been laid out at all.** Platform `ScrollTo` clamps against the last completed layout, so serving is never less correct than waiting — and in the latched state it is the only option that terminates. `IsLayoutRequested` drops out of the branch condition. 2. **Wait on the event whose arrival the wait is for**: a one-shot `ViewTreeObserver.OnGlobalLayoutListener`, after `RequestLayout()` arms the traversal when none is pending. Event-driven, so nothing polls or self-re-posts. 3. **Bound the wait (4 s)**: a view that never lays out (e.g. inside a collapsed container) still serves the clamped scroll and completes the caller's `Task` rather than parking it forever. The served path is untouched — same pixel conversion, same `ScrollFinished()` semantics — so requests that work today behave identically. ### Results Same app, same verified-frozen state, A/B by swapping only the `RequestScrollTo` mapping: | Pixel 8 Pro emulator, 20 calls | stock rc-1 | this change | |---|---|---| | Tasks completed | 0 / 20 (all hang) | **20 / 20** (max 5 ms) | | idle UI-thread msgs/s, screen on | 1,213 | ordinary redraw | | idle UI-thread msgs/s, screen off + backgrounded | 5,532 | **0** (0 % CPU) | | healthy-view sanity legs | OK | OK, unchanged | It gets *worse* off-screen: vsync work disappears and the retry chains run at raw looper throughput. No platform mitigation applies — the loop holds no wakelock, alarm or job for Doze/App Standby to gate, and battery optimization is enabled for the repro package and changes nothing. That combination is why this shows up as battery drain on an idle screen with no console output and no wake-lock in the usage stats. ### Related issues Same wait branch, reported as hangs / silent no-ops: - [#15387](#15387) — *Calling ScrollView ScrollToAsync in OnNavigatedTo event or OnAppearing event does not return.* - [#10283](#10283) — *ScrollView.ScrollToAsync not working if Children.Add used in the same method* - [#19835](#19835) — *ScrollToAsync does not work on nested ScrollView in Android* - [#14594](#14594) — *ScrollToAsync Not Working on Andrioid* (closed as duplicate) Those reports show the *hang / no-op* face of this branch. When the view is in the latched state described above, each deferred request instead becomes a permanent item on the message loop — the CPU/GC/battery half of this bug. Those issues also discuss the completion callback parking inside `MauiScrollView`, which this PR deliberately does **not** touch: it fixes the scheduling half, so the latched state terminates instead of livelocking. ### Review focus 1. Is gating the deferral on `IsLaidOut` alone the right predicate? 2. Is the shape/value of the bounded fallback (a 4 s `PostDelayed`) acceptable, or would you prefer it sourced from an existing constant? Two device tests are now in this PR (`src/Core/tests/DeviceTests/Handlers/ScrollView/ScrollViewHandlerTests.Android.cs`), covering both ways the wait can end: * `ScrollToRequestDeferredBeforeFirstLayoutIsServedByThatLayout` - laid out later, served by that layout pass. * `ScrollToRequestForNeverLaidOutViewTerminatesOnceWithoutRetrying` - GONE on a live window, served once by the bounded fallback, then nothing. Against `main` both fail with `Actual: 0` after their full observation window, i.e. the request is never served; against the handler in this PR both pass, and the surrounding suite is unchanged (Core 86/84 passed/2 skipped, Controls 13/13). Measured logs, the message census before and after, and the harness used are in the replies to the two review threads. --- *Analysis, repro harness and measurements in this PR were produced with AI assistance (qwen3.8-flash-next); every number above was measured on the emulator and is reproducible from the attached zip.* ---------
<!-- 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 --> Add `/review gate` as an explicit existing-test-only mode without replacing or shortening the existing hosted `/review` process. Bare `/review`, its platform/branch options, and dispatches that omit the new flag continue to select the full review. `/review tests` and `/review performance` remain independent. The gate retains the existing selected unit, XAML, device, and UI verifier, including failure-only verification for test-only changes, bounded native selection, retry handling, and skipped/inconclusive outcomes. It does not generate missing tests or run expert code review, Try-Fix, deep-category UI sweeps, or Copilot inference. These exclusions apply only to gate mode; hosted `/review` and local full-review tools retain their existing phases. Publish a commit-pinned, bounded report with a closed **Gate analysis** section. The original expandable layout from #38807 is refined to match [the user-selected test-failure-analysis comment](#37572 (comment)): an author/commit quote, flat-square result/platform/commit badges, and readable result tables grouped by test type. At the user's request, omit the Scope badge/text, Follow-up accordion, and report/artifact-link footer. Only recognized diagnostic fields are rendered; raw execution-log excerpts remain escaped in their own collapsed section rather than displaying a raw Markdown document. Posting runs on a fresh agent and only maintains gate signals and publisher-owned gate comments; it does not approve PRs or edit their titles/descriptions. The trigger and scheduled recovery recognize both commands and preserve the selected mode after permission and source-comment revalidation. Previously removed existing full-review coverage is restored unchanged; no new pipeline/configuration tests are added. Live validation exposed two selection defects: a closed nested Picker helper was mistaken for its test fixture, and a nested XAML `Test` fixture became an assembly-wide filter. Resolve containing class scopes using the existing C# declaration scanner, and group nested XAML fixtures by their page. Build errors and no-match results remain visibly unverified in both detailed evidence and the console summary. Keep the verifier's existing passing policy, but make the publication explicit that unmatched/inconclusive groups are not successful execution evidence. A publication canary exposed an unnecessary repository-label metadata PATCH returning HTTP 404. The gate now assigns the existing gate labels without editing repository-wide descriptions/colors. Required assignment failures explicitly fail publication instead of being ignored. The final live publication completed without that warning. **Additive routing at production source `3e96214dacd9c65b3e99b0f23801e197722d0fc3`:** | Request | Selected pipeline | | --- | --- | | `/review` or normal/default dispatch | Existing full review, Deep UI, final AI Summary, cleanup, and telemetry | | `/review gate` or `gate_only=true` | Setup/Gate, fresh gate-only publication, and cleanup | | `/review tests` / `/review performance` | Their unchanged independent workflows | `eng/pipelines/ci-copilot.yml` keeps the original full stages inline and defaults `GateOnly` to **false**. Its explicit true branch selects `pr-review-gate.yml` at compile time, so gate runs contain no full-review/inference, Deep UI, or token-aggregation jobs. The parent passes the shared 150-minute Gate task limit as a typed template parameter; an actual Azure compiler preview exposed that the extracted stage template cannot read the parent's static timeout directly. No new Azure definition, secret, permission, or OIDC trust is required. **Current validation:** - `actionlint .github/workflows/review-trigger.yml .github/workflows/review-trigger-recovery.yml` - passed. Both Azure YAML files parse, all four changed production PowerShell scripts and 48 compile-time-expanded embedded PowerShell blocks parse, and `git diff --check` passes. - Azure Runs API `previewRun=true` on definition 27723 with the production branch and exact SHA above - **nine successful compiler previews**: omitted mode, explicit false on Android/iOS/Catalyst/Windows, and explicit true on all four platforms. Omitted mode expands identically to false. Full mode retains all five original stages; gate mode includes only `Gate`, `PostGate`, and `CleanupReviewLock`, with a 150-minute credential-free Gate task. - `Invoke-Pester -Path @('.github/scripts/ReviewTrigger.Tests.ps1', '.github/scripts/Recover-MissedReviewCommands.Tests.ps1', '.github/scripts/Review-PR.Tests.ps1', '.github/scripts/CopilotPipeline.Tests.ps1', '.github/scripts/shared/Prepare-UITestFailureAnalysis.Tests.ps1', '.github/scripts/Post-AISummaryComment.Tests.ps1') -Output Minimal -PassThru` - **246 passed, two unchanged model-pin assertions failed** against the independent, untouched `Review-Tests.ps1`. The restored existing suites and implicated product files match the original/current main versions; these unrelated assertions are not changed to manufacture a green result. - [Remote additive canary 15652574](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_build/results?buildId=15652574), queued by [the existing trusted-main dispatcher](https://github.com/dotnet/maui/actions/runs/38237622825), **succeeded** on this draft PR. Only Gate, fresh PostGate, and Cleanup jobs ran; all three succeeded. The no-MAUI-tests control truthfully reported **SKIPPED**, not native test execution. Its 7,062-byte GateLogs artifact contains regular allowlisted diagnostics. The new [MauiBot report](#39189 (comment)) has three badges and a closed Gate analysis with no Scope, Follow-up, or footer; its reviewed head and protected baseline are pinned. Actual GitHub state confirms no gate pass/fail or full-review signals and a released lock. Distinct hosted worker IDs confirm fresh-agent publication. Direct queue access was denied; the already-authorized dispatcher was used without changing credentials or trust. - This pre-merge canary uses isolated source `783a98445b269b3e9e30fef82e98d898ada3a74f` on `kubaflo-gate-only-additive-canary-3e96214`. It differs from production only in the declared `GateOnly` default, temporarily true because the old main dispatcher cannot pass the new input. Its actual Azure-expanded stages are identical to production with explicit true. The production PR remains at the SHA above with default **false**. - `Get-CIStatus.ps1 -PRNumber 39189 -Repository dotnet/maui -MaxJobs 100 -MaxFailureLines 20 -NoCache` - completed and refreshed after the canary; [normal maui-pr build 1631878](https://dev.azure.com/dnceng-public/cbb18261-c48f-4abb-8651-8cdcb5474649/_build/results?buildId=1631878) is still in progress for raw source `3e96214dacd9c65b3e99b0f23801e197722d0fc3` and merge source `74b9a40864ccb43a4079c8bb5d50fd20d53ea0ef`. The latest snapshot has six succeeded jobs, 20 pending/running, and no failures. Pending CI is not passing CI. <details> <summary>Earlier source-specific Gate execution, ten-PR canaries, and compact-comment validation</summary> The evidence below is preserved at its original execution/presentation sources. It does not claim that the ten earlier canaries ran at the newest additive source. **End-to-end execution validation at source `8e639d714ae303b62b537596cf488a476393bdc1`:** - Final publisher PowerShell parsing and `git diff --cached --check` passed. Earlier changed PowerShell/embedded Azure Bash and PowerShell syntax checks, YAML parsing, and `actionlint .github/workflows/review-trigger.yml .github/workflows/review-trigger-recovery.yml` passed; the follow-ups do not alter those YAML files. - `Invoke-Pester -Path @('.github/scripts/shared/Update-AgentLabels.Tests.ps1', '.github/scripts/shared/Detect-TestsInDiff.Tests.ps1', '.github/skills/verify-tests-fail-without-fix/scripts/Verify-TestsFail.Tests.ps1') -Output Minimal -PassThru` — 176 passed, zero failed. The actual console summary renderer was exercised with build-error, unmatched-filter, and environment-error records; none appeared as expected assertion failures. The final live log also correctly displays `BUILD ERR` rather than a successful runtime failure. - Azure Runs API previews succeeded for Android, iOS, Catalyst, and Windows, with only Gate, PostGate, and lock cleanup jobs. The Android `RunGate` task expands to 150 minutes. Those YAML configurations are unchanged by the publisher follow-ups. - The full detector against the exact #39175 test files selects only `UnitTest:PickerTests` and `XamlUnitTest:Maui30644`, merging the XAML page and code-behind rather than selecting a closed helper or broad `Test` filter. - The [hosted PowerShell suite at that source](https://github.com/dotnet/maui/actions/runs/37511816441) matches the existing workflow-equivalent selection: 2,456 passed and three unchanged model-policy assertions failed against the independent `/review tests` implementation/workflow files. Those unrelated model pins are not changed here. The retained local full-review publisher's 75 existing regressions pass. - [Skill validation at that source](https://github.com/dotnet/maui/actions/runs/37511811901): static validation passed, but the evaluation artifact exits 1 with 12 protocol and 18 capability session-construction errors (`Session filesystem path escapes root`), zero evaluation turns, and zero tokens. The unchanged hermeticity harness separately fails while materializing missing sparse-checkout blobs (`Could not reset index file to revision 'HEAD'`). A green execution job is not a passing skill evaluation. - [First live Picker/XAML canary on #39175](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15583760): `Maui30644` reproduced the issue and passed all three cases with the fix, but the incorrect Picker filter matched no tests. The corrections above address that selection. #39175 merged before publication; the publisher correctly refused the closed target and cleanup released its lock. - [Second Android canary on #37572](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15584958) completed the Gate, fresh publication, and cleanup, but exposed the repository-label metadata warning corrected above. Its owned report was superseded by the final canary. - [Final Android canary on #37572](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15585863), dispatched through [trusted `main`](https://github.com/dotnet/maui/actions/runs/37511805027), **succeeded at the exact source SHA above**. The selected `AnimationTests` baseline cannot compile without the fix's internal `HasTweener` API; all seven cases pass with the fix. This exercises the verifier's existing compile-coupled mode, not runtime FAIL-to-PASS reproduction. - The final fresh agent published [the gate report](#37572 (comment)), applied the appropriate gate signal without repository-label metadata edits, and minimized the previous owned report as outdated. Actual GitHub state confirmed the old report minimized, the new report visible, the tested head unchanged, and the in-progress lock absent. Cleanup succeeded. No new full-review tracking/outcome labels or PR metadata edits are claimed. **Comment-presentation follow-up at source `4d85e1f9307a83aba11c4603603876de8dcb121c`:** - Publisher PowerShell parsing and `git diff --cached --check` passed. The existing targeted label, detector, verifier, and local full-review publisher suites passed: **251 tests, zero failures**. No new pipeline/configuration tests were added. - `Post-PRGate.ps1 -DryRun` used the exact final-canary diagnostic transcript and immutable commit/run identities. The actual GitHub Markdown API rendered four badges, a real before/after results table, closed Gate analysis and Follow-up sections, and separately escaped execution logs. The existing failure-only report writer was also exercised with all four test types; skipped/no-report and merge-blocked previews do not claim execution or a with-fix result. - At the user's request, a separately guarded maintainer edit reformatted **the same existing MauiBot comment**, rather than running the publisher under a different identity or posting a duplicate. The live comment's `body_html` read-back confirms the new rendering. MauiBot attribution, the original verdict/run, both tested commits, the PR head, and every label are unchanged. This is a presentation-only edit of existing evidence, **not a new Azure verification run**. **Requested ten-PR canary batch — all ten outcomes verified:** All ten original runs were dispatched from trusted `main` with the custom `pipeline_ref` at source `4d85e1f9307a83aba11c4603603876de8dcb121c`. Original identities remain preserved separately from corrective attempts. Corrective unit-selection/publication runs used `78bb5d3a3bc6da91357b5b116542d77bcc283449`; final Windows helper validation used `d4397eaa8b855209c963ea8aad201508c3d45c05`; the additional Windows bootstrap control used source `ecd602ef48662a2a59f083d9db8fc5bdfb83fd45`. The batch is not represented as ten runs at the newest source. | PR | Platform | Verified outcome | Actual evidence | | --- | --- | --- | --- | | [#37319](#37319 (comment)) | Android | FAILED | [15596739](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15596739): with-fix unit execution has 53 passes and two genuine stroke-transition assertion failures. The independent UI case fails without the fix and passes with it, but does not conceal the unit failures. Unit baseline is compile-coupled to the new API. | | [#38441](#38441 (comment)) | Catalyst | PASSED | [15596747](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15596747): selected CollectionView height-update device case fails without the fix and passes with it. | | [#38625](#38625 (comment)) | Android | PASSED | [15596742](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15596742): 64 selected with-fix unit/SourceGen/XAML cases pass across five groups; baseline compilation is coupled to the new API. | | [#39013](#39013 (comment)) | Android | PASSED | [15596744](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15596744): the selected CurrentItem-after-removal UI case runs and fails without the fix, then runs and passes with it. | | [#38883](#38883 (comment)) | Catalyst, corrective host | FAILED | [15597032](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15597032): corrected `SkiaSharpSvgToolsTests` selects 16 cases, including both PR-added SVG tests. All pass without the fix, on confirmation, and with it. The selected unit tests do not reproduce this packaging change; this is not a with-fix test failure. | | [#39213](#39213 (comment)) | Android; Windows control | SKIPPED | Original corrective Android control [15597033](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15597033) and Windows bootstrap control [15597596](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15597596) both select no tests. No successful test execution or passing signal claimed. | | [#37690](#37690 (comment)) | iOS, corrective run | INCONCLUSIVE | [15597037](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15597037): all 23 selected unit cases pass with the fix; baseline cannot compile against the new cache API. Scoped device execution produces no fresh XHarness XML, so overall verification stays inconclusive. | | [#38843](#38843 (comment)) | iOS, corrective run | INCONCLUSIVE | [15597038](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15597038): test-only ScrollView verification produces no fresh device result. No with-fix execution is claimed. | | [#39185](#39185 (comment)) | Android | FAILED | [15596745](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15596745): selected `BindingPath_Parsed` passes without the fix, both confirmations, and with the fix. Fresh method-scoped XML contains one passing result; a different failure in the broader class cannot count as reproduction of this selected test. Actual inflight baseline is `262d95940f646b601093b36db4e27c691670d753`. | | [#39179](#39179 (comment)) | Windows, final helper run | PASSED, failure-only | [15597455](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15597455): ten actual HybridWebView UI cases, nine passing and one expected baseline failure (`VerifyHybridWebViewWithShadow`, 6.11% screenshot difference). Shared parser classifies the real results without the former missing-helper exception. No with-fix run is claimed. | For all ten outcomes, bounded artifact export, fresh MauiBot publication, actual stored HTML, reviewed head, appropriate gate signals, and lock cleanup are verified. At these execution sources, reports rendered four badges and closed Gate analysis/Follow-up accordions; test-group tables were rendered when evidence existed, while the no-tests control truthfully had no test table. The user-requested in-place simplification below now removes Scope and Follow-up from those same reports. Available excerpts remain escaped and detailed execution evidence stays in bounded artifacts. Replaced owned reports are independently confirmed minimized as outdated. Intentional FAILED verdicts remain red even when publication and cleanup succeed. Missing iOS result files are unverified execution, not demonstrated flakes or proof that the target PR is wrong. A passing gate is not full coverage, a code review, or merge readiness. #39179's old Windows attempts at sources before `d4397` could not parse failure-only results because the snapshot-size helper was declared after that branch exited. The older corrective [15597112](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15597112) published and cleaned up successfully but did **not** validate the helper fix. Final [15597455](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15597455) validates the exact helper source and retains the 156,762-byte `test-failure-HybridWebViewFeatureTests.log`. Its author advanced the raw reviewed head from `63621b4f8254b5a4112b1dbac3e676633544ca52` to `0d16b9cc87ef5640e176a2666e02c269ebdd6ce7` before final dispatch; those identities remain separate. Final reviewed/live head is unchanged, only the passing gate signal is present, and the lock is absent. The final build is `partiallySucceeded` because of its initial WSL preparation warning; protected-base recovery, actual Gate, export, fresh publication, and cleanup succeeded. Native Windows provisioning at source `ecd602ef` is separately verified below. **Canary-exposed corrections:** - Source `78bb5d3a3bc6da91357b5b116542d77bcc283449`: explicitly exit successfully after checked publication so an accepted optional label-removal 404 cannot leak a native exit code into PowerShell@2. Required API errors still throw. Bound/truncate allowlisted optional transcripts rather than rejecting all GateLogs when a transcript is oversized. Select the containing unit fixture instead of broad nested `Resize` (597 cases became the intended 16). Corrective SKIPPED, intentional FAILED, and INCONCLUSIVE publications and cleanup complete successfully. - Source `d4397eaa8b855209c963ea8aad201508c3d45c05`: move the unchanged snapshot-size parser helper before shared parsing and both verification modes; retain bounded `test-failure*.log` diagnostics. Updated related documentation. PowerShell parsing of both changed scripts and `git diff --check` passed. `Invoke-Pester -Path @('.github/skills/verify-tests-fail-without-fix/scripts/Verify-TestsFail.Tests.ps1', '.github/scripts/shared/Export-ExpectedPRAgentArtifact.Tests.ps1', '.github/scripts/shared/Copy-BoundedDiagnosticFile.Tests.ps1', '.github/scripts/shared/Import-ExpectedPRAgentArtifact.Tests.ps1') -Output Minimal -PassThru` — **141 passed**, zero failed/skipped/inconclusive/not-run. No new pipeline/configuration tests were written. Actual Windows failure-only parser/log-export/publication verification passed in [15597455](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15597455). - Source `ecd602ef48662a2a59f083d9db8fc5bdfb83fd45`: select a native PowerShell child for the Windows MSBuild-task watchdog instead of system `bash` that selected unconfigured WSL on Windows-2022. Retain the existing Unix command, wall-clock bound, output sanitization, exit-code propagation, and retry markers. YAML parsing, all eight embedded PowerShell blocks, the Windows child command, and `git diff --check` passed; no pipeline tests were added. The additional [Windows bootstrap control 15597596](https://dev.azure.com/DevDiv/DevDiv/_build/results?buildId=15597596), on already-selected no-tests PR #39213 at unchanged head `1021c9a53afc990312bd6be5cea48dd56205c96f`, **completed successfully at this exact source**. MSBuild tasks actually built on the first attempt in 3m10s, with zero errors and no WSL/retry failure. Its bounded report is SKIPPED; fresh MauiBot [6038579070](#39213 (comment)) rendering, absence of pass/fail signals, prior-owned minimization, export, publication, and cleanup are verified. No native tests are claimed for this control; it is not a substitute for the separate Windows helper execution. **User-requested compact presentation at source `e41058bb0798ed6dddabcb1fda339d532bf2f145`:** - Remove the Follow-up accordion and its unused next-action logic, the Scope badge/text, and the report/artifact-link footer. Keep Result/Platform/Commit badges, Gate analysis, nuanced verdicts, test tables, escaped excerpts, and pinned head/baseline identities. Update both relevant report-format documentation sections. Publication ownership, ordering, labels, minimization, and artifact limits are unchanged. - Publisher PowerShell AST parsing and `git diff --cached --check` passed. Production `Post-PRGate.ps1 -DryRun` and actual GitHub Markdown rendering passed using retained evidence for full-mode PASSED (#38441), compile-coupled PASSED (#38625), failure-only PASSED (#39179), FAILED (#37319), SKIPPED (#39213), and INCONCLUSIVE (#37690). Each has three badges and closed Gate analysis without Scope, Follow-up, or the footer; test tables and escaped log contents remain unchanged. No new pipeline tests or native verification reruns were added. - All ten report URLs above were updated **in place** with separately guarded maintainer edits after freshly checking each comment's exact body, update timestamp, owner, ID, and run marker. The publisher was not run under the maintainer's identity. Actual stored `body_html` read-back verifies the same MauiBot comment IDs and unchanged verdicts, commit identities, test tables, and log text. These are presentation-only edits of existing evidence, not new Azure Gate runs or new comments. </details> The additive correction, remote canary verification, earlier ten-PR verification, and compact comment presentation are complete and pushed. This PR remains **draft** while normal CI finishes; no merge readiness is claimed. The earlier model-policy and skill-harness failures are preserved above as source-specific evidence, not silently repaired or described as green. After this PR merges, `/review` continues the full process and `/review gate` selects only existing-test verification. ### 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. --> N/A - requested additive gate-only review and report-presentation changes; #38807 is the initial report-layout reference, not an issue fixed by this PR. <!-- Are you targeting main? All PRs should target the main branch unless otherwise noted. --> --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…stScrollTo retry loop (#39213) ### The bug On Android, `ScrollView.ScrollToAsync` can enter a state where **the returned `Task` never completes and the handler spins the UI thread forever** — thousands of looper messages per second, continuous JNI-bridge allocations, GC churn, battery drain — until the process is killed. The trigger is the handler's own wait condition `!IsLaidOut || IsLayoutRequested` becoming permanently true, which an ordinary app can cause without touching any MAUI internals. ### Cause `MapRequestScrollTo` defers by re-posting itself to the same looper it is running on: ```csharp if (!handler.PlatformView.IsLaidOut || handler.PlatformView.IsLayoutRequested) { handler.PlatformView.Post(() => { if (handler.IsConnected()) MapRequestScrollTo(handler, scrollView, args); }); return; } ``` This treats `IsLayoutRequested == true` as "a traversal is scheduled, so the condition will eventually clear". Android does not guarantee that: `ViewRootImpl` silently swallows `requestLayout()` while it is handling a layout-inside-layout request (`mHandlingLayoutInLayoutRequest`) — routine when a layout callback resizes or scrolls the view itself (parallax, keyboard-adaptive containers, auto-scroll lists). The flag then stays set with **no traversal ever coming**, so every armed retry re-posts forever: one permanent message-loop item plus one `RunnableImplementor`/closure allocation per `ScrollToAsync` call. A flag-polled retry cannot detect or escape this state, because the state is *defined* by the flag no longer meaning what the loop assumes it means. ### Repro Self-contained MAUI app: **[ScrollBug-repro.zip](https://github.com/philipag/maui/releases/download/scrollbug-repro-zip/ScrollBug-repro.zip)** (sources + raw logcat, no build outputs; build with `cd repro && dotnet build`). It uses the stock `ScrollView` and no handler overrides; one test-page hook subscribes to the view's `ViewTreeObserver.GlobalLayout` and calls `RequestLayout()` from inside the callback — precisely the swallowed-request pattern above. The app then *verifies* the latch (40 ms sampling of `IsLaidOut`/`IsLayoutRequested`, reports `STUCK pct=100 laidOutPct=100`), fires 20 × `ScrollToAsync(0, y, false)`, and counts its own UI-thread message flow through a `Looper` printer. Pixel 8 Pro emulator (API 36), stock `Microsoft.Maui.Controls 11.0.0-rc.1.26451.6`: ``` completedInBudget=0/20 — every Task HUNG idleMsgs=1,213/s with the screen on; 5,325/s backgrounded with the screen off (mWakefulness=Dozing) census top: ViewRootImpl$ViewRootHandler <- mono.java.lang.RunnableImplementor x~182,000 per 30 s CPU 115 % of one core, 4.5 MB/s allocated ``` The same app with the scroll calls removed reports 1 msg/s — a healthy `ScrollView` never produces this signature. Raw logcat for every run is in the zip. ### The fix Keep the deferral for the case it exists for (before the **first** layout), but stop gating it on a flag that can lie forever: 1. **Serve once the view has been laid out at all.** Platform `ScrollTo` clamps against the last completed layout, so serving is never less correct than waiting — and in the latched state it is the only option that terminates. `IsLayoutRequested` drops out of the branch condition. 2. **Wait on the event whose arrival the wait is for**: a one-shot `ViewTreeObserver.OnGlobalLayoutListener`, after `RequestLayout()` arms the traversal when none is pending. Event-driven, so nothing polls or self-re-posts. 3. **Bound the wait (4 s)**: a view that never lays out (e.g. inside a collapsed container) still serves the clamped scroll and completes the caller's `Task` rather than parking it forever. The served path is untouched — same pixel conversion, same `ScrollFinished()` semantics — so requests that work today behave identically. ### Results Same app, same verified-frozen state, A/B by swapping only the `RequestScrollTo` mapping: | Pixel 8 Pro emulator, 20 calls | stock rc-1 | this change | |---|---|---| | Tasks completed | 0 / 20 (all hang) | **20 / 20** (max 5 ms) | | idle UI-thread msgs/s, screen on | 1,213 | ordinary redraw | | idle UI-thread msgs/s, screen off + backgrounded | 5,532 | **0** (0 % CPU) | | healthy-view sanity legs | OK | OK, unchanged | It gets *worse* off-screen: vsync work disappears and the retry chains run at raw looper throughput. No platform mitigation applies — the loop holds no wakelock, alarm or job for Doze/App Standby to gate, and battery optimization is enabled for the repro package and changes nothing. That combination is why this shows up as battery drain on an idle screen with no console output and no wake-lock in the usage stats. ### Related issues Same wait branch, reported as hangs / silent no-ops: - [#15387](#15387) — *Calling ScrollView ScrollToAsync in OnNavigatedTo event or OnAppearing event does not return.* - [#10283](#10283) — *ScrollView.ScrollToAsync not working if Children.Add used in the same method* - [#19835](#19835) — *ScrollToAsync does not work on nested ScrollView in Android* - [#14594](#14594) — *ScrollToAsync Not Working on Andrioid* (closed as duplicate) Those reports show the *hang / no-op* face of this branch. When the view is in the latched state described above, each deferred request instead becomes a permanent item on the message loop — the CPU/GC/battery half of this bug. Those issues also discuss the completion callback parking inside `MauiScrollView`, which this PR deliberately does **not** touch: it fixes the scheduling half, so the latched state terminates instead of livelocking. ### Review focus 1. Is gating the deferral on `IsLaidOut` alone the right predicate? 2. Is the shape/value of the bounded fallback (a 4 s `PostDelayed`) acceptable, or would you prefer it sourced from an existing constant? Two device tests are now in this PR (`src/Core/tests/DeviceTests/Handlers/ScrollView/ScrollViewHandlerTests.Android.cs`), covering both ways the wait can end: * `ScrollToRequestDeferredBeforeFirstLayoutIsServedByThatLayout` - laid out later, served by that layout pass. * `ScrollToRequestForNeverLaidOutViewTerminatesOnceWithoutRetrying` - GONE on a live window, served once by the bounded fallback, then nothing. Against `main` both fail with `Actual: 0` after their full observation window, i.e. the request is never served; against the handler in this PR both pass, and the surrounding suite is unchanged (Core 86/84 passed/2 skipped, Controls 13/13). Measured logs, the message census before and after, and the harness used are in the replies to the two review threads. --- *Analysis, repro harness and measurements in this PR were produced with AI assistance (qwen3.8-flash-next); every number above was measured on the emulator and is reproducible from the attached zip.* ---------
…stScrollTo retry loop (#39213) ### The bug On Android, `ScrollView.ScrollToAsync` can enter a state where **the returned `Task` never completes and the handler spins the UI thread forever** — thousands of looper messages per second, continuous JNI-bridge allocations, GC churn, battery drain — until the process is killed. The trigger is the handler's own wait condition `!IsLaidOut || IsLayoutRequested` becoming permanently true, which an ordinary app can cause without touching any MAUI internals. ### Cause `MapRequestScrollTo` defers by re-posting itself to the same looper it is running on: ```csharp if (!handler.PlatformView.IsLaidOut || handler.PlatformView.IsLayoutRequested) { handler.PlatformView.Post(() => { if (handler.IsConnected()) MapRequestScrollTo(handler, scrollView, args); }); return; } ``` This treats `IsLayoutRequested == true` as "a traversal is scheduled, so the condition will eventually clear". Android does not guarantee that: `ViewRootImpl` silently swallows `requestLayout()` while it is handling a layout-inside-layout request (`mHandlingLayoutInLayoutRequest`) — routine when a layout callback resizes or scrolls the view itself (parallax, keyboard-adaptive containers, auto-scroll lists). The flag then stays set with **no traversal ever coming**, so every armed retry re-posts forever: one permanent message-loop item plus one `RunnableImplementor`/closure allocation per `ScrollToAsync` call. A flag-polled retry cannot detect or escape this state, because the state is *defined* by the flag no longer meaning what the loop assumes it means. ### Repro Self-contained MAUI app: **[ScrollBug-repro.zip](https://github.com/philipag/maui/releases/download/scrollbug-repro-zip/ScrollBug-repro.zip)** (sources + raw logcat, no build outputs; build with `cd repro && dotnet build`). It uses the stock `ScrollView` and no handler overrides; one test-page hook subscribes to the view's `ViewTreeObserver.GlobalLayout` and calls `RequestLayout()` from inside the callback — precisely the swallowed-request pattern above. The app then *verifies* the latch (40 ms sampling of `IsLaidOut`/`IsLayoutRequested`, reports `STUCK pct=100 laidOutPct=100`), fires 20 × `ScrollToAsync(0, y, false)`, and counts its own UI-thread message flow through a `Looper` printer. Pixel 8 Pro emulator (API 36), stock `Microsoft.Maui.Controls 11.0.0-rc.1.26451.6`: ``` completedInBudget=0/20 — every Task HUNG idleMsgs=1,213/s with the screen on; 5,325/s backgrounded with the screen off (mWakefulness=Dozing) census top: ViewRootImpl$ViewRootHandler <- mono.java.lang.RunnableImplementor x~182,000 per 30 s CPU 115 % of one core, 4.5 MB/s allocated ``` The same app with the scroll calls removed reports 1 msg/s — a healthy `ScrollView` never produces this signature. Raw logcat for every run is in the zip. ### The fix Keep the deferral for the case it exists for (before the **first** layout), but stop gating it on a flag that can lie forever: 1. **Serve once the view has been laid out at all.** Platform `ScrollTo` clamps against the last completed layout, so serving is never less correct than waiting — and in the latched state it is the only option that terminates. `IsLayoutRequested` drops out of the branch condition. 2. **Wait on the event whose arrival the wait is for**: a one-shot `ViewTreeObserver.OnGlobalLayoutListener`, after `RequestLayout()` arms the traversal when none is pending. Event-driven, so nothing polls or self-re-posts. 3. **Bound the wait (4 s)**: a view that never lays out (e.g. inside a collapsed container) still serves the clamped scroll and completes the caller's `Task` rather than parking it forever. The served path is untouched — same pixel conversion, same `ScrollFinished()` semantics — so requests that work today behave identically. ### Results Same app, same verified-frozen state, A/B by swapping only the `RequestScrollTo` mapping: | Pixel 8 Pro emulator, 20 calls | stock rc-1 | this change | |---|---|---| | Tasks completed | 0 / 20 (all hang) | **20 / 20** (max 5 ms) | | idle UI-thread msgs/s, screen on | 1,213 | ordinary redraw | | idle UI-thread msgs/s, screen off + backgrounded | 5,532 | **0** (0 % CPU) | | healthy-view sanity legs | OK | OK, unchanged | It gets *worse* off-screen: vsync work disappears and the retry chains run at raw looper throughput. No platform mitigation applies — the loop holds no wakelock, alarm or job for Doze/App Standby to gate, and battery optimization is enabled for the repro package and changes nothing. That combination is why this shows up as battery drain on an idle screen with no console output and no wake-lock in the usage stats. ### Related issues Same wait branch, reported as hangs / silent no-ops: - [#15387](#15387) — *Calling ScrollView ScrollToAsync in OnNavigatedTo event or OnAppearing event does not return.* - [#10283](#10283) — *ScrollView.ScrollToAsync not working if Children.Add used in the same method* - [#19835](#19835) — *ScrollToAsync does not work on nested ScrollView in Android* - [#14594](#14594) — *ScrollToAsync Not Working on Andrioid* (closed as duplicate) Those reports show the *hang / no-op* face of this branch. When the view is in the latched state described above, each deferred request instead becomes a permanent item on the message loop — the CPU/GC/battery half of this bug. Those issues also discuss the completion callback parking inside `MauiScrollView`, which this PR deliberately does **not** touch: it fixes the scheduling half, so the latched state terminates instead of livelocking. ### Review focus 1. Is gating the deferral on `IsLaidOut` alone the right predicate? 2. Is the shape/value of the bounded fallback (a 4 s `PostDelayed`) acceptable, or would you prefer it sourced from an existing constant? Two device tests are now in this PR (`src/Core/tests/DeviceTests/Handlers/ScrollView/ScrollViewHandlerTests.Android.cs`), covering both ways the wait can end: * `ScrollToRequestDeferredBeforeFirstLayoutIsServedByThatLayout` - laid out later, served by that layout pass. * `ScrollToRequestForNeverLaidOutViewTerminatesOnceWithoutRetrying` - GONE on a live window, served once by the bounded fallback, then nothing. Against `main` both fail with `Actual: 0` after their full observation window, i.e. the request is never served; against the handler in this PR both pass, and the surrounding suite is unchanged (Core 86/84 passed/2 skipped, Controls 13/13). Measured logs, the message census before and after, and the harness used are in the replies to the two review threads. --- *Analysis, repro harness and measurements in this PR were produced with AI assistance (qwen3.8-flash-next); every number above was measured on the emulator and is reproducible from the attached zip.* ---------
…stScrollTo retry loop (#39213) ### The bug On Android, `ScrollView.ScrollToAsync` can enter a state where **the returned `Task` never completes and the handler spins the UI thread forever** — thousands of looper messages per second, continuous JNI-bridge allocations, GC churn, battery drain — until the process is killed. The trigger is the handler's own wait condition `!IsLaidOut || IsLayoutRequested` becoming permanently true, which an ordinary app can cause without touching any MAUI internals. ### Cause `MapRequestScrollTo` defers by re-posting itself to the same looper it is running on: ```csharp if (!handler.PlatformView.IsLaidOut || handler.PlatformView.IsLayoutRequested) { handler.PlatformView.Post(() => { if (handler.IsConnected()) MapRequestScrollTo(handler, scrollView, args); }); return; } ``` This treats `IsLayoutRequested == true` as "a traversal is scheduled, so the condition will eventually clear". Android does not guarantee that: `ViewRootImpl` silently swallows `requestLayout()` while it is handling a layout-inside-layout request (`mHandlingLayoutInLayoutRequest`) — routine when a layout callback resizes or scrolls the view itself (parallax, keyboard-adaptive containers, auto-scroll lists). The flag then stays set with **no traversal ever coming**, so every armed retry re-posts forever: one permanent message-loop item plus one `RunnableImplementor`/closure allocation per `ScrollToAsync` call. A flag-polled retry cannot detect or escape this state, because the state is *defined* by the flag no longer meaning what the loop assumes it means. ### Repro Self-contained MAUI app: **[ScrollBug-repro.zip](https://github.com/philipag/maui/releases/download/scrollbug-repro-zip/ScrollBug-repro.zip)** (sources + raw logcat, no build outputs; build with `cd repro && dotnet build`). It uses the stock `ScrollView` and no handler overrides; one test-page hook subscribes to the view's `ViewTreeObserver.GlobalLayout` and calls `RequestLayout()` from inside the callback — precisely the swallowed-request pattern above. The app then *verifies* the latch (40 ms sampling of `IsLaidOut`/`IsLayoutRequested`, reports `STUCK pct=100 laidOutPct=100`), fires 20 × `ScrollToAsync(0, y, false)`, and counts its own UI-thread message flow through a `Looper` printer. Pixel 8 Pro emulator (API 36), stock `Microsoft.Maui.Controls 11.0.0-rc.1.26451.6`: ``` completedInBudget=0/20 — every Task HUNG idleMsgs=1,213/s with the screen on; 5,325/s backgrounded with the screen off (mWakefulness=Dozing) census top: ViewRootImpl$ViewRootHandler <- mono.java.lang.RunnableImplementor x~182,000 per 30 s CPU 115 % of one core, 4.5 MB/s allocated ``` The same app with the scroll calls removed reports 1 msg/s — a healthy `ScrollView` never produces this signature. Raw logcat for every run is in the zip. ### The fix Keep the deferral for the case it exists for (before the **first** layout), but stop gating it on a flag that can lie forever: 1. **Serve once the view has been laid out at all.** Platform `ScrollTo` clamps against the last completed layout, so serving is never less correct than waiting — and in the latched state it is the only option that terminates. `IsLayoutRequested` drops out of the branch condition. 2. **Wait on the event whose arrival the wait is for**: a one-shot `ViewTreeObserver.OnGlobalLayoutListener`, after `RequestLayout()` arms the traversal when none is pending. Event-driven, so nothing polls or self-re-posts. 3. **Bound the wait (4 s)**: a view that never lays out (e.g. inside a collapsed container) still serves the clamped scroll and completes the caller's `Task` rather than parking it forever. The served path is untouched — same pixel conversion, same `ScrollFinished()` semantics — so requests that work today behave identically. ### Results Same app, same verified-frozen state, A/B by swapping only the `RequestScrollTo` mapping: | Pixel 8 Pro emulator, 20 calls | stock rc-1 | this change | |---|---|---| | Tasks completed | 0 / 20 (all hang) | **20 / 20** (max 5 ms) | | idle UI-thread msgs/s, screen on | 1,213 | ordinary redraw | | idle UI-thread msgs/s, screen off + backgrounded | 5,532 | **0** (0 % CPU) | | healthy-view sanity legs | OK | OK, unchanged | It gets *worse* off-screen: vsync work disappears and the retry chains run at raw looper throughput. No platform mitigation applies — the loop holds no wakelock, alarm or job for Doze/App Standby to gate, and battery optimization is enabled for the repro package and changes nothing. That combination is why this shows up as battery drain on an idle screen with no console output and no wake-lock in the usage stats. ### Related issues Same wait branch, reported as hangs / silent no-ops: - [#15387](#15387) — *Calling ScrollView ScrollToAsync in OnNavigatedTo event or OnAppearing event does not return.* - [#10283](#10283) — *ScrollView.ScrollToAsync not working if Children.Add used in the same method* - [#19835](#19835) — *ScrollToAsync does not work on nested ScrollView in Android* - [#14594](#14594) — *ScrollToAsync Not Working on Andrioid* (closed as duplicate) Those reports show the *hang / no-op* face of this branch. When the view is in the latched state described above, each deferred request instead becomes a permanent item on the message loop — the CPU/GC/battery half of this bug. Those issues also discuss the completion callback parking inside `MauiScrollView`, which this PR deliberately does **not** touch: it fixes the scheduling half, so the latched state terminates instead of livelocking. ### Review focus 1. Is gating the deferral on `IsLaidOut` alone the right predicate? 2. Is the shape/value of the bounded fallback (a 4 s `PostDelayed`) acceptable, or would you prefer it sourced from an existing constant? Two device tests are now in this PR (`src/Core/tests/DeviceTests/Handlers/ScrollView/ScrollViewHandlerTests.Android.cs`), covering both ways the wait can end: * `ScrollToRequestDeferredBeforeFirstLayoutIsServedByThatLayout` - laid out later, served by that layout pass. * `ScrollToRequestForNeverLaidOutViewTerminatesOnceWithoutRetrying` - GONE on a live window, served once by the bounded fallback, then nothing. Against `main` both fail with `Actual: 0` after their full observation window, i.e. the request is never served; against the handler in this PR both pass, and the surrounding suite is unchanged (Core 86/84 passed/2 skipped, Controls 13/13). Measured logs, the message census before and after, and the harness used are in the replies to the two review threads. --- *Analysis, repro harness and measurements in this PR were produced with AI assistance (qwen3.8-flash-next); every number above was measured on the emulator and is reproducible from the attached zip.* ---------
|
Thanks for landing this on inflight/current 👍 We're hitting the Android MapRequestScrollTo UI-thread livelock in production (idle ~100% CPU). |
|
It will be in sr1 net11 |
|
@geezy10 You can work around this. Note that ScrollToAsync is not virtual so this will only work when your code is calling it directly. Personally I think this is a very serious bug that affects lots of people (hence all the confusing bug reports) so I think sr1 is too late for distribution. |
…stScrollTo retry loop (#39213) ### The bug On Android, `ScrollView.ScrollToAsync` can enter a state where **the returned `Task` never completes and the handler spins the UI thread forever** — thousands of looper messages per second, continuous JNI-bridge allocations, GC churn, battery drain — until the process is killed. The trigger is the handler's own wait condition `!IsLaidOut || IsLayoutRequested` becoming permanently true, which an ordinary app can cause without touching any MAUI internals. ### Cause `MapRequestScrollTo` defers by re-posting itself to the same looper it is running on: ```csharp if (!handler.PlatformView.IsLaidOut || handler.PlatformView.IsLayoutRequested) { handler.PlatformView.Post(() => { if (handler.IsConnected()) MapRequestScrollTo(handler, scrollView, args); }); return; } ``` This treats `IsLayoutRequested == true` as "a traversal is scheduled, so the condition will eventually clear". Android does not guarantee that: `ViewRootImpl` silently swallows `requestLayout()` while it is handling a layout-inside-layout request (`mHandlingLayoutInLayoutRequest`) — routine when a layout callback resizes or scrolls the view itself (parallax, keyboard-adaptive containers, auto-scroll lists). The flag then stays set with **no traversal ever coming**, so every armed retry re-posts forever: one permanent message-loop item plus one `RunnableImplementor`/closure allocation per `ScrollToAsync` call. A flag-polled retry cannot detect or escape this state, because the state is *defined* by the flag no longer meaning what the loop assumes it means. ### Repro Self-contained MAUI app: **[ScrollBug-repro.zip](https://github.com/philipag/maui/releases/download/scrollbug-repro-zip/ScrollBug-repro.zip)** (sources + raw logcat, no build outputs; build with `cd repro && dotnet build`). It uses the stock `ScrollView` and no handler overrides; one test-page hook subscribes to the view's `ViewTreeObserver.GlobalLayout` and calls `RequestLayout()` from inside the callback — precisely the swallowed-request pattern above. The app then *verifies* the latch (40 ms sampling of `IsLaidOut`/`IsLayoutRequested`, reports `STUCK pct=100 laidOutPct=100`), fires 20 × `ScrollToAsync(0, y, false)`, and counts its own UI-thread message flow through a `Looper` printer. Pixel 8 Pro emulator (API 36), stock `Microsoft.Maui.Controls 11.0.0-rc.1.26451.6`: ``` completedInBudget=0/20 — every Task HUNG idleMsgs=1,213/s with the screen on; 5,325/s backgrounded with the screen off (mWakefulness=Dozing) census top: ViewRootImpl$ViewRootHandler <- mono.java.lang.RunnableImplementor x~182,000 per 30 s CPU 115 % of one core, 4.5 MB/s allocated ``` The same app with the scroll calls removed reports 1 msg/s — a healthy `ScrollView` never produces this signature. Raw logcat for every run is in the zip. ### The fix Keep the deferral for the case it exists for (before the **first** layout), but stop gating it on a flag that can lie forever: 1. **Serve once the view has been laid out at all.** Platform `ScrollTo` clamps against the last completed layout, so serving is never less correct than waiting — and in the latched state it is the only option that terminates. `IsLayoutRequested` drops out of the branch condition. 2. **Wait on the event whose arrival the wait is for**: a one-shot `ViewTreeObserver.OnGlobalLayoutListener`, after `RequestLayout()` arms the traversal when none is pending. Event-driven, so nothing polls or self-re-posts. 3. **Bound the wait (4 s)**: a view that never lays out (e.g. inside a collapsed container) still serves the clamped scroll and completes the caller's `Task` rather than parking it forever. The served path is untouched — same pixel conversion, same `ScrollFinished()` semantics — so requests that work today behave identically. ### Results Same app, same verified-frozen state, A/B by swapping only the `RequestScrollTo` mapping: | Pixel 8 Pro emulator, 20 calls | stock rc-1 | this change | |---|---|---| | Tasks completed | 0 / 20 (all hang) | **20 / 20** (max 5 ms) | | idle UI-thread msgs/s, screen on | 1,213 | ordinary redraw | | idle UI-thread msgs/s, screen off + backgrounded | 5,532 | **0** (0 % CPU) | | healthy-view sanity legs | OK | OK, unchanged | It gets *worse* off-screen: vsync work disappears and the retry chains run at raw looper throughput. No platform mitigation applies — the loop holds no wakelock, alarm or job for Doze/App Standby to gate, and battery optimization is enabled for the repro package and changes nothing. That combination is why this shows up as battery drain on an idle screen with no console output and no wake-lock in the usage stats. ### Related issues Same wait branch, reported as hangs / silent no-ops: - [#15387](#15387) — *Calling ScrollView ScrollToAsync in OnNavigatedTo event or OnAppearing event does not return.* - [#10283](#10283) — *ScrollView.ScrollToAsync not working if Children.Add used in the same method* - [#19835](#19835) — *ScrollToAsync does not work on nested ScrollView in Android* - [#14594](#14594) — *ScrollToAsync Not Working on Andrioid* (closed as duplicate) Those reports show the *hang / no-op* face of this branch. When the view is in the latched state described above, each deferred request instead becomes a permanent item on the message loop — the CPU/GC/battery half of this bug. Those issues also discuss the completion callback parking inside `MauiScrollView`, which this PR deliberately does **not** touch: it fixes the scheduling half, so the latched state terminates instead of livelocking. ### Review focus 1. Is gating the deferral on `IsLaidOut` alone the right predicate? 2. Is the shape/value of the bounded fallback (a 4 s `PostDelayed`) acceptable, or would you prefer it sourced from an existing constant? Two device tests are now in this PR (`src/Core/tests/DeviceTests/Handlers/ScrollView/ScrollViewHandlerTests.Android.cs`), covering both ways the wait can end: * `ScrollToRequestDeferredBeforeFirstLayoutIsServedByThatLayout` - laid out later, served by that layout pass. * `ScrollToRequestForNeverLaidOutViewTerminatesOnceWithoutRetrying` - GONE on a live window, served once by the bounded fallback, then nothing. Against `main` both fail with `Actual: 0` after their full observation window, i.e. the request is never served; against the handler in this PR both pass, and the surrounding suite is unchanged (Core 86/84 passed/2 skipped, Controls 13/13). Measured logs, the message census before and after, and the harness used are in the replies to the two review threads. --- *Analysis, repro harness and measurements in this PR were produced with AI assistance (qwen3.8-flash-next); every number above was measured on the emulator and is reproducible from the attached zip.* ---------
…stScrollTo retry loop (#39213) ### The bug On Android, `ScrollView.ScrollToAsync` can enter a state where **the returned `Task` never completes and the handler spins the UI thread forever** — thousands of looper messages per second, continuous JNI-bridge allocations, GC churn, battery drain — until the process is killed. The trigger is the handler's own wait condition `!IsLaidOut || IsLayoutRequested` becoming permanently true, which an ordinary app can cause without touching any MAUI internals. ### Cause `MapRequestScrollTo` defers by re-posting itself to the same looper it is running on: ```csharp if (!handler.PlatformView.IsLaidOut || handler.PlatformView.IsLayoutRequested) { handler.PlatformView.Post(() => { if (handler.IsConnected()) MapRequestScrollTo(handler, scrollView, args); }); return; } ``` This treats `IsLayoutRequested == true` as "a traversal is scheduled, so the condition will eventually clear". Android does not guarantee that: `ViewRootImpl` silently swallows `requestLayout()` while it is handling a layout-inside-layout request (`mHandlingLayoutInLayoutRequest`) — routine when a layout callback resizes or scrolls the view itself (parallax, keyboard-adaptive containers, auto-scroll lists). The flag then stays set with **no traversal ever coming**, so every armed retry re-posts forever: one permanent message-loop item plus one `RunnableImplementor`/closure allocation per `ScrollToAsync` call. A flag-polled retry cannot detect or escape this state, because the state is *defined* by the flag no longer meaning what the loop assumes it means. ### Repro Self-contained MAUI app: **[ScrollBug-repro.zip](https://github.com/philipag/maui/releases/download/scrollbug-repro-zip/ScrollBug-repro.zip)** (sources + raw logcat, no build outputs; build with `cd repro && dotnet build`). It uses the stock `ScrollView` and no handler overrides; one test-page hook subscribes to the view's `ViewTreeObserver.GlobalLayout` and calls `RequestLayout()` from inside the callback — precisely the swallowed-request pattern above. The app then *verifies* the latch (40 ms sampling of `IsLaidOut`/`IsLayoutRequested`, reports `STUCK pct=100 laidOutPct=100`), fires 20 × `ScrollToAsync(0, y, false)`, and counts its own UI-thread message flow through a `Looper` printer. Pixel 8 Pro emulator (API 36), stock `Microsoft.Maui.Controls 11.0.0-rc.1.26451.6`: ``` completedInBudget=0/20 — every Task HUNG idleMsgs=1,213/s with the screen on; 5,325/s backgrounded with the screen off (mWakefulness=Dozing) census top: ViewRootImpl$ViewRootHandler <- mono.java.lang.RunnableImplementor x~182,000 per 30 s CPU 115 % of one core, 4.5 MB/s allocated ``` The same app with the scroll calls removed reports 1 msg/s — a healthy `ScrollView` never produces this signature. Raw logcat for every run is in the zip. ### The fix Keep the deferral for the case it exists for (before the **first** layout), but stop gating it on a flag that can lie forever: 1. **Serve once the view has been laid out at all.** Platform `ScrollTo` clamps against the last completed layout, so serving is never less correct than waiting — and in the latched state it is the only option that terminates. `IsLayoutRequested` drops out of the branch condition. 2. **Wait on the event whose arrival the wait is for**: a one-shot `ViewTreeObserver.OnGlobalLayoutListener`, after `RequestLayout()` arms the traversal when none is pending. Event-driven, so nothing polls or self-re-posts. 3. **Bound the wait (4 s)**: a view that never lays out (e.g. inside a collapsed container) still serves the clamped scroll and completes the caller's `Task` rather than parking it forever. The served path is untouched — same pixel conversion, same `ScrollFinished()` semantics — so requests that work today behave identically. ### Results Same app, same verified-frozen state, A/B by swapping only the `RequestScrollTo` mapping: | Pixel 8 Pro emulator, 20 calls | stock rc-1 | this change | |---|---|---| | Tasks completed | 0 / 20 (all hang) | **20 / 20** (max 5 ms) | | idle UI-thread msgs/s, screen on | 1,213 | ordinary redraw | | idle UI-thread msgs/s, screen off + backgrounded | 5,532 | **0** (0 % CPU) | | healthy-view sanity legs | OK | OK, unchanged | It gets *worse* off-screen: vsync work disappears and the retry chains run at raw looper throughput. No platform mitigation applies — the loop holds no wakelock, alarm or job for Doze/App Standby to gate, and battery optimization is enabled for the repro package and changes nothing. That combination is why this shows up as battery drain on an idle screen with no console output and no wake-lock in the usage stats. ### Related issues Same wait branch, reported as hangs / silent no-ops: - [#15387](#15387) — *Calling ScrollView ScrollToAsync in OnNavigatedTo event or OnAppearing event does not return.* - [#10283](#10283) — *ScrollView.ScrollToAsync not working if Children.Add used in the same method* - [#19835](#19835) — *ScrollToAsync does not work on nested ScrollView in Android* - [#14594](#14594) — *ScrollToAsync Not Working on Andrioid* (closed as duplicate) Those reports show the *hang / no-op* face of this branch. When the view is in the latched state described above, each deferred request instead becomes a permanent item on the message loop — the CPU/GC/battery half of this bug. Those issues also discuss the completion callback parking inside `MauiScrollView`, which this PR deliberately does **not** touch: it fixes the scheduling half, so the latched state terminates instead of livelocking. ### Review focus 1. Is gating the deferral on `IsLaidOut` alone the right predicate? 2. Is the shape/value of the bounded fallback (a 4 s `PostDelayed`) acceptable, or would you prefer it sourced from an existing constant? Two device tests are now in this PR (`src/Core/tests/DeviceTests/Handlers/ScrollView/ScrollViewHandlerTests.Android.cs`), covering both ways the wait can end: * `ScrollToRequestDeferredBeforeFirstLayoutIsServedByThatLayout` - laid out later, served by that layout pass. * `ScrollToRequestForNeverLaidOutViewTerminatesOnceWithoutRetrying` - GONE on a live window, served once by the bounded fallback, then nothing. Against `main` both fail with `Actual: 0` after their full observation window, i.e. the request is never served; against the handler in this PR both pass, and the surrounding suite is unchanged (Core 86/84 passed/2 skipped, Controls 13/13). Measured logs, the message census before and after, and the harness used are in the replies to the two review threads. --- *Analysis, repro harness and measurements in this PR were produced with AI assistance (qwen3.8-flash-next); every number above was measured on the emulator and is reproducible from the attached zip.* ---------
…stScrollTo retry loop (#39213) ### The bug On Android, `ScrollView.ScrollToAsync` can enter a state where **the returned `Task` never completes and the handler spins the UI thread forever** — thousands of looper messages per second, continuous JNI-bridge allocations, GC churn, battery drain — until the process is killed. The trigger is the handler's own wait condition `!IsLaidOut || IsLayoutRequested` becoming permanently true, which an ordinary app can cause without touching any MAUI internals. ### Cause `MapRequestScrollTo` defers by re-posting itself to the same looper it is running on: ```csharp if (!handler.PlatformView.IsLaidOut || handler.PlatformView.IsLayoutRequested) { handler.PlatformView.Post(() => { if (handler.IsConnected()) MapRequestScrollTo(handler, scrollView, args); }); return; } ``` This treats `IsLayoutRequested == true` as "a traversal is scheduled, so the condition will eventually clear". Android does not guarantee that: `ViewRootImpl` silently swallows `requestLayout()` while it is handling a layout-inside-layout request (`mHandlingLayoutInLayoutRequest`) — routine when a layout callback resizes or scrolls the view itself (parallax, keyboard-adaptive containers, auto-scroll lists). The flag then stays set with **no traversal ever coming**, so every armed retry re-posts forever: one permanent message-loop item plus one `RunnableImplementor`/closure allocation per `ScrollToAsync` call. A flag-polled retry cannot detect or escape this state, because the state is *defined* by the flag no longer meaning what the loop assumes it means. ### Repro Self-contained MAUI app: **[ScrollBug-repro.zip](https://github.com/philipag/maui/releases/download/scrollbug-repro-zip/ScrollBug-repro.zip)** (sources + raw logcat, no build outputs; build with `cd repro && dotnet build`). It uses the stock `ScrollView` and no handler overrides; one test-page hook subscribes to the view's `ViewTreeObserver.GlobalLayout` and calls `RequestLayout()` from inside the callback — precisely the swallowed-request pattern above. The app then *verifies* the latch (40 ms sampling of `IsLaidOut`/`IsLayoutRequested`, reports `STUCK pct=100 laidOutPct=100`), fires 20 × `ScrollToAsync(0, y, false)`, and counts its own UI-thread message flow through a `Looper` printer. Pixel 8 Pro emulator (API 36), stock `Microsoft.Maui.Controls 11.0.0-rc.1.26451.6`: ``` completedInBudget=0/20 — every Task HUNG idleMsgs=1,213/s with the screen on; 5,325/s backgrounded with the screen off (mWakefulness=Dozing) census top: ViewRootImpl$ViewRootHandler <- mono.java.lang.RunnableImplementor x~182,000 per 30 s CPU 115 % of one core, 4.5 MB/s allocated ``` The same app with the scroll calls removed reports 1 msg/s — a healthy `ScrollView` never produces this signature. Raw logcat for every run is in the zip. ### The fix Keep the deferral for the case it exists for (before the **first** layout), but stop gating it on a flag that can lie forever: 1. **Serve once the view has been laid out at all.** Platform `ScrollTo` clamps against the last completed layout, so serving is never less correct than waiting — and in the latched state it is the only option that terminates. `IsLayoutRequested` drops out of the branch condition. 2. **Wait on the event whose arrival the wait is for**: a one-shot `ViewTreeObserver.OnGlobalLayoutListener`, after `RequestLayout()` arms the traversal when none is pending. Event-driven, so nothing polls or self-re-posts. 3. **Bound the wait (4 s)**: a view that never lays out (e.g. inside a collapsed container) still serves the clamped scroll and completes the caller's `Task` rather than parking it forever. The served path is untouched — same pixel conversion, same `ScrollFinished()` semantics — so requests that work today behave identically. ### Results Same app, same verified-frozen state, A/B by swapping only the `RequestScrollTo` mapping: | Pixel 8 Pro emulator, 20 calls | stock rc-1 | this change | |---|---|---| | Tasks completed | 0 / 20 (all hang) | **20 / 20** (max 5 ms) | | idle UI-thread msgs/s, screen on | 1,213 | ordinary redraw | | idle UI-thread msgs/s, screen off + backgrounded | 5,532 | **0** (0 % CPU) | | healthy-view sanity legs | OK | OK, unchanged | It gets *worse* off-screen: vsync work disappears and the retry chains run at raw looper throughput. No platform mitigation applies — the loop holds no wakelock, alarm or job for Doze/App Standby to gate, and battery optimization is enabled for the repro package and changes nothing. That combination is why this shows up as battery drain on an idle screen with no console output and no wake-lock in the usage stats. ### Related issues Same wait branch, reported as hangs / silent no-ops: - [#15387](#15387) — *Calling ScrollView ScrollToAsync in OnNavigatedTo event or OnAppearing event does not return.* - [#10283](#10283) — *ScrollView.ScrollToAsync not working if Children.Add used in the same method* - [#19835](#19835) — *ScrollToAsync does not work on nested ScrollView in Android* - [#14594](#14594) — *ScrollToAsync Not Working on Andrioid* (closed as duplicate) Those reports show the *hang / no-op* face of this branch. When the view is in the latched state described above, each deferred request instead becomes a permanent item on the message loop — the CPU/GC/battery half of this bug. Those issues also discuss the completion callback parking inside `MauiScrollView`, which this PR deliberately does **not** touch: it fixes the scheduling half, so the latched state terminates instead of livelocking. ### Review focus 1. Is gating the deferral on `IsLaidOut` alone the right predicate? 2. Is the shape/value of the bounded fallback (a 4 s `PostDelayed`) acceptable, or would you prefer it sourced from an existing constant? Two device tests are now in this PR (`src/Core/tests/DeviceTests/Handlers/ScrollView/ScrollViewHandlerTests.Android.cs`), covering both ways the wait can end: * `ScrollToRequestDeferredBeforeFirstLayoutIsServedByThatLayout` - laid out later, served by that layout pass. * `ScrollToRequestForNeverLaidOutViewTerminatesOnceWithoutRetrying` - GONE on a live window, served once by the bounded fallback, then nothing. Against `main` both fail with `Actual: 0` after their full observation window, i.e. the request is never served; against the handler in this PR both pass, and the surrounding suite is unchanged (Core 86/84 passed/2 skipped, Controls 13/13). Measured logs, the message census before and after, and the harness used are in the replies to the two review threads. --- *Analysis, repro harness and measurements in this PR were produced with AI assistance (qwen3.8-flash-next); every number above was measured on the emulator and is reproducible from the attached zip.* ---------


The bug
On Android,
ScrollView.ScrollToAsynccan enter a state where the returnedTasknever completes and the handler spins the UI thread forever — thousands of looper messages per second, continuous JNI-bridge allocations, GC churn, battery drain — until the process is killed. The trigger is the handler's own wait condition!IsLaidOut || IsLayoutRequestedbecoming permanently true, which an ordinary app can cause without touching any MAUI internals.Cause
MapRequestScrollTodefers by re-posting itself to the same looper it is running on:This treats
IsLayoutRequested == trueas "a traversal is scheduled, so the condition will eventually clear". Android does not guarantee that:ViewRootImplsilently swallowsrequestLayout()while it is handling a layout-inside-layout request (mHandlingLayoutInLayoutRequest) — routine when a layout callback resizes or scrolls the view itself (parallax, keyboard-adaptive containers, auto-scroll lists). The flag then stays set with no traversal ever coming, so every armed retry re-posts forever: one permanent message-loop item plus oneRunnableImplementor/closure allocation perScrollToAsynccall.A flag-polled retry cannot detect or escape this state, because the state is defined by the flag no longer meaning what the loop assumes it means.
Repro
Self-contained MAUI app: ScrollBug-repro.zip (sources + raw logcat, no build outputs; build with
cd repro && dotnet build). It uses the stockScrollViewand no handler overrides; one test-page hook subscribes to the view'sViewTreeObserver.GlobalLayoutand callsRequestLayout()from inside the callback — precisely the swallowed-request pattern above. The app then verifies the latch (40 ms sampling ofIsLaidOut/IsLayoutRequested, reportsSTUCK pct=100 laidOutPct=100), fires 20 ×ScrollToAsync(0, y, false), and counts its own UI-thread message flow through aLooperprinter.Pixel 8 Pro emulator (API 36), stock
Microsoft.Maui.Controls 11.0.0-rc.1.26451.6:The same app with the scroll calls removed reports 1 msg/s — a healthy
ScrollViewnever produces this signature. Raw logcat for every run is in the zip.The fix
Keep the deferral for the case it exists for (before the first layout), but stop gating it on a flag that can lie forever:
ScrollToclamps against the last completed layout, so serving is never less correct than waiting — and in the latched state it is the only option that terminates.IsLayoutRequesteddrops out of the branch condition.ViewTreeObserver.OnGlobalLayoutListener, afterRequestLayout()arms the traversal when none is pending. Event-driven, so nothing polls or self-re-posts.Taskrather than parking it forever.The served path is untouched — same pixel conversion, same
ScrollFinished()semantics — so requests that work today behave identically.Results
Same app, same verified-frozen state, A/B by swapping only the
RequestScrollTomapping:It gets worse off-screen: vsync work disappears and the retry chains run at raw looper throughput. No platform mitigation applies — the loop holds no wakelock, alarm or job for Doze/App Standby to gate, and battery optimization is enabled for the repro package and changes nothing. That combination is why this shows up as battery drain on an idle screen with no console output and no wake-lock in the usage stats.
Related issues
Same wait branch, reported as hangs / silent no-ops:
Those reports show the hang / no-op face of this branch. When the view is in the latched state described above, each deferred request instead becomes a permanent item on the message loop — the CPU/GC/battery half of this bug. Those issues also discuss the completion callback parking inside
MauiScrollView, which this PR deliberately does not touch: it fixes the scheduling half, so the latched state terminates instead of livelocking.Review focus
IsLaidOutalone the right predicate?PostDelayed) acceptable, or would you prefer it sourced from an existing constant?Two device tests are now in this PR (
src/Core/tests/DeviceTests/Handlers/ScrollView/ScrollViewHandlerTests.Android.cs), covering both ways the wait can end:ScrollToRequestDeferredBeforeFirstLayoutIsServedByThatLayout- laid out later, served by that layout pass.ScrollToRequestForNeverLaidOutViewTerminatesOnceWithoutRetrying- GONE on a live window, served once by the bounded fallback, then nothing.Against
mainboth fail withActual: 0after their full observation window, i.e. the request is never served; against the handler in this PR both pass, and the surrounding suite is unchanged (Core 86/84 passed/2 skipped, Controls 13/13). Measured logs, the message census before and after, and the harness used are in the replies to the two review threads.Analysis, repro harness and measurements in this PR were produced with AI assistance (qwen3.8-flash-next); every number above was measured on the emulator and is reproducible from the attached zip.