Skip to content

[Android] Prevent AppBar lift target crash under GC pressure - #38636

Merged
kubaflo merged 7 commits into
inflight/currentfrom
simonrozsival-investigate-android-appbar-lift-crash
Sep 17, 2026
Merged

kubaflo merged 7 commits into
inflight/currentfrom
simonrozsival-investigate-android-appbar-lift-crash

Conversation

@simonrozsival

Copy link
Copy Markdown
Member

Note

Are you waiting for the changes in this PR to be merged?
It would be very helpful if you could test the resulting artifacts from this PR and let us know in a comment if this change resolves your issue. Thank you!

Description

Fixes #38620.

Material 3 AppBar lift-target visibility checks retained an Android.Graphics.Rect Java peer in per-view state and reused it across GC cycles. Under GC pressure, the JNI argument could resolve to null and crash inside Android's View.getGlobalVisibleRect implementation.

This change uses a call-scoped, deterministically disposed Rect for each visibility check. The underlying interop race may belong to the dotnet/android GC bridge, but avoiding the retained peer is the smallest safe MAUI servicing fix.

Changes

  • Stop caching the visibility Rect in AppBarLiftState.
  • Centralize the visibility probe in IsOnScreen using a call-scoped Rect.
  • Add an Android Material 3 device regression test that repeatedly runs the AppBar visibility check during concurrent garbage collection.

Testing

  • Built Core.DeviceTests for Android with UseMaterial3=true.
  • The new AppBarLiftTargetCheckSurvivesGarbageCollection regression test passes on the Android emulator.
  • The broader ScrollView category has two pre-existing AppBar assertions that fail in the zero-sized device-test host; the new regression test itself passes.

Vignesh-SF3580 and others added 7 commits September 16, 2026 19:11
…dapterPositions (#38598)

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

### Issue Details
The GroupedCollectionViewRemovalsUseCurrentAdapterPositions test is
failing on iOS when running with CollectionView1 (CV1). The test was
checked locally, and the crash can be reproduced with CV1. The same test
scenario works properly with CollectionView2 (CV2). The PR changes are
related to Android, while this test failure occurs only with iOS CV1.

This test was added in #38486

### Root Cause
The test scenario causes an existing crash with CollectionView1 (CV1) on
iOS. During the investigation, it was also found that the
GroupFooterTemplate used in the sample contributes to the CV1 crash. The
same scenario works correctly with CV2. The same behavior was reproduced
with MAUI 10.0.0 without the PR changes, confirming that the failure is
not related to this PR.

### Description of Change
Updated the test to run only with CollectionView2 (CV2). This avoids the
existing CV1-specific failure on iOS while continuing to validate the
intended grouped CollectionView item removal scenario.

Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

### Description of Change

Limits skill evaluation specs to the workflow-owned executor and
supported model configuration. The preparer now rejects alternate
executor shapes, provider and plugin mapping keys at any depth, and
combined `defaults` plus legacy `config`, while allowing the same words
in prompt and rubric text.

Adds focused preparer coverage for accepted and rejected configuration
shapes and workflow structure coverage confirming validation completes
before token selection and evaluation steps.

### Validation

- Preparer test suite: 80 runs, 462 assertions
- Preparer validation across all current evaluation spec directories
- Strict Vally 0.14.0 lint across all 16 evaluation specs

### Issues Fixed

N/A

Co-authored-by: PureWeen <223556219+Copilot@users.noreply.github.com>
…and Project Details (#38595)

> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

### Issue Details
VoiceOver on macOS does not announce the ComboBox control type or its
initial "Collapsed" state when initially navigating to the Project and
Category pickers in the .NET MAUI mobile project template
(DeveloperBalance).
Unknown
On initial linear navigation (`Control + Option + Right Arrow`),
VoiceOver reads only the control's descriptive label without indicating
that it is an expandable ComboBox or that its current state is
collapsed.

### Root Cause
In earlier versions, static semantic properties
(`SemanticProperties.Description` and `SemanticProperties.Hint="State
Collapsed"`) were assigned to the parent `SfTextInputLayout` container.
The regression was introduced in PR #32286 , which attempted to make
state announcements dynamic by removing the static `"State Collapsed"`
hint and relying exclusively on `SemanticScreenReader.Announce`
triggered via `Picker.IsOpen` property changes.
Because synthetic announcements only fire on value changes, no state
announcement was produced when the control initially received focus.

### Description of Change

Appended State Collapsed directly to the `SemanticProperties.Hint` of
each native Picker on both the Project Details and Task Details pages.
Kept `SfTextInputLayout` responsible solely for visual presentation and
floating labels.
Preserved existing bindings, commands, and dynamic expansion
announcements from PR #32286 while ensuring the initial resting state is
exposed to platform accessibility APIs.

### Why Tests Were Not Added

This issue requires manual accessibility validation using platform
screen readers (macOS VoiceOver and Android TalkBack) to verify focus
traversal and spoken announcements. Because these accessibility
announcements cannot be reliably validated via automated UI/unit tests,
manual verification was performed across macOS, Android, and Windows.

### Issues Fixed
Fixes #36471 

### Screenshots

| Before Issue Fix | After Issue Fix |
|----------|----------|
| <video width="300" height="600"
src="https://github.com/user-attachments/assets/8ab47eea-6061-4fcb-9780-e8eea0c4e785">
| <video width="300" height="600"
src="https://github.com/user-attachments/assets/b5d23234-2423-43fc-b3cb-915b14e73cd7">
|
…ized by its parent layout (#38599)

### Description of Change

On iOS, a `ScrollView` whose frame is resized by its parent layout in
the same pass in which its content becomes taller than the viewport ends
up **scrolled by half the resize delta**, so the page appears with the
first item partially hidden. The common shape is a bound page: a `Grid`
(`Auto,*,Auto`) with the `ScrollView` in the star row, whose content
*and* an Auto-row footer arrive from the ViewModel after the page is
already on screen — the footer grows, the star row shrinks, the content
grows, and the ScrollView lands at e.g. offset 18 instead of 0 (content
`Padding` 8 + item `Margin` 8 + stroke 2 scrolled away).

**Cause.** `ViewHandlerExtensions.PlatformArrangeHandler` arranges views
by setting `Center` and then `Bounds` (rather than `Frame`, so
non-identity transforms keep working). On a `UIScrollView`,
`Bounds.Origin` *is* the content offset, and UIKit re-derives it inside
`setBounds:` when the size changes — it keeps the content under the
view's center stable, i.e. it scrolls by half the delta. A KVO observer
on `contentOffset` captured the move exactly there:

```
offset->17.0 bounds=(0.0,17.0,691.0) contentSize=725.0
  at UIKit.UIView.set_Bounds(CGRect)
  at Microsoft.Maui.ViewHandlerExtensions.PlatformArrangeHandler(IViewHandler, Rect)   ViewHandlerExtensions.iOS.cs:158
  at Microsoft.Maui.Handlers.ViewHandler`2.PlatformArrange(Rect)
  at Microsoft.Maui.Controls.ScrollView.ArrangeOverride(Rect)
  at Microsoft.Maui.Layouts.GridLayoutManager.ArrangeChildren(Rect)
  at Microsoft.Maui.Platform.MauiView.LayoutSubviews()
```

The arrange defect itself is old: the fixture fails identically on the
`10.0.90` (SR9), `10.0.100` and `10.0.101` sources, so it is not a
regression of the recent ScrollView changes. What changed in SR10 is
*reachability*: #32267 made
`MauiScrollView.InvalidateMeasure(isPropagating: true)` return `true`,
so a content change inside a ScrollView now propagates measure
invalidation to its ancestors (needed so a content-sized ScrollView
shrinks when children are removed). Before SR10 the ScrollView was a
propagation barrier and a bound page's content arrival never re-laid-out
the page; since SR10 it does — and a page host that applies insets or
chrome on every layout pass (a custom scaffold, say) can then resize the
ScrollView in the very pass its content grows. That is why an app can be
clean on SR9 and hit this on SR10/SR11 with no code change of its own;
the fixture forces the resize explicitly (a bound footer growing with
the content) so it reproduces on every version.

**Fix.** Arranging a scroll view must never scroll it.
`ScrollViewHandler.PlatformArrange` (iOS) — the call through which a
parent layout resizes the scroll view — now remembers the content offset
before the base arrange and puts it back if UIKit moved it, clamped to
the range the new size currently allows. The clamp is the same
inset-aware range `ScrollToAsync` already uses
(`ClampToScrollableRange`, shared with `GetTargetContentOffset`: rest is
`-AdjustedContentInset`, the maximum extends past the arranged extent by
the trailing inset). Kept in the ScrollView handler rather than the
generic arrange helper or a `Bounds` override on `MauiScrollView`: it is
scroll-view-specific, only the arrange path is affected, and UIKit
implements `contentOffset` through `setBounds:` so an override there
would sit on every scroll frame. A view the user had scrolled keeps its
position across a resize, exactly as UIKit's own `setFrame:` semantics
would. Side effect worth knowing: in the affected pass `Scrolled` is
raised twice (UIKit's spurious move, then the restore) — the final state
is correct, whereas before the fix the spurious one was raised and
*kept*.

No public API change beyond the `PlatformArrange` override itself.

### Workaround for affected versions

The override is public, so an app (or a library hosting pages) can apply
the same correction without waiting for the fix, by registering a
handler subclass on iOS/MacCatalyst:

```csharp
#if IOS || MACCATALYST
using CoreGraphics;
using Microsoft.Maui.Graphics;
using Microsoft.Maui.Handlers;

public class OffsetPreservingScrollViewHandler : ScrollViewHandler
{
    public override void PlatformArrange(Rect rect)
    {
        var scrollView = PlatformView;
        var offset = scrollView.ContentOffset;

        base.PlatformArrange(rect);

        if (scrollView.ContentOffset == offset)
            return;

        // Restore the offset the arrange found, kept inside the range the new size allows
        var inset = scrollView.AdjustedContentInset;
        var bounds = scrollView.Bounds;
        var contentSize = scrollView.ContentSize;
        var minX = -(double)inset.Left;
        var minY = -(double)inset.Top;
        var maxX = Math.Max(minX, contentSize.Width + inset.Right - bounds.Width);
        var maxY = Math.Max(minY, contentSize.Height + inset.Bottom - bounds.Height);
        scrollView.ContentOffset = new CGPoint(
            Math.Clamp((double)offset.X, minX, maxX),
            Math.Clamp((double)offset.Y, minY, maxY));
    }
}
#endif
```

```csharp
// MauiProgram.cs
builder.ConfigureMauiHandlers(handlers =>
{
#if IOS || MACCATALYST
    handlers.AddHandler<ScrollView, OffsetPreservingScrollViewHandler>();
#endif
});
```

Notes: it clamps against `ContentSize` rather than the internal arranged
extent, which is equivalent for this purpose; it replaces the ScrollView
handler globally, so combine it with any custom ScrollView handler the
app already registers; and once on a fixed version it becomes a harmless
no-op that can be removed. Merely deferring the content population to a
later tick than other layout changes also avoids the coincidence in
plain layouts, but is not reliable under hosts that re-apply insets on
every layout pass.

### Note on #32267 — the enabler, and why it deserves a different
approach

#32267 is what made this reachable from SR10 on, and we think its
approach should be revisited on `main`, independently of this fix.

**What it set out to do is legitimate.** A ScrollView *sized by its
content* — a `StackLayout` child, an `Auto` row, `VerticalOptions=Start`
— must make its parent re-measure when its content shrinks, or it keeps
blank space at the bottom (#32221, #20586, #34536).

**How it did it is the problem.** `MauiScrollView` was deliberately a
measure-invalidation *barrier* (`InvalidateMeasure(isPropagating: true)`
returned `false`; the surrounding code still says "Invalidation stops at
`UIScrollView`s for performance reasons"), and it already had the
targeted escape hatch for the content-sized case: `LayoutSubviews` calls
`InvalidateAncestorsMeasures()` when `ContentSize` changes. #32267's
diff is a single line that flips the barrier off unconditionally
(`return true`), so **every** invalidation raised anywhere inside a
ScrollView now walks up and re-measures the entire page, regardless of
whether the ScrollView's size can even change.

**Performance cost.** A ScrollView in a star row, in `Fill`, or with an
explicit size is fully constrained by its parent: its ancestors can
learn nothing from its content changing, yet since SR10 each such change
— a bound list populating, a `Label` text update, every keystroke in an
`Entry` or `Editor` inside the scroll view — invalidates and re-measures
the page above it. The scroll view is the single most common container
for content-heavy pages, so this is paid constantly, on the main thread,
for no layout result. The old barrier existed precisely to avoid that.

**Correctness cost.** Turning arbitrary content changes into page
re-layouts is what creates the coincidence this PR fixes: a page host
that applies insets or chrome on each layout pass now resizes the
ScrollView in the very pass its content grows. The arrange defect
predates SR10, but SR10 is what makes ordinary bound pages hit it.

**What the fix should have been.** The reported root cause was that, on
the first pass after removing children, `CrossPlatformMeasure` returned
the ScrollView's current size, so `ContentSize` did not change and the
existing `InvalidateAncestorsMeasures()` never fired. The proportionate
fix addresses *that*: propagate only when the ScrollView's own measured
size can actually change — i.e. when it is not size-constrained by its
parent — and/or when its measured size differs from what the parent last
measured. That keeps the content-sized case correct while leaving the
barrier in place for every constrained ScrollView, which is the
overwhelmingly common one. We would suggest reverting the unconditional
`return true` in favour of such a condition as a follow-up on `main`; it
is out of scope for a servicing fix, and this PR is deliberately
independent of it — it fixes the arrange defect regardless of what
triggers the resize.

Separately, the XML doc on
`IPlatformMeasureInvalidationController.InvalidateMeasure` in
`MauiScrollView` says the return value means "stop propagating", while
the walk in `ViewExtensions.InvalidateAncestorsMeasures` treats `true`
as "keep propagating". The doc is inverted and worth a one-line
correction — it makes changes like #32267 easy to misjudge.

### Issues Fixed

Reported against 10.0.101 (page hosted in a custom scaffold with bound
content). Reproduces with plain `NavigationPage` + `Grid`.

### Tests

`ScrollViewInitialOffsetInGridRow` (iOS + MacCatalyst): a pushed,
edge-to-edge page with a `Grid Auto,*,Auto`, the `ScrollView` in the
star row, content `VerticalStackLayout Padding=0,8` whose first child is
a `Border Margin=16,8`, in five cases — static vs. async content
(content and a footer banner arriving together after appearing) × with
vs. without a header row (the latter puts the ScrollView under the
status bar, so the top inset is non-zero), plus a guard where the
content is tall and laid out from the start and only the footer grows
later: an ordinary resize of a laid-out scroll view does not scroll it
(verified without the fix), and the restore must keep it that way. The
page instruments the native `UIScrollView` (offset,
adjusted/content/safe insets, content size, bounds, content frame,
`ScrollY`) and, via KVO, the managed stack of the first offset move, so
a failure names its cause. Oracles: native offset `==
-AdjustedContentInset.Top` and `ScrollY == 0` once the content is laid
out; and, Appium-side, the first item's top exactly 16 below the
ScrollView's visible top.

Results on this commit (iOS simulator, iPhone 11 Pro):

- with the fix: **5/5**; `Issue36801` + `Issue36801DeferredElement` +
`ShellFlyoutHeaderScrollViewContent` suites **12/12**
- with the fix reverted (pristine sr11): `AsyncContentWithHeader`
**fails** at `offset=18` (36pt footer growth, halved); the same case
fails identically against the `10.0.90`, `10.0.100` and `10.0.101`
sources for `src/Core/src` + `src/Controls/src/Core`
- with the fix reverted and `ScrollEventProxy` + `NotifyInsetsChanged`
disabled: still fails with the same `set_Bounds` stack, `ScrollY` left
at 0 while the native offset is 18 — those paths only report the offset
- `StaticContentResizedLater` passes with and without the fix (the
guard)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------
Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
…38621)

This PR addresses UI test failures in the main branch caused in this PR
#38599. And it updates the
`AssertRestsAtTop` test method to improve platform-specific handling for
iOS devices. The main change is that the calculation and assertion logic
for verifying the top position of the first item in the `ScrollView` is
now only applied when running on iOS, ensuring more accurate and
relevant test behavior for that platform.

**Platform-specific test logic:**

* In `ScrollViewInitialOffsetInGridRow.cs`, the calculation and
assertion for the first item's top position relative to the `ScrollView`
are now executed only for iOS devices, with updated comments clarifying
the logic and rationale for this conditional handling.

**Cause:** On Mac Catalyst, Appium element rectangles use desktop screen
coordinates, which cannot be reliably combined with UIKit’s
AdjustedContentInset. This caused false failures in the visual geometry
assertion.
**Fix:** Restrict the geometry assertion to iOS. Mac Catalyst continues
to validate the behavior using the native ContentOffset and managed
ScrollY checks reported by the HostApp.

Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
Use a call-scoped Android Rect for AppBar lift target visibility checks so GC bridge processing cannot invalidate a retained JNI peer. Add a focused device stress test under concurrent garbage collection.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Assert only the crash-prevention contract while the attached view repeatedly checks global visibility under concurrent collection.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI lite review requested due to automatic review settings September 17, 2026 14:05
@github-actions

Copy link
Copy Markdown
Contributor

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 38636

Or

  • Run remotely in PowerShell:
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 38636"

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).
There may be pipelines that require an authorized user to comment /azp run to run.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

The new call-scoped Rect allocation happens from a scroll-changed callback and can introduce avoidable GC pressure during scrolling, and the new stress test should guard against indefinite hangs by adding a timeout when awaiting the background GC loop.

Get a fresh assessment by requesting another Copilot review.

Review effort: Lite
Findings: 2 Medium severity

Open (2)
What changed in this PR

This PR addresses an Android Material 3 crash in MAUI’s AppBar lift-target logic under GC pressure by avoiding reuse of a potentially invalidated Android.Graphics.Rect Java peer during View.getGlobalVisibleRect calls, and adds a device regression test to exercise the scenario.

Changes:

  • Remove the cached per-view Rect from AppBarLiftState and route visibility checks through a new IsOnScreen helper.
  • Use a call-scoped Rect instance for each GetGlobalVisibleRect invocation to avoid holding a stale JNI peer across GC cycles.
  • Add an Android device test that repeatedly triggers the lift-target visibility check while concurrently forcing GC.
File Description
src/​Core/​src/​Platform/​Android/​AppbarLayoutExtensions.cs Reworks on-screen detection to avoid reusing a cached Rect Java peer across GC cycles.
src/​Core/​tests/​DeviceTests/​Handlers/​ScrollView/​ScrollViewHandlerTests.Android.cs Adds a regression device test that stresses TrySetAppBarLiftTargetIfOnScreen under concurrent GC.

Comment on lines 149 to +157
}

static bool IsOnScreen(View view)
{
// Keep the Java peer call-scoped so GC bridge processing cannot invalidate
// a cached JNI reference between visibility checks.
using var visibleRect = new Rect();
return view.GetGlobalVisibleRect(visibleRect);
}
Comment on lines +207 to +211
finally
{
cancellationTokenSource.Cancel();
await gcTask;
}
@kubaflo

This comment has been minimized.

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Expert Review — 1 findings

See inline comments for details.


try
{
for (int i = 0; i < 2_000; i++)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 AI-Generated Review (multi-model)

[major] Regression Prevention and Test Coverage — This regression test only verifies that repeated TrySetAppBarLiftTargetIfOnScreen() calls do not throw, but it does not prove the original bug reproduces on the base implementation. Concrete failure mode: if the cached-Rect implementation survives these 2,000 iterations without throwing on a given run, the test passes on both base and fixed code, so it cannot gate regressions deterministically.

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI Review Summary

@simonrozsival — new AI review results are available based on commit 7d659a1.

Gate Partial Confidence Low Platform Android


🗂️ Review Sessions — click to expand
🚦 Gate — Test Before & After Fix

Gate Result: ❌ FAILED

Platform: ANDROID · Base: main · Merge base: beef1b48

🩺 Test does not reproduce the bug — ran the same in both states (PASS without fix, PASS with fix). The repro test is not exercising the issue. Strengthen the test before reviewing the fix.

Test Without Fix (expect FAIL) With Fix (expect PASS)
📱 ScrollViewHandlerTests (AppBarLiftTargetCheckSurvivesGarbageCollection) Category=ScrollView ❌ PASS — 1176s ✅ PASS — 395s
🔴 Without fix — 📱 ScrollViewHandlerTests (AppBarLiftTargetCheckSurvivesGarbageCollection): PASS ❌ · 1176s

(no coded error found; showing last 1200 chars)

759000,
            "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: 1
  Failed: 0
  Skipped: 0
  Total: 1
  Tests completed successfully
🟢 With fix — 📱 ScrollViewHandlerTests (AppBarLiftTargetCheckSurvivesGarbageCollection): PASS ✅ · 395s

(no coded error found; showing last 1200 chars)

639000,
            "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: 1
  Failed: 0
  Skipped: 0
  Total: 1
  Tests completed successfully

⚠️ Failure Details

  • ❌ ScrollViewHandlerTests (AppBarLiftTargetCheckSurvivesGarbageCollection) PASSED without fix (should fail) — tests don't catch the bug
📁 Fix files reverted (1 files)
  • src/Core/src/Platform/Android/AppbarLayoutExtensions.cs

📋 Pre-Flight — Context & Validation

PR #38636 Pre-Flight

Context

  • PR: [Android] Prevent AppBar lift target crash under GC pressure
  • Issue: #38620, a verified Android Material 3 regression in 10.0.101/current main.
  • Failure: TrySetAppBarLiftTargetIfOnScreen can pass a null JNI Rect peer to View.GetGlobalVisibleRect, producing a main-thread java.lang.NullPointerException while scroll-view hierarchies churn under GC pressure.
  • Affected path: src/Core/src/Platform/Android/AppbarLayoutExtensions.cs.
  • Observed environments: Android API 36 emulator and API 37 physical device; the available local test target is Android API 30.

Existing PR Approach

The PR removes the AppBarLiftState.VisibleRect field and routes both visibility probes through IsOnScreen, which creates and deterministically disposes a new Android.Graphics.Rect per call. This avoids retaining a Java peer across GC cycles, but allocates in the ViewTreeObserver.OnScrollChanged hot path.

The PR also adds AppBarLiftTargetCheckSurvivesGarbageCollection, which invokes the visibility path 2,000 times on the UI thread while a background task repeatedly performs full GC and waits for finalizers.

Direct Diff Assessment

  • Production diff: 10 added lines, 3 removed lines in AppbarLayoutExtensions.cs.
  • Test diff: 58 added lines in ScrollViewHandlerTests.Android.cs.
  • Existing reviewer concerns: per-scroll Java Rect allocation may add GC pressure; the test's background GC task has no timeout and could wedge.
  • Regression cross-reference reported no overlap with labeled recent fixes touching these files.

Gate Evidence

Gate verification is already complete and MUST NOT be rerun. It failed because the new test passed both without and with the PR fix:

State Result
Without fix PASS in 1,176s across the initial run and two confirmations
With fix PASS in 395s

The result is non-discriminating for two independent reasons:

  1. The stress loop does not reproduce the reported JNI race on the available API 30 x86_64 emulator.
  2. RuntimeFeature.IsMaterial3Enabled defaults to false, UseMaterial3 was unset in the current environment, and the test returns immediately when Material 3 is disabled. Candidate validation must explicitly set UseMaterial3=true.

Do not create or overwrite gate/content.md.

Bounded Candidate Validation

Use only the detected primary test and the three directly related AppBar regression tests, in one Android device-test invocation:

UseMaterial3=true pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 \
  -Project Core \
  -Platform android \
  -TestFilter "Category=ScrollView" \
  -IncludeClasses "Microsoft.Maui.DeviceTests.ScrollViewHandlerTests" \
  -IncludeMethods "AppBarLiftTargetCheckSurvivesGarbageCollection,AppBarLiftTargetSetToScrollViewOnAttach,AppBarLiftTargetClearedOnVisibilityGone,AppBarLiftTargetNotSetWhenNoAppBarLayout"

The primary test passing is functional evidence only; it cannot prove the field-reported race is fixed because the baseline gate did not reproduce it. Each candidate gets one implementation/test pass and at most one focused correction/retest.

Worktree Constraints

The worktree contains many pre-existing tracked and untracked changes outside the PR's two-file diff. Preserve them exactly. Follow the try-fix skill's baseline boundary and restore exclusively with:

pwsh .github/scripts/EstablishBrokenBaseline.ps1 -Restore

🔬 Code Review — Deep Analysis

Code Review — PR #38636

Independent Assessment

What this changes: The Android Material 3 AppBar visibility probe no longer stores an Android.Graphics.Rect Java peer in per-view AppBarLiftState. Both initial attachment and ViewTreeObserver.OnScrollChanged now create and dispose a Rect for each GetGlobalVisibleRect call. The PR also adds a device test that invokes the probe 2,000 times while a background task forces collection and finalization.

Inferred motivation: A managed Rect wrapper retained across GC cycles can reach View.GetGlobalVisibleRect with a null/invalid JNI peer, causing Android's Rect.set(...) path to throw. A call-scoped peer narrows the lifetime to one interop call and avoids reuse after GC-bridge processing.

Reconciliation with PR Narrative

Author claims: The cached Java peer causes an Android Material 3 crash under GC pressure; replacing it with a deterministically disposed call-scoped Rect is the smallest servicing fix, and the new device test covers concurrent collection.

Agreement/disagreement: The production change matches the reported stack and removes the suspect retained peer. The regression-test claim is not established: the trusted Gate ran the new test against both the base and fixed implementations, and both passed. On the available API 30 environment, the race did not reproduce; additionally, the test returns without exercising the body when Material 3 is not enabled.

Prior Review Reconciliation

Prior finding Source Status Evidence
Per-scroll Rect allocation can add GC pressure Copilot review, AppbarLayoutExtensions.cs:157 ⚠️ Unresolved OnParentScrollChanged calls IsOnScreen, which allocates a Java peer on every observer callback.
The GC worker can wedge the test because shutdown has no timeout Copilot review, ScrollViewHandlerTests.Android.cs:211 ⚠️ Unresolved The finally block cancels and then awaits gcTask without a bounded wait.

No prior ❌ Error-level finding was present on the PR before this expert pass.

Blast Radius Assessment

  • Runs for all instances: The production path is Android-only and gated by Material 3 callers, but it runs for every participating MauiScrollView and MauiRecyclerView, including each parent scroll-change notification.
  • Startup impact: No application startup/static-initialization change; the path begins when a participating native view attaches or its parent scrolls.
  • Static/shared state: No new static state. Existing per-view state remains in a ConditionalWeakTable; the cached Rect field is removed.
  • Lifecycle/defaults: Existing alive, attachment, visibility, ancestor, and listener cleanup guards are preserved. The change does not alter lift-target ownership semantics.

CI Status

  • Required-check result: Undetermined through gh pr checks --required because GitHub CLI authentication is unavailable. Anonymous check-run data shows the main build running/succeeding, but does not establish the repository's required-check set.
  • Classification: The trusted review Gate is definitively red because the proposed regression test passed on both base and fixed code.
  • Action taken: The Gate was not rerun, as required. Confidence is capped at low and approval is blocked.

Findings

❌ Error — Regression test does not distinguish the fix

At src/Core/tests/DeviceTests/Handlers/ScrollView/ScrollViewHandlerTests.Android.cs:202, a fixed number of repeated calls only asserts that no exception happened in that particular run. The trusted Gate confirmed the cached-Rect base implementation passes this test, including two confirmation runs, so the test cannot reliably detect reintroduction of the defect. It can also return before exercising any assertion when RuntimeFeature.IsMaterial3Enabled is false.

⚠️ Warning — Visibility checking now allocates on a scroll callback

src/Core/src/Platform/Android/AppbarLayoutExtensions.cs:155 creates a Java Rect for every probe, including ViewTreeObserver.OnScrollChanged. This is safer than retaining the suspect peer, but trades the crash for added managed/Java peer churn on a performance-sensitive callback. Given the interop failure mechanism, this can be an acceptable servicing tradeoff only if explicitly accepted; an allocation-free alternative has not been validated.

⚠️ Warning — GC stress-worker shutdown is unbounded

src/Core/tests/DeviceTests/Handlers/ScrollView/ScrollViewHandlerTests.Android.cs:210 awaits a worker that repeatedly calls GC.WaitForPendingFinalizers() without a timeout. If finalization stalls, the device-test work item can hang instead of failing in bounded time.

Failure-Mode Probing

  • Material 3 disabled: The test returns as a pass without executing the regression path, which contributed to non-discriminating Gate evidence when UseMaterial3 was unset.
  • Base implementation does not hit the timing race: All 2,000 calls complete and the test passes, exactly as the Gate observed; no deterministic invariant detects the retained peer.
  • Rapid parent scroll changes: Functional lift-target behavior is unchanged, but each callback now allocates/disposes a Java peer, increasing pressure on the same GC/interop subsystem involved in the report.
  • Detach/reconnect or hidden view: Existing guards return before allocation, and existing detach/visibility cleanup still removes pending work and listeners.
  • Worker finalization stalls: Cancellation is requested, but the UI-thread test remains awaiting gcTask indefinitely because no timeout bounds shutdown.

External Output Contract

Not applicable.

Verdict: NEEDS_CHANGES

Confidence: low

Summary: The call-scoped peer is a plausible, localized mitigation for the reported JNI crash, but the submitted regression test demonstrably passes without the fix and therefore cannot protect it. The red Gate, unresolved hot-path allocation tradeoff, and unbounded stress-worker shutdown require changes or explicit resolution before approval.


🛠️ Try-Fix — Analysis & Comparison

Try-Fix Aggregate for PR #38636

Candidate 1 — JNI Peer-Liveness Guard

Model: gpt-5.3-codex

Result: Blocked before implementation or testing.

Approach: Preserve an allocation-free visibility path and guard the cached Android.Graphics.Rect peer's JNI liveness before calling GetGlobalVisibleRect.

Prior approach avoided: The PR deletes the cached AppBarLiftState.VisibleRect and creates/disposes a fresh Rect for every visibility check. Candidate 1 instead targeted peer validity without adding a Java allocation to the scroll-change hot path.

Mechanism-level difference: The PR avoids stale peers by replacing the wrapper on every call. Candidate 1 would retain reuse but prevent an invalid JNI handle from crossing the Java boundary, short-circuiting or repairing state before GetGlobalVisibleRect.

Files changed: None.

Diff: Empty.

Test results: Not run. The primary test and the three directly related AppBar regressions were all blocked before execution.

Failure analysis: EstablishBrokenBaseline.ps1 rejected the extensive pre-existing dirty worktree and did not create .github/.baseline-state.json. The try-fix safety contract prohibits tracked edits or candidate testing without that baseline state. The required final restore command ran and reported No baseline state found / Restored False; no attempt edits were made.

Self-review: 0 findings because there was no candidate diff.

Artifacts: CustomAgentLogsTmp/PRState/38636/PRAgent/try-fix/attempt-1/ and CustomAgentLogsTmp/PRState/38636/PRAgent/try-fix-1/content.md.

Candidate 2 — Managed Coordinate Visibility

Model: gpt-5.6-sol

Result: Blocked before implementation or testing.

Approach: Replace GetGlobalVisibleRect(Rect) with a managed numeric bounds calculation: obtain screen coordinates for the view and clipping ancestors, intersect primitive bounds, and store reusable integer buffers in AppBarLiftState.

Prior approaches avoided: The PR's per-call creation/disposal of a Java Rect and Candidate 1's planned cached-peer JNI-liveness guard were both avoided.

Mechanism-level difference: Both prior mechanisms continue calling GetGlobalVisibleRect(Rect) and differ only in how they keep its Java argument valid. Candidate 2 would remove the Java Rect peer from the failure chain entirely, deriving visibility from primitive coordinates and managed numeric intersections so GC cannot produce the reported null JNI argument.

Files changed: None.

Diff: Empty.

Test results: Not run. AppBarLiftTargetCheckSurvivesGarbageCollection, AppBarLiftTargetSetToScrollViewOnAttach, AppBarLiftTargetClearedOnVisibilityGone, and AppBarLiftTargetNotSetWhenNoAppBarLayout were all blocked before execution.

Failure analysis: The mandatory baseline command again rejected the pre-existing dirty worktree, emitted no Baseline established marker, and created no .github/.baseline-state.json. Without a RevertedFiles allow-list, implementation and testing were prohibited. The exact final restore command reported No baseline state found / Restored False; no attempt edits were made.

Self-review: 0 findings because there was no candidate diff. The proposed clipping semantics and performance therefore remain unvalidated.

Artifacts: CustomAgentLogsTmp/PRState/38636/PRAgent/try-fix/attempt-2/ and CustomAgentLogsTmp/PRState/38636/PRAgent/try-fix-2/content.md.

Aggregate Outcome

Two bounded, mechanism-distinct candidates were generated, but neither could be implemented or tested safely. The blocker is environmental rather than a candidate test failure: the try-fix baseline script requires a clean worktree, while this workspace contains extensive pre-existing tracked changes outside PR #38636. No production or test code was modified by STEP 5a.


🏁 Report — Final Recommendation

⚠️ Final Recommendation: REQUEST CHANGES

Winner: pr (best available candidate, but not merge-ready).

The raw PR is the only implemented candidate whose fix-side targeted device test completed successfully. It therefore ranks above pr-plus-reviewer, whose one allowed validation failed to compile, and above both STEP 5a candidates, which were blocked before implementation or testing. Approval is nevertheless prohibited: the trusted Gate failed because the submitted regression test passed on the base implementation as well as the fix, and the expert reviewer classified that non-discriminating coverage as a blocking issue.

Comparative Ranking

Rank Candidate Implementation Validation evidence Review assessment
1 pr Replaces the per-view cached Android.Graphics.Rect with a call-scoped, deterministically disposed peer for each visibility probe. Fix-side test passed in 395s. Gate failed because the same test also passed on base in the initial run and two confirmations; UseMaterial3 was unset in the Gate environment and the API 30 emulator did not reproduce the field race. Plausible localized crash mitigation, but the regression test does not prove the fix and per-scroll Java-peer allocation remains a performance tradeoff.
2 pr-plus-reviewer Keeps the PR production fix and adds deterministic cached-peer fault injection, GC-worker synchronization, and bounded waits to the test. Required one-shot validation failed during compilation with CS0234 at the new helper's Android.Views.View parameter; no tests ran. No correction or retest was permitted. The test design directly addresses the expert finding, but a non-compiling candidate cannot outrank the raw PR's completed fix-side run.
3 try-fix-1 Planned an allocation-free JNI-peer-liveness guard while retaining the cached Rect. No code was produced. Blocked before edits and testing because the STEP 5a baseline could not be established in the dirty raw worktree. Conceptually avoids hot-path allocation, but checking or repairing peer liveness was not implemented and would still need proof against a check-to-call race.
4 try-fix-2 Planned managed coordinate/clipping intersection without passing a Java Rect. No code was produced. Blocked before edits and testing for the same baseline-safety reason. Removes the suspect peer from the failure chain, but matching GetGlobalVisibleRect clipping semantics and performance is unproven and carries the largest behavioral risk.

Why pr Wins

  1. It directly removes reuse of the Java peer implicated by the field stack trace while preserving AppBar target-selection and lifecycle behavior.
  2. Its fix-side targeted test completed successfully, whereas pr-plus-reviewer failed to compile and both try-fix-* candidates have no executable diff or test evidence.
  3. The alternative mechanisms are only proposals. Neither establishes safer JNI behavior, equivalent clipping semantics, or regression compatibility.

This is a relative winner, not an approval. The submitted PR still needs a deterministic regression test that fails against the cached-peer implementation and passes against the call-scoped implementation. The expert review also records the per-scroll allocation cost and unbounded GC-worker shutdown; the latter should be corrected in the submitted test.

Expert and Gate Reconciliation

  • Expert verdict: NEEDS_CHANGES; one major inline finding was persisted for the non-discriminating regression test.
  • Trusted Gate: ❌ FAILED; base and fix both passed the new test, so Gate does not permit approval.
  • Regression cross-reference: CLEAN; no overlap with recent labeled bug-fix removals.
  • Required checks: gh pr checks --required was unavailable because GitHub CLI authentication is absent. Anonymous check-run data showed successful main-build jobs, but it does not establish the required-check set and cannot override the failed trusted Gate.

Required Change

Keep the production mitigation unless a separately validated lower-allocation mechanism is supplied, but replace or strengthen the test with deterministic peer invalidation/fault injection and bounded worker waits. Run the four prescribed Android AppBar methods with UseMaterial3=true; approval requires the strengthened test to fail against base, pass against the fix, and preserve the three adjacent AppBar behaviors.


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

@MauiBot MauiBot added s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-gate-failed AI could not verify tests catch the bug s/agent-fix-pr-picked AI could not beat the PR fix - PR is the best among all candidates s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review) and removed s/agent-review-in-progress AI review is currently running for this PR labels Sep 17, 2026
@kubaflo
kubaflo changed the base branch from main to inflight/current September 17, 2026 18:27
@kubaflo
kubaflo merged commit 3b38b29 into inflight/current Sep 17, 2026
31 of 41 checks passed
@kubaflo
kubaflo deleted the simonrozsival-investigate-android-appbar-lift-crash branch September 17, 2026 18:29
@github-actions github-actions Bot added this to the .NET 10 SR12 milestone Sep 17, 2026
kubaflo pushed a commit that referenced this pull request Sep 18, 2026
<!-- 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!

Fixes #38620.

Material 3 AppBar lift-target visibility checks retained an
`Android.Graphics.Rect` Java peer in per-view state and reused it across
GC cycles. Under GC pressure, the JNI argument could resolve to null and
crash inside Android's `View.getGlobalVisibleRect` implementation.

This change uses a call-scoped, deterministically disposed `Rect` for
each visibility check. The underlying interop race may belong to the
`dotnet/android` GC bridge, but avoiding the retained peer is the
smallest safe MAUI servicing fix.

- Stop caching the visibility `Rect` in `AppBarLiftState`.
- Centralize the visibility probe in `IsOnScreen` using a call-scoped
`Rect`.
- Add an Android Material 3 device regression test that repeatedly runs
the AppBar visibility check during concurrent garbage collection.

- Built `Core.DeviceTests` for Android with `UseMaterial3=true`.
- The new `AppBarLiftTargetCheckSurvivesGarbageCollection` regression
test passes on the Android emulator.
- The broader ScrollView category has two pre-existing AppBar assertions
that fail in the zero-sized device-test host; the new regression test
itself passes.

---------
kubaflo pushed a commit that referenced this pull request Sep 21, 2026
<!-- 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!

Fixes #38620.

Material 3 AppBar lift-target visibility checks retained an
`Android.Graphics.Rect` Java peer in per-view state and reused it across
GC cycles. Under GC pressure, the JNI argument could resolve to null and
crash inside Android's `View.getGlobalVisibleRect` implementation.

This change uses a call-scoped, deterministically disposed `Rect` for
each visibility check. The underlying interop race may belong to the
`dotnet/android` GC bridge, but avoiding the retained peer is the
smallest safe MAUI servicing fix.

- Stop caching the visibility `Rect` in `AppBarLiftState`.
- Centralize the visibility probe in `IsOnScreen` using a call-scoped
`Rect`.
- Add an Android Material 3 device regression test that repeatedly runs
the AppBar visibility check during concurrent garbage collection.

- Built `Core.DeviceTests` for Android with `UseMaterial3=true`.
- The new `AppBarLiftTargetCheckSurvivesGarbageCollection` regression
test passes on the Android emulator.
- The broader ScrollView category has two pre-existing AppBar assertions
that fail in the zero-sized device-test host; the new regression test
itself passes.

---------
kubaflo pushed a commit that referenced this pull request Sep 27, 2026
<!-- 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!

Fixes #38620.

Material 3 AppBar lift-target visibility checks retained an
`Android.Graphics.Rect` Java peer in per-view state and reused it across
GC cycles. Under GC pressure, the JNI argument could resolve to null and
crash inside Android's `View.getGlobalVisibleRect` implementation.

This change uses a call-scoped, deterministically disposed `Rect` for
each visibility check. The underlying interop race may belong to the
`dotnet/android` GC bridge, but avoiding the retained peer is the
smallest safe MAUI servicing fix.

- Stop caching the visibility `Rect` in `AppBarLiftState`.
- Centralize the visibility probe in `IsOnScreen` using a call-scoped
`Rect`.
- Add an Android Material 3 device regression test that repeatedly runs
the AppBar visibility check during concurrent garbage collection.

- Built `Core.DeviceTests` for Android with `UseMaterial3=true`.
- The new `AppBarLiftTargetCheckSurvivesGarbageCollection` regression
test passes on the Android emulator.
- The broader ScrollView category has two pre-existing AppBar assertions
that fail in the zero-sized device-test host; the new regression test
itself passes.

---------
kubaflo pushed a commit that referenced this pull request Sep 27, 2026
<!-- 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!

Fixes #38620.

Material 3 AppBar lift-target visibility checks retained an
`Android.Graphics.Rect` Java peer in per-view state and reused it across
GC cycles. Under GC pressure, the JNI argument could resolve to null and
crash inside Android's `View.getGlobalVisibleRect` implementation.

This change uses a call-scoped, deterministically disposed `Rect` for
each visibility check. The underlying interop race may belong to the
`dotnet/android` GC bridge, but avoiding the retained peer is the
smallest safe MAUI servicing fix.

- Stop caching the visibility `Rect` in `AppBarLiftState`.
- Centralize the visibility probe in `IsOnScreen` using a call-scoped
`Rect`.
- Add an Android Material 3 device regression test that repeatedly runs
the AppBar visibility check during concurrent garbage collection.

- Built `Core.DeviceTests` for Android with `UseMaterial3=true`.
- The new `AppBarLiftTargetCheckSurvivesGarbageCollection` regression
test passes on the Android emulator.
- The broader ScrollView category has two pre-existing AppBar assertions
that fail in the zero-sized device-test host; the new regression test
itself passes.

---------
kubaflo pushed a commit that referenced this pull request Oct 3, 2026
<!-- 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!

Fixes #38620.

Material 3 AppBar lift-target visibility checks retained an
`Android.Graphics.Rect` Java peer in per-view state and reused it across
GC cycles. Under GC pressure, the JNI argument could resolve to null and
crash inside Android's `View.getGlobalVisibleRect` implementation.

This change uses a call-scoped, deterministically disposed `Rect` for
each visibility check. The underlying interop race may belong to the
`dotnet/android` GC bridge, but avoiding the retained peer is the
smallest safe MAUI servicing fix.

- Stop caching the visibility `Rect` in `AppBarLiftState`.
- Centralize the visibility probe in `IsOnScreen` using a call-scoped
`Rect`.
- Add an Android Material 3 device regression test that repeatedly runs
the AppBar visibility check during concurrent garbage collection.

- Built `Core.DeviceTests` for Android with `UseMaterial3=true`.
- The new `AppBarLiftTargetCheckSurvivesGarbageCollection` regression
test passes on the Android emulator.
- The broader ScrollView category has two pre-existing AppBar assertions
that fail in the zero-sized device-test host; the new regression test
itself passes.

---------
kubaflo pushed a commit that referenced this pull request Oct 3, 2026
<!-- 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!

Fixes #38620.

Material 3 AppBar lift-target visibility checks retained an
`Android.Graphics.Rect` Java peer in per-view state and reused it across
GC cycles. Under GC pressure, the JNI argument could resolve to null and
crash inside Android's `View.getGlobalVisibleRect` implementation.

This change uses a call-scoped, deterministically disposed `Rect` for
each visibility check. The underlying interop race may belong to the
`dotnet/android` GC bridge, but avoiding the retained peer is the
smallest safe MAUI servicing fix.

- Stop caching the visibility `Rect` in `AppBarLiftState`.
- Centralize the visibility probe in `IsOnScreen` using a call-scoped
`Rect`.
- Add an Android Material 3 device regression test that repeatedly runs
the AppBar visibility check during concurrent garbage collection.

- Built `Core.DeviceTests` for Android with `UseMaterial3=true`.
- The new `AppBarLiftTargetCheckSurvivesGarbageCollection` regression
test passes on the Android emulator.
- The broader ScrollView category has two pre-existing AppBar assertions
that fail in the zero-sized device-test host; the new regression test
itself passes.

---------
kubaflo pushed a commit that referenced this pull request Oct 6, 2026
<!-- 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!

Fixes #38620.

Material 3 AppBar lift-target visibility checks retained an
`Android.Graphics.Rect` Java peer in per-view state and reused it across
GC cycles. Under GC pressure, the JNI argument could resolve to null and
crash inside Android's `View.getGlobalVisibleRect` implementation.

This change uses a call-scoped, deterministically disposed `Rect` for
each visibility check. The underlying interop race may belong to the
`dotnet/android` GC bridge, but avoiding the retained peer is the
smallest safe MAUI servicing fix.

- Stop caching the visibility `Rect` in `AppBarLiftState`.
- Centralize the visibility probe in `IsOnScreen` using a call-scoped
`Rect`.
- Add an Android Material 3 device regression test that repeatedly runs
the AppBar visibility check during concurrent garbage collection.

- Built `Core.DeviceTests` for Android with `UseMaterial3=true`.
- The new `AppBarLiftTargetCheckSurvivesGarbageCollection` regression
test passes on the Android emulator.
- The broader ScrollView category has two pre-existing AppBar assertions
that fail in the zero-sized device-test host; the new regression test
itself passes.

---------
kubaflo pushed a commit that referenced this pull request Oct 6, 2026
<!-- 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!

Fixes #38620.

Material 3 AppBar lift-target visibility checks retained an
`Android.Graphics.Rect` Java peer in per-view state and reused it across
GC cycles. Under GC pressure, the JNI argument could resolve to null and
crash inside Android's `View.getGlobalVisibleRect` implementation.

This change uses a call-scoped, deterministically disposed `Rect` for
each visibility check. The underlying interop race may belong to the
`dotnet/android` GC bridge, but avoiding the retained peer is the
smallest safe MAUI servicing fix.

- Stop caching the visibility `Rect` in `AppBarLiftState`.
- Centralize the visibility probe in `IsOnScreen` using a call-scoped
`Rect`.
- Add an Android Material 3 device regression test that repeatedly runs
the AppBar visibility check during concurrent garbage collection.

- Built `Core.DeviceTests` for Android with `UseMaterial3=true`.
- The new `AppBarLiftTargetCheckSurvivesGarbageCollection` regression
test passes on the Android emulator.
- The broader ScrollView category has two pre-existing AppBar assertions
that fail in the zero-sized device-test host; the new regression test
itself passes.

---------
kubaflo pushed a commit that referenced this pull request Oct 13, 2026
<!-- 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!

Fixes #38620.

Material 3 AppBar lift-target visibility checks retained an
`Android.Graphics.Rect` Java peer in per-view state and reused it across
GC cycles. Under GC pressure, the JNI argument could resolve to null and
crash inside Android's `View.getGlobalVisibleRect` implementation.

This change uses a call-scoped, deterministically disposed `Rect` for
each visibility check. The underlying interop race may belong to the
`dotnet/android` GC bridge, but avoiding the retained peer is the
smallest safe MAUI servicing fix.

- Stop caching the visibility `Rect` in `AppBarLiftState`.
- Centralize the visibility probe in `IsOnScreen` using a call-scoped
`Rect`.
- Add an Android Material 3 device regression test that repeatedly runs
the AppBar visibility check during concurrent garbage collection.

- Built `Core.DeviceTests` for Android with `UseMaterial3=true`.
- The new `AppBarLiftTargetCheckSurvivesGarbageCollection` regression
test passes on the Android emulator.
- The broader ScrollView category has two pre-existing AppBar assertions
that fail in the zero-sized device-test host; the new regression test
itself passes.

---------
kubaflo pushed a commit that referenced this pull request Oct 13, 2026
<!-- 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!

Fixes #38620.

Material 3 AppBar lift-target visibility checks retained an
`Android.Graphics.Rect` Java peer in per-view state and reused it across
GC cycles. Under GC pressure, the JNI argument could resolve to null and
crash inside Android's `View.getGlobalVisibleRect` implementation.

This change uses a call-scoped, deterministically disposed `Rect` for
each visibility check. The underlying interop race may belong to the
`dotnet/android` GC bridge, but avoiding the retained peer is the
smallest safe MAUI servicing fix.

- Stop caching the visibility `Rect` in `AppBarLiftState`.
- Centralize the visibility probe in `IsOnScreen` using a call-scoped
`Rect`.
- Add an Android Material 3 device regression test that repeatedly runs
the AppBar visibility check during concurrent garbage collection.

- Built `Core.DeviceTests` for Android with `UseMaterial3=true`.
- The new `AppBarLiftTargetCheckSurvivesGarbageCollection` regression
test passes on the Android emulator.
- The broader ScrollView category has two pre-existing AppBar assertions
that fail in the zero-sized device-test host; the new regression test
itself passes.

---------
kubaflo pushed a commit that referenced this pull request Oct 14, 2026
<!-- 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!

Fixes #38620.

Material 3 AppBar lift-target visibility checks retained an
`Android.Graphics.Rect` Java peer in per-view state and reused it across
GC cycles. Under GC pressure, the JNI argument could resolve to null and
crash inside Android's `View.getGlobalVisibleRect` implementation.

This change uses a call-scoped, deterministically disposed `Rect` for
each visibility check. The underlying interop race may belong to the
`dotnet/android` GC bridge, but avoiding the retained peer is the
smallest safe MAUI servicing fix.

- Stop caching the visibility `Rect` in `AppBarLiftState`.
- Centralize the visibility probe in `IsOnScreen` using a call-scoped
`Rect`.
- Add an Android Material 3 device regression test that repeatedly runs
the AppBar visibility check during concurrent garbage collection.

- Built `Core.DeviceTests` for Android with `UseMaterial3=true`.
- The new `AppBarLiftTargetCheckSurvivesGarbageCollection` regression
test passes on the Android emulator.
- The broader ScrollView category has two pre-existing AppBar assertions
that fail in the zero-sized device-test host; the new regression test
itself passes.

---------
kubaflo pushed a commit that referenced this pull request Oct 14, 2026
<!-- 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!

Fixes #38620.

Material 3 AppBar lift-target visibility checks retained an
`Android.Graphics.Rect` Java peer in per-view state and reused it across
GC cycles. Under GC pressure, the JNI argument could resolve to null and
crash inside Android's `View.getGlobalVisibleRect` implementation.

This change uses a call-scoped, deterministically disposed `Rect` for
each visibility check. The underlying interop race may belong to the
`dotnet/android` GC bridge, but avoiding the retained peer is the
smallest safe MAUI servicing fix.

- Stop caching the visibility `Rect` in `AppBarLiftState`.
- Centralize the visibility probe in `IsOnScreen` using a call-scoped
`Rect`.
- Add an Android Material 3 device regression test that repeatedly runs
the AppBar visibility check during concurrent garbage collection.

- Built `Core.DeviceTests` for Android with `UseMaterial3=true`.
- The new `AppBarLiftTargetCheckSurvivesGarbageCollection` regression
test passes on the Android emulator.
- The broader ScrollView category has two pre-existing AppBar assertions
that fail in the zero-sized device-test host; the new regression test
itself passes.

---------
@github-actions github-actions Bot locked and limited conversation to collaborators Oct 18, 2026

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — 7d659a13 Deployed Sep 17, 2026 by simonrozsival via conclusion #1948
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

platform/android s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-fix-pr-picked AI could not beat the PR fix - PR is the best among all candidates s/agent-gate-failed AI could not verify tests catch the bug s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Android] Material 3 - TrySetAppBarLiftTargetIfOnScreen might throw java.lang.NullPointerException

9 participants