Skip to content

[Android] Fix device-test teardown racing native peer finalization - #40801

Merged
kubaflo merged 1 commit into
mainfrom
kubaflo-fix-android-renders-to-image-npe
Nov 29, 2026
Merged

kubaflo merged 1 commit into
mainfrom
kubaflo-fix-android-renders-to-image-npe

Conversation

@kubaflo

@kubaflo kubaflo commented Nov 29, 2026

Copy link
Copy Markdown
Contributor

Agent assessment

Assessed head: f1c3419d9f6f0ed18b69f7cc83189797751fcfce

Change confidence: High

  • ↑ Fixture-only change; both tracked objects remain weakly owned, and recovered Android peers stay alive through disconnect.
  • ↑ Ten fixed runs and four restored runs passed; registration still captures partially initialized handlers.
  • ↓ The complete CI/platform matrix has not yet validated this head.

Diagnosis confidence: High

  • ↑ Instrumentation captured a live SwipeView Java handle changing from 32930 to 0 during focus-listener removal, before the accessibility-delegate lookup.
  • ↑ Reverting only the fixture fix immediately reproduced the original image-test NPE.
  • ↓ The precise finalizer interleaving is runtime-dependent.

Evidence fit: High

  • ↑ Native device TRX verifies the same five affected fixtures and the original accessibility NPE, including image-rendering failures.
  • ↑ Baseline → fixed → reverted → restored execution was performed on the same emulator and SDK.
  • ↓ Local execution used Android API 36/arm64; CI uses API 33/Linux x64. These are selected fixtures, not the entire Core suite.

Note

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

Target Branch

This PR is for Initial base
New features, API changes, or .NET 12 work (including .NET 12 fixes) main
.NET 11 servicing fixes net11, for review
Older servicing, release integration, infrastructure, or documentation The branch designated for that work

This fixes the .NET 12 native device-test fixture on main.

For .NET 11 fixes, only a maintainer retargets the approved PR to the active
inflight lane and merges it after CI validates that final base. Do not merge
individual fixes directly into net11; agents must not retarget or merge.

Description of Change

The weak-handler teardown introduced in #40661 can recover a handler while its Android platform peer is already finalizing. Handle != IntPtr.Zero does not rule out queued finalization: the handle can disappear during focus-listener removal, causing ViewCompat.GetAccessibilityDelegate to receive a JNI null view.

Track the initialized platform view through its own short weak reference. Android teardown recovers that reference separately, skips peers that are already finalizing/disposed, and uses GC.KeepAlive through the complete handler disconnect. This preserves collection assertions' weak ownership instead of retaining every handler/view until teardown.

Registration order and cleanup of partially initialized handlers are preserved. No framework/product code changes are included.

Rejected approach: A product-only handle recheck before the accessibility lookup stopped that NPE but merely exposed ObjectDisposedException in subsequent Border/ContentView RemoveAllViews cleanup (three failures across two of ten runs). Avoid moving the guard between individual native calls; the fixture must not disconnect an already-finalizing peer.

Validation

Local: macOS arm64, pinned SDK 12.0.100-alpha.1.26523.103, CoreCLR, Release, Android API 36 arm64 emulator only. CI's API 33/Linux x64 environment remains a validation gap.

All counted runs used the same five fixtures: SwipeView, Border, ContentView, Slider and ShapeView. Fresh native TRX reports were checked for unique run identities, exact fixture isolation, and genuine image theory results.

Revision Runs Result
Original fixture 7 1 red run, 3 original accessibility NPEs; 2,510 passed, 84 skipped
Peer-lifetime fix 10 0 failures; 3,590 passed, 120 skipped; all 50 PNG and 50 JPEG rows passed
Fix reverted 1 1 original accessibility NPE in ContentView JPEG rendering; 358 passed, 12 skipped
Fix restored 4 0 failures; 1,436 passed, 48 skipped

Commands and results:

  • dotnet build Microsoft.Maui.BuildTasks.slnf --configuration Release --verbosity quiet — passed, zero warnings/errors.
  • dotnet format Microsoft.Maui.sln --no-restore --include src/Core/tests/DeviceTests.Shared/HandlerTests/HandlerTestBasement.cs --exclude Templates/src --exclude-diagnostics CA1822 — passed (exit 0; workspace-loading warnings).
  • Native selection/build/run command below — passed with the fix and failed with the original/reverted fixture, as counted above:
pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 \
  -Project Core -Platform android -DeviceUdid emulator-5580 \
  -IncludeClasses 'Microsoft.Maui.DeviceTests.SwipeViewHandlerTests,Microsoft.Maui.DeviceTests.BorderHandlerTests,Microsoft.Maui.DeviceTests.Handlers.ContentView.ContentViewTests,Microsoft.Maui.DeviceTests.SliderHandlerTests,Microsoft.Maui.DeviceTests.ShapeViewHandlerTests' \
  -RepoRoot "$PWD" -DotnetPath "$DOTNET_ROOT/dotnet" \
  -OutputDirectory artifacts/android-npe/restored-final -Timeout 00:15:00
  • Subsequent repetitions reused that compiled selection through the native command below — passed/failed according to the revision table. The device's original testResults.trx was pulled and checked independently of the host report.
dotnet test --project src/Core/tests/DeviceTests/Core.DeviceTests.csproj \
  --configuration Release --framework net12.0-android --no-build --no-restore \
  -p:RuntimeIdentifier=android-arm64 --device emulator-5580 --report-trx \
  --results-directory "$PWD/artifacts/android-npe/peer-fixed-series-$run"

Existing image/transform tests reproduce this shared teardown failure; no new GC-timing-sensitive test was added. Full PR CI is pending.

Issues Fixed

CI-discovered regression; no separate issue is linked. Relates to #40661.

Failure evidence: main device-test build 1704155, Android Core log 659.

Let AI finish this PR

  • Let the MAUI agent address review feedback and fix remaining issues on this PR. Maintainers still decide whether it is merged. For PRs from forks, the agent opens a follow-up PR that keeps your commits.

Track each initialized platform view through its own short weak reference and keep recovered peers alive through Android fixture teardown. Avoid disconnecting handlers whose native peer is already finalizing without retaining views during collection assertions.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 29, 2026 11:15
@kubaflo

kubaflo commented Nov 29, 2026

Copy link
Copy Markdown
Contributor Author

@dalexsoto stamp

@kubaflo

This comment has been minimized.

@kubaflo
kubaflo temporarily deployed to copilot-pat-pool November 29, 2026 11:16 — with GitHub Actions Inactive
@github-actions

This comment has been minimized.

@azure-pipelines

This comment has been minimized.

@azure-pipelines

This comment has been minimized.

@kubaflo

This comment has been minimized.

@azure-pipelines

This comment has been minimized.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

The teardown weak reference still targets the original platform view after handler reconnection, risking skipped cleanup or keeping the wrong peer alive during disconnect.

1 open issue
What changed in this PR

This PR addresses an Android device-test teardown race introduced by the weak-handler tracking in #40661. It changes shared test infrastructure only; no framework/product code is modified.

Changes:

  • Tracks initialized platform views through separate short weak references.
  • Skips unavailable or disposed Android peers and keeps recovered peers alive through disconnect.
  • Preserves early handler registration and captures the platform view even when initialization throws.
File Description
src/​Core/​tests/​DeviceTests.Shared/​HandlerTests/​HandlerTestBasement.cs Adds weak platform-view tracking and Android peer-lifetime protection during fixture teardown.

Review effort: Balanced

Comment on lines +348 to 350
if (!platformViewReference.TryGetTarget(out var platformView) ||
platformView is global::Java.Lang.Object nativeView && nativeView.Handle == IntPtr.Zero)
continue;

@dalexsoto dalexsoto left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Stamping as requested by @kubaflo; no code review performed.

@kubaflo

kubaflo commented Nov 29, 2026

Copy link
Copy Markdown
Contributor Author

CI evidence (maui-pr-devicetests 1704198 at f1c3419): all Android jobs passed, including the API 33 core job where "View Renders To Image" hit the NPE on main (build 1704155). This is one green run; the NPE was intermittent on main (3 of 4 runs), so it is supporting evidence, not proof. The remaining failures are Windows-only and unrelated to this PR: [Button] ReplacingVirtualViewUpdatesLayoutAndReleasesOldPress (fixed by #40800) and the NavigationPage SettingTitleIconImageSourceDoesntCrash host crash 0xDEAD (fails on main too; under investigation).

kubaflo added a commit that referenced this pull request Nov 29, 2026
<!-- copilot-assessment:v1 -->
### Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: `4b5901591c54bd76752e588ac5582a05707a3207`

| Dimension | Assessment | Rationale |
|---|---|---|
| Change confidence | 7.5/10 | ↑ PR devicetests
[1704250](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1704250):
iOS controls General 1493 total, 0 failed; log 303 shows iPhone 11 Pro /
iOS 27.2 selected.<br>↑ Local simulator runs: 14 scoped tests red → fix
green → reverted red → restored green.<br>↓ One green CI run of an
intermittent failure; other device-test suites not run locally. |
| Diagnosis confidence | 6/10 | ↑ Locally, the iPhone Duo profile
reproduces the failures without any predecessor test.<br>↓ main's device
step does not log the selected profile, so no CI log shows that failing
builds 1704212/1704247 used iPhone Duo. |
| Evidence fit | 6/10 | ↑ The same 17-test cluster fails intermittently
on unrelated PRs with the main tree, consistent with nondeterministic
device selection.<br>↓ Local Duo runs used iOS 27.1 and standard-phone
runs iOS 26.0; CI uses iOS 27.2, so this isn't a same-runtime
comparison. |
<!-- /copilot-assessment -->

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

<!--
Open .NET 11 fix PRs against net11 for review; target main for
next-major features.
After approval, a maintainer manually retargets the fix PR to the active
inflight
branch and merges it directly there. Do not merge individual fixes into
net11.
Bots must not retarget or merge. Candidate integration into net11 and
release/*
changes are separate, explicitly coordinated release work.
-->

### Target Branch

| This PR is for | Initial base |
| --- | --- |
| New features, API changes, or .NET 12 work (including .NET 12 fixes) |
`main` |
| .NET 11 servicing fixes | `net11`, for review |
| Older servicing, release integration, infrastructure, or documentation
| The branch designated for that work |

- [x] I selected the applicable base branch using the [contribution
guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting).

For .NET 11 fixes, only a maintainer retargets the approved PR to the
active
inflight lane and merges it after CI validates that final base. Do not
merge
individual fixes directly into `net11`; agents must not retarget or
merge.

### Description of Change

<!-- Enter description of the fix in this section -->

The apparent intermittent iOS General cascade is **simulator-profile
drift, not a demonstrated TabbedPage state leak**.

The native device-test migration prefers iPhone 11 Pro / iPhone 16 but
falls back to any compatible phone on the newest installed runtime. A
device-specific runtime supporting only **iPhone Duo** therefore
silently changes this standard-phone lane to an unfolded, regular-width
navigation environment. The More-tab and native back-button assumptions
no longer hold; the tab-bar layer-removal assertion and ScrollView
geometry assertion also fail.

Select the newest installed runtime **together with a supported
standard-phone profile**, retaining the existing iPhone 11 Pro / iPhone
16 preferences. Do not fall back to an arbitrary device profile.
Explicit version/major requests remain within their requested version
range; when no supported standard-phone profile exists, report a
provisioning error instead of substituting another OS.

Log and persist the runtime identifier, version, build, and device type
in `device.json`. No product code, test assertion, skip, or category
exclusion changes.

**Coverage boundary:** a device-specific Duo runtime is not a
replacement for standard-phone coverage. This does not add foldable
coverage; that needs a separately configured lane. For `latest`, the
selected standard-phone runtime can be older than an installed Duo-only
runtime.

#### CI evidence

Actual simulator logs in the General job's published `DeviceTests`
artifact show:

| Build | General job | Device | Runtime |
| --- | --- | --- | --- |
|
[1704247](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1704247)
| Failed, 17 victims | iPhone Duo / iPhone19,4 | iOS 27.2 / 24B91016s |
|
[1704240](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1704240)
| Passed | iPhone 11 Pro / iPhone12,3 | iOS 27.2 / 24B8117 |
|
[1704155](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1704155)
| Passed on main | iPhone 11 Pro / iPhone12,3 | iOS 27.2 / 24B8117 |

Each has 1,493 `TEST_START` events with different randomized order. In
1704247, the first failure starts at 14:32:39 UTC:
`BarBackgroundTransitionRemovesGradientAndRestoresEffect(True)`, with
`ArgumentNullException: collection`. The root-replacement tests do not
begin until 14:40:12 UTC, so they cannot explain that first failure. The
raw test-step log is 749 for 1704247, 736 for 1704240, and 781 for
1704155. The previously reported build 1704212/log 727 was no longer
readable; no claims are made about its ordering.

Before implementation, searched open and recently merged PRs across all
bases for the test names, More-navigation mechanisms,
`Start-TestDevice`, device-specific runtime selection, and iPhone Duo.
Inspected #40656, #40755, and #40766. The open siblings
#40799/#40800/#40801/#40802/#40805/#40796 do not implement this native
standard-phone runtime/profile selection correction.

#### Local causal validation

All results below come from **fresh native MTP TRX**, verified by the
existing runner for exact class/method isolation. Only owned iOS
simulators were used.

| Phase | Profile / runtime | Passed | Failed |
| --- | --- | --- | --- |
| Original | Duo / iOS 27.1, 24A94232 | 0 | 14 |
| Fixed | iPhone 11 Pro / iOS 26.0, 23A343 | 14 | 0 |
| Fix reverted exactly to main | Duo / iOS 27.1, 24A94232 | 0 | 14 |
| Fix restored | iPhone 11 Pro / iOS 26.0, 23A343 | 14 | 0 |

The 14 scoped victims cover all six tab-gradient variants, all six
failing More-transition variants, ScrollView, and the base
NavigationPage back-button variant. They reproduce **without running any
potential leaking predecessor**. Local exception messages match the CI
cluster, including `collection`, missing native back button, absent
shared-element flight, premature push completion, and navigation
timeout.

Commands, all from an isolated worktree off `origin/main` at
`1344d16421`:

```bash
export DOTNET_ROOT=/Users/kubaflo/Projects/copilot-worktrees/maui/kubaflo-catalyst-cascade/.dotnet
export PATH="$DOTNET_ROOT:$PATH"
# This installed preview SDK packages mlaunch under tools/lib, while its default property points at tools/bin.
export MlaunchPath="$DOTNET_ROOT/packs/Microsoft.iOS.Sdk.net12.0_27.1/27.1.12089-net12-p1/tools/lib/mlaunch/mlaunch.app/Contents/MacOS/mlaunch"
export RelativeMlaunchPath=packs/Microsoft.iOS.Sdk.net12.0_27.1/27.1.12089-net12-p1/tools/lib/mlaunch/mlaunch.app/Contents/MacOS/mlaunch
```

Preparation — **passed**, zero warnings/errors:

```bash
dotnet build Microsoft.Maui.BuildTasks.slnf --disable-build-servers -v:q
```

Causal run command — original used `-iOSVersion 27.1`;
fixed/reverted/restored used `-iOSVersion latest`, which selects that
same Duo runtime with the original selector. Results are listed in the
table above:

```bash
pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 \
  -Project Controls -Platform ios -iOSVersion latest \
  -IncludeClasses 'Microsoft.Maui.DeviceTests.TabbedPageTests,Microsoft.Maui.DeviceTests.TabbedPageTests_TabbedViewHandler,Microsoft.Maui.DeviceTests.TabbedPageNavigationHandlerTests,Microsoft.Maui.DeviceTests.NavigationPageTests,Microsoft.Maui.DeviceTests.PageTransitionsTests,Microsoft.Maui.DeviceTests.ScrollViewTests' \
  -IncludeMethods 'BarBackgroundTransitionRemovesGradientAndRestoresEffect,NavigatingBackViaBackButtonFiresNavigatedEvent,MoreTabNavigationsCompleteAfterTheTransition,MoreTabUnanimatedPushIsRecordedForThePop,MoreTabSharedElementFliesFromTheOverflowRoot,TestContentHorizontalOptionsChanged' \
  -SkipXcodeVersionCheck -Timeout 00:10:00 -DotnetPath "$DOTNET_ROOT/dotnet" \
  -OutputDirectory artifacts/ios-cascade/cluster-restored
```

Final expanded verification includes the three remaining NavigationPage
handler variants — **17 passed / 0 failed / 0 skipped**, covering every
reported victim:

```bash
pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 \
  -Project Controls -Platform ios -iOSVersion latest \
  -IncludeClasses 'Microsoft.Maui.DeviceTests.TabbedPageTests,Microsoft.Maui.DeviceTests.TabbedPageTests_TabbedViewHandler,Microsoft.Maui.DeviceTests.TabbedPageNavigationHandlerTests,Microsoft.Maui.DeviceTests.NavigationPageTests,Microsoft.Maui.DeviceTests.NavigationPageNavigationHandlerTests,Microsoft.Maui.DeviceTests.NavigationPageTests_TabbedViewHandler,Microsoft.Maui.DeviceTests.NavigationPageTests_FlyoutViewHandler,Microsoft.Maui.DeviceTests.PageTransitionsTests,Microsoft.Maui.DeviceTests.ScrollViewTests' \
  -IncludeMethods 'BarBackgroundTransitionRemovesGradientAndRestoresEffect,NavigatingBackViaBackButtonFiresNavigatedEvent,MoreTabNavigationsCompleteAfterTheTransition,MoreTabUnanimatedPushIsRecordedForThePop,MoreTabSharedElementFliesFromTheOverflowRoot,TestContentHorizontalOptionsChanged' \
  -SkipXcodeVersionCheck -Timeout 00:10:00 -DotnetPath "$DOTNET_ROOT/dotnet" \
  -OutputDirectory artifacts/ios-cascade/full-cluster-final
```

Exact-version guard — **passed**: this real invocation rejects the
installed Duo-only 27.1 runtime with the expected provisioning error,
exit 1, without creating a simulator:

```bash
pwsh -NoProfile .github/skills/run-device-tests/scripts/Start-TestDevice.ps1 \
  -Platform ios -ApiVersion 27.1 \
  -ResultsDirectory artifacts/ios-cascade/exact-runtime-rejection \
  -DeviceDirectory artifacts/ios-cascade/exact-runtime-device
```

PowerShell parser validation and `git diff --check` — **passed**. No
pipeline unit/snapshot tests were added. The initial local launch
attempt did not run tests because of the preview SDK's missing
`tools/bin/mlaunch`; only subsequent runs using the explicit valid
launch path are counted. Full repository tests and PR CI have not been
run as validation evidence.

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

The recurrent iOS Controls General cluster in the linked builds; no
unrelated issue-closing reference.

### Let AI finish this PR

- [ ] **Let the MAUI agent address review feedback and fix remaining
issues on this PR.** Maintainers still decide whether it is merged. For
PRs from forks, the agent opens a follow-up PR that keeps your commits.

<!--
Verify the target branch follows the release workflow in
docs/ReleaseBranchWorkflow.md.
Infrastructure and documentation changes should target the branch where
they apply.
-->

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@kubaflo
kubaflo merged commit beb16fe into main Nov 29, 2026
72 of 79 checks passed
@kubaflo
kubaflo deleted the kubaflo-fix-android-renders-to-image-npe branch November 29, 2026 16:39

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — f1c3419d Deployed Nov 29, 2026 by kubaflo via conclusion #3470
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants