Skip to content

[Android] Prevent fragment crashes during Shell and FlyoutPage root replacement - #38214

Merged
kubaflo merged 5 commits into
inflight/currentfrom
kubaflo-android-root-replacement
Sep 5, 2026
Merged

kubaflo merged 5 commits into
inflight/currentfrom
kubaflo-android-root-replacement

Conversation

@kubaflo

@kubaflo kubaflo commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

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!

Root Cause

Android Shell and FlyoutPage create content through asynchronously committed AndroidX fragment transactions. A same-turn Window.Page replacement could detach the outgoing fragment container before those transactions ran, terminating the process with IllegalArgumentException: No view found for id ... ShellItemRenderer.

Skipping cleanup is not safe: the outgoing ContainerView.CurrentView must still be cleared so the replaced MAUI view graph is not retained.

Description of Change

  • Serialize and coalesce navigation-root requests with last-request-wins behavior under reentrancy.
  • Drain committed transactions while the outgoing native root remains attached, including the distinct Activity fragment manager used by compatibility Shell during replacement.
  • Retry boundedly through the Android main looper when AndroidX is already executing transactions.
  • Attach a prepared Window root before committing its content fragment, and explicitly discard superseded roots and newly-created handlers.
  • Preserve current toolbar mappings with identity/version tracking and safe native reparenting.
  • Keep modal disconnects scoped to their owning fragment manager to avoid re-entering Activity-level dismissal transactions.
  • Clear outgoing ContainerView content and release Visual Diagnostics native Activity/view subscriptions during handler teardown.
  • Add Android device regressions for Shell/Flyout root replacement, reentrancy, retries, stale roots and toolbars, nested FlyoutPage hosts, modal teardown, and disconnect/reconnect completion.

What NOT to Do

  • Do not remove ContainerView.CurrentView cleanup to hide the crash; that retains the outgoing MAUI view graph.
  • Do not use MainThread.BeginInvokeOnMainThread for the transaction retry; it can execute inline on the UI thread before AndroidX clears its executing state.
  • Do not drain the Activity fragment manager during scoped modal disconnect; that can re-enter the dismissal transaction already running there.

Empirical Validation

The failure still reproduced on current main on an Android API 34 emulator. The exact stress scenario alternated new Shell and FlyoutPage roots in the same turn and crashed before the fix with the missing fragment-container exception.

After the fix, all 50 iterations completed, the final Shell root was attached, the process remained alive, and logcat contained no fatal exception, missing-view exception, or fragment-manager busy exception.

Final targeted API 34 results:

Category Result
Window 34/34 passed
FlyoutPage 17/17 passed
Modal 44/44 passed

The final Android Controls DeviceTests Release app also builds successfully.

Before fix — reproduced on current main

android-root-replacement-before.mp4

After fix — same 50-iteration stress scenario

android-root-replacement-after.mp4

Issues Fixed

Supersedes #36212. Follow-up to #35372 and #36152.

jonathanpeppers and others added 5 commits September 4, 2026 00:11
<!-- 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

Generalizes the existing Darc-based official release pipeline so it can
publish shipping NuGet packages from allowlisted non-workload
repositories, initially `dotnet/android-libraries`, while preserving the
existing MAUI workload-release path.

- Keeps the existing free-text repository and commit inputs.
- Infers workload behavior for `dotnet/android`, `dotnet/macios`, and
`dotnet/maui`.
- Preserves the existing first-match BAR resolution behavior for all
repositories, then validates the resolved repository and gathers using
the dynamically returned BAR build ID.
- Keeps workload gathering, workload-set promotion, pack-before-manifest
ordering, approvals, and publishing behavior isolated from the
non-workload path.
- Gathers only shipping NuGet assets and rejects malformed packages,
duplicate filenames, duplicate ID/version identities, unexpected
packages, and workload manifests on non-workload releases.
- Supports include/exclude package filters for both workload and
non-workload releases.
- Filters exact ID/version pairs already on NuGet.org during preparation
and again immediately before publishing, preventing reruns and packages
published between those phases from causing HTTP 409 conflicts.
- Supports repeating the same non-workload BAR release after partial
publication: Darc may no longer download assets whose BAR location moved
to NuGet.org, so missing selected assets are accepted only when their
exact identity is confirmed on NuGet.org. Other missing or unavailable
packages fail closed.
- Publishes the exact selected and staged package lists as the
`NuGetReleaseAudit` artifact before manual approval.
- Uses the existing `1ES.PublishNuget@1` task and `nuget.org
(dotnetframework)` service connection, then verifies every expected
package on NuGet.org.
- Supports a non-mutating dry run with `pushPackages: false`.

### Dry-run inputs

```yaml
ghOwner: dotnet
ghRepo: android-libraries
commitHash: <ANDROID_LIBRARIES_COMMIT_WITH_BAR_BUILD>
pushWorkloadSet: false
pushNugetOrg: true
pushPackages: false
```

Queue `dotnet-maui-release` against this PR branch after it appears in
the internal `dotnet-maui` mirror. The run performs BAR resolution,
gathering, package validation/filtering, and audit artifact publication
without promotion or NuGet publishing.

### External setup

Before enabling a real push, release owners must verify that the
existing `nuget.org (dotnetframework)` service connection owns every
package ID in the audit artifact and has sufficient scope/quota.
Android-libraries BAR builds contain per-build deltas rather than the
union of channel assets, so each pending BAR build must be released in
commit order.

### Validation

- [Successful `dotnet/android-libraries` NuGet.org release
run](https://dev.azure.com/dnceng/internal/_build/results?buildId=3063121&view=results):
BAR resolution, gathering, filtering, audit publication, package push,
and NuGet.org verification all succeeded.
- The overall build is `partiallySucceeded` only because 1ES production
branch/source validation reported non-blocking errors for running the
test from this PR branch instead of an approved production branch.
- Focused release pipeline and NuGet availability Pester suites.
- YAML parsing and whitespace validation.

### Issues Fixed

N/A

---------

Copilot-Session: 2933e733-3bed-4524-ae14-f7ad1c7959e6
<!-- 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!

## Summary

The main scanner recovered, but the net11 scanner has failed 13
consecutive scheduled runs since August 29. The two latest failures,
runs 33824526633 and 33757658045, are threat-detection false positives:
the scanner contract requests `## Recommended Action` with concrete
commands while its custom threat detector rejects instructions aimed at
downstream readers.

This changes both scanner twins to emit a declarative `## Investigation
Context` section. Its content is limited to suspected owning areas or
files, relevant evidence, and uncertainty, and explicitly forbids
commands, requests, second-person wording, imperative verbs, and
instructions directed at readers or agents.

Strict threat detection, trusted manifest validation, and publisher
logic remain unchanged. The latest failed net11 manifest independently
passed trusted validation for all 3 pipelines and 5 issue payloads, so
this removes the immediate publication blocker without weakening the
trust boundary.

#38163 and #38165 track related scanner behavior. Earlier failures had
additional recurrence/fingerprint instability causes; those remain
follow-up work and are not claimed as fixed here.

## Tests

- Scanner suites: 413 passed
- CI-fixer transport: 31 passed
- Pinned gh-aw v0.86.2 source-lock parity: passed

Co-authored-by: PureWeen <223556219+Copilot@users.noreply.github.com>
…ctMode UI Test in CI (#38192)

This PR addresses flaky UI test failures in CI and includes updates to
improve rendering and test stability across platforms. The main changes
are as follows:

UI component and test improvements:

* Replaced the `_primarySearchBar` initialization from `SearchBar` to
`UITestSearchBar` and set `IsCursorVisible` to `false` in
`Issue14708.cs`, likely to better control test conditions and prevent
cursor blinking during image verification.

Test verification adjustments:

* Updated the `VerifyScreenshot` call in the landscape search bar test
to use platform-specific cropping parameters, improving the reliability
of visual regression tests by accounting for differences in keyboard and
UI layout between Android and other platforms.

Test case:

- SearchBarLandscapeShowsInlineKeyboardNotExtractMode
…anup (#37278)

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

After PR #35487 corrected `AssertionExtensions.WaitForGC`,
`MauiCALayerAutosizeToSuperLayerBehavior_DoesNotLeak` began failing on
Mac Catalyst for:

- `MauiCALayer`
- `StaticCALayer`
- `StaticCAGradientLayer`
- `StaticCAShapeLayer`

The production layer behavior was not leaking. The test called
`UIView.AttachAndRun` without awaiting its returned task, so `WaitForGC`
could run before `AttachAndRun` removed the view from the native visual
hierarchy in its `finally` block.

### Description of Change

- Changed the `InvokeOnMainThreadAsync` callback in
`MauiCALayerAutosizeToSuperLayerBehavior_DoesNotLeak` to an asynchronous
callback and awaited `view.AttachAndRun(...)` before the GC assertion.
- Re-enabled `MauiCALayerAutosizeToSuperLayerBehavior_DoesNotLeak`.
### Validation Status

- Mac Catalyst: the awaited `AttachAndRun` cleanup was tested.

### Issues Fixed

Fixes #36614

### Platforms Tested

- [ ] Android
- [x] Windows
- [ ] iOS
- [x] Mac Catalyst

| Before | After |
|---|---|
| **Mac Catalyst**<br><img
src="https://github.com/user-attachments/assets/c145e6b2-0823-4e7b-93fa-74c957e701e6"
width="600" height="300"> | **Mac Catalyst**<br><img
src="https://github.com/user-attachments/assets/af942f05-e9b7-436e-97fa-3b212d133c76"
width="600" height="300"> |
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI lite review requested due to automatic review settings September 4, 2026 18:30
@kubaflo
kubaflo temporarily deployed to copilot-pat-pool September 4, 2026 18:30 — with GitHub Actions Inactive
@github-actions

github-actions Bot commented Sep 4, 2026

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

Or

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

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

@kubaflo

kubaflo commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).

@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Sep 4, 2026
@kubaflo
kubaflo temporarily deployed to copilot-pat-pool September 4, 2026 18:34 — with GitHub Actions Inactive
@kubaflo
kubaflo temporarily deployed to copilot-pat-pool September 4, 2026 18:36 — with GitHub Actions Inactive
@kubaflo
kubaflo temporarily deployed to copilot-pat-pool September 4, 2026 18:36 — with GitHub Actions Inactive

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 updated Android Window handler test stub can throw due to a null platformView path in the new discard callback, which can break the new device test coverage.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Pull request overview

This PR hardens Android navigation root replacement (Shell/FlyoutPage/Window) against AndroidX fragment transaction timing hazards by serializing root swaps, draining pending transactions while the outgoing root is still attached, and adding retries when the FragmentManager is busy. It also adds targeted Android device-test coverage and tightens teardown to avoid retaining stale view graphs and diagnostics overlays.

Changes:

  • Refactors NavigationRootManager (Android) to serialize/coalesce root swap requests, drain pending transactions (including activity manager when needed), and retry via main-looper posting when transactions are executing.
  • Updates WindowHandler (Android) to publish/attach prepared roots safely, scope disconnect completion, and ensure Visual Diagnostics overlays are deinitialized during teardown.
  • Adds/extends Android device tests and stubs to cover root replacement reentrancy/busy retries/toolbars and to guard against regressions.
File summaries
File Description
src/Core/src/WindowOverlay/WindowOverlay.Android.cs Ensures Android overlay view cleanup unsubscribes/disposes native view and clears platform references.
src/Core/src/VisualDiagnostics/VisualDiagnosticsOverlay.cs Adjusts overlay deinitialization behavior during teardown.
src/Core/src/Platform/Android/Navigation/NavigationRootManager.cs Implements serialized/coalesced root swapping, fragment transaction draining, and bounded busy-retry scheduling.
src/Core/src/Handlers/Window/WindowHandler.Android.cs Publishes prepared roots safely, coordinates disconnect lifecycle, and deinitializes diagnostics overlay on teardown.
src/Core/src/Handlers/View/ViewHandler.Android.cs Guards toolbar mapping when native toolbar can’t be produced; reparents toolbar safely.
src/Controls/tests/DeviceTests/Stubs/WindowHandlerStub.Android.cs Updates test stub to participate in prepared-root publish/discard flow (but contains a null-safety bug noted in PR comments).
src/Controls/tests/DeviceTests/Elements/Window/WindowTests.cs Adds extensive Android device regression coverage for root replacement, reentrancy, busy retry, and toolbar behavior.
src/Controls/tests/DeviceTests/Elements/FlyoutPage/FlyoutPageTests.Android.cs Adds device coverage for Flyout detail swap + same-turn root replacement and nested Flyout survival.
src/Controls/tests/DeviceTests/ControlsHandlerTestBase.Android.cs Wires the test activity root into the updated Window handler stub.
src/Controls/src/Core/Platform/ModalNavigationManager/ModalNavigationManager.Android.cs Requires modal root initialization to be synchronous by failing fast when a deferred connect occurs.
Review details
  • Files reviewed: 10/10 changed files
  • Comments generated: 1
  • Review effort level: Lite

Comment on lines +71 to +75
void OnRootDiscarded(AView? platformView)
{
if (ReferenceEquals(PlatformViewUnderTest, platformView))
platformView.RemoveFromParent();
}

@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

@kubaflo — new AI review results are available based on commit 563fa14.

Gate Inconclusive Confidence Low Platform Android


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

Gate Result: ⚠️ INCONCLUSIVE

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

🩺 Could not verify — environment/infrastructure error. The gate ran the tests but hit an environment error (an emulator/simulator/Appium/XHarness flake, a device that would not boot, or an empty/invalid result file), so it could not record a real pass/fail. The ⚠️ ENV ERROR marks below are infrastructure, not test failures — this is not a problem with your PR. Comment /review to retry on a fresh agent.

Device test result file(s) contained no tests for class(es) 'Microsoft.Maui.DeviceTests.ControlsHandlerTestBase' (the target tests did not run). Total tests found in result file(s): 0.

⚠️ Gate coverage limitations

  • The A/B gate did not verify 2 dropped DeviceTest group(s): WindowHandlerStub, WindowTests (ReplacedFlyoutPageRootClearsOldContainerView, ReplacingShellRootWhileSwitchingItemsDoesNotCrash, ReplacingShellRootFromPageLoadedDoesNotCrash, ReplacingFlyoutRootFromDetailLoadedDoesNotCrash, ReplacingContentRootWithShellInSameTurnDoesNotCrash, ReentrantRootReplacementDoesNotClobberNewRoot, RootReplacementDuringFragmentExecutionIsDeferred, OutgoingToolbarMappingDuringRootDrainIsIgnored, RootReplacementDuringFlyoutConstructionPublishesLatestRoot, SupersededRootRequestDoesNotReportApplied, ReentrantDisconnectDetachesDiscardedPreparedRoot, NewToolbarElementReusingOutgoingToolbarWinsDuringRootDrain, DetachedRootWithActiveFragmentCanBeReplaced, DetachedRootWithActiveFragmentCanBeDisconnected, BusyRootReplacementCancelsAfterRetryLimit, UnavailableActivityPermanentlyStopsDeferredRootSwaps, RootReplacementDuringDisconnectAttachesLatestRoot, ReentrantRootRequestsYieldBeforeContinuing, NestedVirtualDisconnectsPreserveEveryCompletion, SwitchBetweenWindowShouldTriggerIsActivated). Deep UI Tests runs HostApp UI categories only and does not execute DeviceTests; separate device-test validation is required.
Test Without Fix (expect FAIL) With Fix (expect PASS)
📱 ControlsHandlerTestBase ControlsHandlerTestBase 🛠️ BUILD ERROR ⚠️ ENV ERROR
📱 FlyoutPageTests (SwappingDetailThenReplacingWindowRootDoesNotCrash, NestedFlyoutPageDetailSurvivesRootReplacement) Category=FlyoutPage 🛠️ BUILD ERROR ✅ PASS — 401s
🔴 Without fix — 📱 ControlsHandlerTestBase: 🛠️ BUILD ERROR · 166s

Error-relevant lines (filtered from the build log):

/home/vsts/work/1/s/src/Controls/tests/DeviceTests/Elements/Window/WindowTests.cs(938,11): error CS0246: The type or namespace name 'RootRequestOutcome' could not be found (are you missing a using directive or an assembly reference?) [/home/vsts/work/1/s/src/Controls/tests/DeviceTests/Controls.DeviceTests.csproj::TargetFramework=net10.0-android]
Build FAILED.
🟢 With fix — 📱 ControlsHandlerTestBase: ⚠️ ENV ERROR · 387s

No log file found

🔴 Without fix — 📱 FlyoutPageTests (SwappingDetailThenReplacingWindowRootDoesNotCrash, NestedFlyoutPageDetailSurvivesRootReplacement): 🛠️ BUILD ERROR · 160s

Error-relevant lines (filtered from the build log):

/home/vsts/work/1/s/src/Controls/tests/DeviceTests/Elements/Window/WindowTests.cs(938,11): error CS0246: The type or namespace name 'RootRequestOutcome' could not be found (are you missing a using directive or an assembly reference?) [/home/vsts/work/1/s/src/Controls/tests/DeviceTests/Controls.DeviceTests.csproj::TargetFramework=net10.0-android]
Build FAILED.
🟢 With fix — 📱 FlyoutPageTests (SwappingDetailThenReplacingWindowRootDoesNotCrash, NestedFlyoutPageDetailSurvivesRootReplacement): PASS ✅ · 401s

(no coded error found; showing last 1200 chars)

            "totalMemoryBytes": 8322998272
          },
          "target": {
            "kind": "emulator",
            "name": "sdk_gphone_x86_64",
            "identifier": "emulator-5554",
            "operatingSystem": "Android",
            "operatingSystemVersion": "11",
            "apiLevel": 30,
            "architecture": "x86_64",
            "supportedArchitectures": [
              "x86_64",
              "x86",
              "arm64-v8a",
              "armeabi-v7a",
              "armeabi"
            ],
            "manufacturer": "Google",
            "model": "sdk_gphone_x86_64",
            "productName": "sdk_gphone_x86_64",
            "buildFingerprint": "google/sdk_gphone_x86_64/generic_x86_64_arm64:11/RSR1.201211.001/7027799:user/release-keys",
            "cpuModel": "0",
            "cpuMaxFrequencyHertz": 2000,
            "totalMemoryBytes": 2077544448
          }
        }
      }
      <<XHARNESS_RESULT_END>>
info: Attempting to remove apk 'com.microsoft.maui.controls.devicetests'..
info: Successfully uninstalled com.microsoft.maui.controls.devicetests
XHarness exit code: 0
  Passed: 2
  Failed: 0
  Skipped: 0
  Total: 2
  Tests completed successfully

⚠️ Failure Details

  • 🛠️ ControlsHandlerTestBase without fix: build failed before tests could run
    • /home/vsts/work/1/s/src/Controls/tests/DeviceTests/Elements/Window/WindowTests.cs(938,11): error CS0246: The type or namespace name 'RootRequestOutcome' could not be found (are you missing a using dir...
  • 🛠️ FlyoutPageTests (SwappingDetailThenReplacingWindowRootDoesNotCrash, NestedFlyoutPageDetailSurvivesRootReplacement) without fix: build failed before tests could run
    • /home/vsts/work/1/s/src/Controls/tests/DeviceTests/Elements/Window/WindowTests.cs(938,11): error CS0246: The type or namespace name 'RootRequestOutcome' could not be found (are you missing a using dir...
  • ⚠️ ControlsHandlerTestBase with fix: Device test result file(s) contained no tests for class(es) 'Microsoft.Maui.DeviceTests.ControlsHandlerTestBase' (the target tests did not run). Total tests found in result file(s): 0.
📁 Fix files reverted (6 files)
  • src/Controls/src/Core/Platform/ModalNavigationManager/ModalNavigationManager.Android.cs
  • src/Core/src/Handlers/View/ViewHandler.Android.cs
  • src/Core/src/Handlers/Window/WindowHandler.Android.cs
  • src/Core/src/Platform/Android/Navigation/NavigationRootManager.cs
  • src/Core/src/VisualDiagnostics/VisualDiagnosticsOverlay.cs
  • src/Core/src/WindowOverlay/WindowOverlay.Android.cs

📋 Pre-Flight — Context & Validation

PR #38214 Pre-Flight

PR

  • Title: [Android] Prevent fragment crashes during Shell and FlyoutPage root replacement
  • State: Open, non-draft
  • Base / head: main (d172c1ad97f5d2cf8c6bda5ef53043c7ff504505) / kubaflo-android-root-replacement (563fa14b9511642a4989555177813278421b3cba)
  • Local review commit: dd0038aae94db906e4034f5635ec864ffb1bbaa1 is the squashed PR change on branch pr-review-38214.
  • Size: 10 files, +1,735/-65.

Problem and Prior History

Shell and FlyoutPage can commit AndroidX fragment transactions asynchronously. Replacing Window.Page in the same turn can detach the outgoing fragment container before those transactions execute, causing a process-ending IllegalArgumentException (No view found for id ... ShellItemRenderer). Cleanup cannot simply be skipped: #35372 established that leaving ContainerView.CurrentView populated retains the outgoing MAUI view graph, while #36152 showed that clearing it without first settling fragment work exposes the crash.

The PR supersedes the closed #36212 attempt and follows #35372 and #36152. Its stated negative constraints are:

  1. Do not remove ContainerView.CurrentView cleanup.
  2. Do not use MainThread.BeginInvokeOnMainThread for busy-manager retries because it can execute inline on the UI thread.
  3. Do not drain the Activity fragment manager during scoped modal disconnect because that can re-enter Activity-level dismissal.
  4. Do not reject nested FlyoutPage detail hosts by comparing their container ID to the window root.

Existing PR Approach

The current implementation expands NavigationRootManager into a serialized, last-request-wins root-swap state machine. It:

  • drains pending transactions on the owning manager while the outgoing native root remains attached and, for replacement only, also drains a distinct Activity manager;
  • catches AndroidX's “already executing transactions” state and retries boundedly through Android.OS.Handler.PostDelayed;
  • prepares and publishes the Window native root before committing its content fragment;
  • coalesces reentrant requests, tracks request outcomes, and discards superseded roots/handlers;
  • preserves toolbar ownership with identity/version tracking and native reparenting;
  • scopes modal disconnect to its owning manager;
  • clears outgoing ContainerView.CurrentView, coordinator/inset state, overlay subscriptions, and retry infrastructure;
  • defers Window handler teardown completion with lifecycle generations.

Any candidate must use a different root-cause mechanism, not merely move these guards or rename this state machine.

Direct Diff Inspection

Production files changed:

  • src/Core/src/Platform/Android/Navigation/NavigationRootManager.cs
  • src/Core/src/Handlers/Window/WindowHandler.Android.cs
  • src/Core/src/Handlers/View/ViewHandler.Android.cs
  • src/Core/src/WindowOverlay/WindowOverlay.Android.cs
  • src/Core/src/VisualDiagnostics/VisualDiagnosticsOverlay.cs
  • src/Controls/src/Core/Platform/ModalNavigationManager/ModalNavigationManager.Android.cs

Test/support files changed:

  • src/Controls/tests/DeviceTests/Elements/Window/WindowTests.cs
  • src/Controls/tests/DeviceTests/Elements/FlyoutPage/FlyoutPageTests.Android.cs
  • src/Controls/tests/DeviceTests/ControlsHandlerTestBase.Android.cs
  • src/Controls/tests/DeviceTests/Stubs/WindowHandlerStub.Android.cs

The added Android regressions cover the direct Shell/Flyout root-replacement crash, stale ContainerView cleanup, nested FlyoutPage hosting, loaded-event and fragment-callback reentrancy, busy-manager retry/cancellation, stale roots/toolbars, activity loss, disconnect/reconnect completion, and bounded yielding. A public review comment also identifies a test-stub null dereference in WindowHandlerStub.OnRootDiscarded: ReferenceEquals(null, null) can be true before platformView.RemoveFromParent().

Bounded Test Contract

Detected primary test command:

pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform android -TestFilter "Category=Window" -IncludeClasses "Microsoft.Maui.DeviceTests.WindowTests"

This confines execution to the Android WindowTests class/category containing the primary ReplacingShellRootWhileSwitchingItemsDoesNotCrash regression and the related root-swap tests. STEP 5a supplied no separate mandatory regression-test list, so no broader category or full suite may be invented. The previously completed gate was INCONCLUSIVE because the tests could not be built/run; do not rerun the gate and do not create or overwrite gate/content.md.

Environment

gh is unauthenticated, so public GitHub API data and the locally materialized squashed diff were used. The worktree contains many pre-existing harness changes under .github/ and eng/; they are unrelated and must not be reverted or modified. Every try-fix attempt must obey .github/.baseline-state.json and restore only through:

pwsh .github/scripts/EstablishBrokenBaseline.ps1 -Restore

🔬 Code Review — Deep Analysis

Expert PR Evaluation

Verdict: NEEDS_DISCUSSION
Confidence: low

The expert reviewer found no actionable file-and-line defects in the submitted PR and wrote an empty inline-findings.json array. The review traced the Android root-swap state machine, fragment-manager draining and retry paths, Window handler publication/discard behavior, toolbar ownership, modal-manager scoping, overlay teardown, reentrancy, stale-root cleanup, and disconnect/reconnect lifecycle behavior.

The implementation is coherent with the reported failure mechanism, and the added Android device tests exercise the principal lifecycle and reentrancy risks. No reviewer-driven source patch is warranted. Approval cannot be recommended from this evaluation alone because the trusted Gate is inconclusive and the targeted Android regression command has not produced a runnable result; this is an evidence gap, not a confirmed code defect.


🛠️ Try-Fix — Analysis & Comparison

Candidate 1 — Try-Fix Result (PR #38214, Android)

Approach

Stable host-container swap barrier (mechanism-level alternative): keep a persistent Android host container attached to Activity and swap Shell/Flyout roots inside it, then clear outgoing ContainerView.CurrentView only after fragment-removal completion callback.

Mechanism-level difference from PR #38214

The PR uses a serialized last-request-wins root-swap state machine (request queue/coalescing, busy-manager delayed retries, generation/version tracking, prepared-root publish + commit orchestration). This candidate changes structural ownership instead: preserve fragment target container identity across same-turn root replacement so async commits do not target a detached container. Cleanup is callback-gated rather than retry/drain/state-machine serialization.

Baseline / Boundary outcome

Step 2 baseline command failed before baseline state creation because pre-existing tracked harness-owned dirty files were present; .github/.baseline-state.json stayed absent, so no safe RevertedFiles allow-list existed.

Baseline log


╔═══════════════════════════════════════════════════════════════════╗
║  ERROR: DIRTY WORKING DIRECTORY - Cannot establish baseline       ║
╚═══════════════════════════════════════════════════════════════════╝

The following files have uncommitted changes:

   M .github/scripts/Apply-PRFinalize.Tests.ps1
   M .github/scripts/BuildAndRunHostApp.ps1
   M .github/scripts/CiScanMutation.Tests.ps1
   M .github/scripts/DetectUITestCategories.Tests.ps1
   M .github/scripts/EstablishBrokenBaseline.ps1
   M .github/scripts/Invoke-CiScanReconcile.Tests.ps1
   M .github/scripts/Post-AISummaryComment.Tests.ps1
   M .github/scripts/PrepareVallyEvaluation.rb
   M .github/scripts/Resolve-RerunEligibility.Tests.ps1
   M .github/scripts/Resolve-RerunEligibility.ps1
   M .github/scripts/Review-PR.Tests.ps1
   M .github/scripts/Review-PR.ps1
   M .github/scripts/Review-Tests.Tests.ps1
   M .github/scripts/Review-Tests.ps1
   M .github/scripts/ReviewTrigger.Tests.ps1
   M .github/scripts/SetupVallyRuntime.sh
   M .github/scripts/TestPrepareVallyEvaluation.rb
   M .github/scripts/Validate-CiScanManifest.Tests.ps1
   M .github/scripts/apply-pr-finalize.ps1
   M .github/scripts/post-ai-summary-comment.ps1
   M .github/scripts/post-inline-review.ps1
   M .github/scripts/shared/Build-AndDeploy.ps1
   M .github/scripts/shared/Detect-TestsInDiff.ps1
   M .github/scripts/shared/Get-EnvErrorPatterns.ps1
   M .github/scripts/shared/Invoke-UITestWithRetry.ps1
   M .github/scripts/shared/Remove-StaleMauiBotComments.ps1
   M .github/scripts/shared/Start-Emulator.ps1
   M .github/scripts/shared/Update-AgentLabels.Tests.ps1
   M .github/scripts/shared/Update-AgentLabels.ps1
   M .github/scripts/shared/shared-utils.ps1
   M .github/skills/agentic-labeler/tests/eval.vally.yaml
   M .github/skills/agentic-workflows/SKILL.md
   M .github/skills/analyze-sessions/SKILL.md
   M .github/skills/analyze-sessions/references/design-rationale.md
   M .github/skills/analyze-sessions/tests/eval.vally.yaml
   M .github/skills/ci-fix/tests/eval.ownership.vally.yaml
   M .github/skills/ci-fix/tests/eval.vally.yaml
   M .github/skills/code-review/SKILL.md
   M .github/skills/code-review/tests/eval.inline-findings.vally.yaml
   M .github/skills/code-review/tests/eval.producer-trace.vally.yaml
   M .github/skills/code-review/tests/eval.trim-aot.vally.yaml
   M .github/skills/code-review/tests/eval.vally.yaml
   M .github/skills/code-review/tests/hermeticity.vally.yaml
   M .github/skills/code-review/tests/soak.capability.vally.yaml
   M .github/skills/evaluate-pr-tests/tests/eval.vally.yaml
   M .github/skills/pr-review/SKILL.md
   M .github/skills/pr-review/tests/eval.gh-auth.vally.yaml
   M .github/skills/release-readiness/SKILL.md
   M .github/skills/release-readiness/scripts/Find-ReleaseReadinessTrackers.ps1
   M .github/skills/release-readiness/scripts/Get-PreviewReadiness.ps1
   M .github/skills/release-readiness/scripts/New-ReleaseHandoff.ps1
   D .github/skills/release-readiness/scripts/Update-TrackerIssue.sh
   M .github/skills/release-readiness/tests/Test-ReleaseReadiness.ps1
   M .github/skills/run-device-tests/SKILL.md
   M .github/skills/run-device-tests/scripts/Run-DeviceTests.Tests.ps1
   M .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1
   M .github/skills/try-fix/tests/eval.restore.vally.yaml
   M .github/skills/try-fix/tests/eval.vally.yaml
   M .github/skills/verify-tests-fail-without-fix/scripts/Verify-TestsFail.Tests.ps1
   M .github/skills/verify-tests-fail-without-fix/scripts/verify-tests-fail.ps1
   M .github/skills/verify-tests-fail-without-fix/tests/eval.protocol.vally.yaml
   M .github/skills/verify-tests-fail-without-fix/tests/eval.vally.yaml
   M eng/scripts/detect-ui-test-categories.ps1
   M eng/scripts/disable-notification-center.sh
   M eng/scripts/enable-notification-center.sh
   M eng/scripts/nuget_release_packages.Tests.ps1
   M eng/scripts/nuget_release_packages.ps1

This usually means a previous try-fix attempt did not restore properly.

To fix:
  1. Run 'git status' to review the changes
  2. Either commit them: git add . && git commit -m 'Save changes'
  3. Or discard them:   git checkout -- .
  4. Then retry this script

Exception: /home/vsts/work/1/s/.github/scripts/EstablishBrokenBaseline.ps1:392
Line |
 392 |      throw "EstablishBrokenBaseline.ps1 failed: Working directory is n …
     |      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | EstablishBrokenBaseline.ps1 failed: Working directory is not clean.
     | Clean up before establishing baseline.

Files changed

  • Production/test code files: none (blocked before baseline-governed edit scope)
  • Artifact files:
    • CustomAgentLogsTmp/PRState/38214/PRAgent/try-fix/attempt-1/*
    • CustomAgentLogsTmp/PRState/38214/PRAgent/try-fix-1/content.md
    • CustomAgentLogsTmp/PRState/38214/PRAgent/try-fix/content.md

Test command and result summary

Command:

pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform android -TestFilter "Category=Window" -IncludeClasses "Microsoft.Maui.DeviceTests.WindowTests"

Result: NOT RUN (Blocked before Step 7 due to baseline establishment failure).

Saved test output:

Test command (required):
pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform android -TestFilter "Category=Window" -IncludeClasses "Microsoft.Maui.DeviceTests.WindowTests"

Result: NOT RUN
Reason: Blocked before Step 7. Step 2 baseline establishment failed with "DIRTY WORKING DIRECTORY", and .github/.baseline-state.json was not created, so no safe editable baseline existed.

Result

Blocked

Inline expert self-review

  • Findings count: 0
  • reviewer-findings.json: [] (no candidate code diff)

Failure analysis

Environment/worktree baseline blocker prevented entering the baseline-governed editable state required by the try-fix protocol. Editing code without successful EstablishBrokenBaseline + RevertedFiles state would violate the restore boundary.

Complete saved diff

# No code changes were applied in this attempt.
# EstablishBrokenBaseline.ps1 failed before baseline creation, so edit scope was unavailable.

Restore status

Mandatory script-only restore executed:
pwsh .github/scripts/EstablishBrokenBaseline.ps1 -Restore
Result: Restored=False, Message=No baseline state found (expected for verified no-state blocked path).


Candidate 2 — Try-Fix Result (PR #38214, Android)

Approach

Producer-side synchronous fragment commits: change the Shell and FlyoutPage fragment-producing paths so root-bearing add/replace/remove transactions execute immediately while their target container is attached (retaining FlyoutPage's existing attach-time deferral). With no queued transaction still referencing the outgoing container, ordinary same-turn Window.Page replacement can detach the old root and clear ContainerView.CurrentView normally.

Causal mechanism-level difference

The PR serializes root replacement in NavigationRootManager: it drains owning/activity managers while attached, retries busy managers with bounded delayed posts, publishes prepared roots, coalesces/discards requests, tracks toolbar/modal/lifecycle ownership, and coordinates cleanup. Candidate 1 instead proposed a persistent Activity host/container identity plus callback-gated outgoing cleanup. Candidate 2 does neither. It targets transaction production itself: synchronous producer commits eliminate the pending fragment work before Window replacement begins, so no root-request state machine, stable host container, or cleanup callback barrier is required. Immediate ContainerView.CurrentView cleanup remains intact.

Baseline / boundary outcome

The exact mandatory baseline command was run once:

pwsh .github/scripts/EstablishBrokenBaseline.ps1

It failed with DIRTY WORKING DIRECTORY because pre-existing harness-owned tracked changes under .github/ and eng/ were present. A direct check confirmed .github/.baseline-state.json was absent. Therefore no RevertedFiles allow-list existed, and the attempt was blocked before edits by the required baseline boundary. Candidate 1 was not reopened, rerun, altered, or repeated; its blocker was not bypassed.

The complete baseline output is saved at:
CustomAgentLogsTmp/PRState/38214/PRAgent/try-fix/attempt-2/baseline.log

Files changed

  • Production/test code: none.
  • Intended but unmodified producer paths:
    • src/Controls/src/Core/Compatibility/Handlers/Shell/Android/ShellRenderer.cs
    • src/Controls/src/Core/Compatibility/Handlers/Shell/Android/ShellItemRendererBase.cs
    • src/Compatibility/Core/src/Android/AppCompat/FlyoutPageContainer.cs
  • Attempt/result artifacts:
    • CustomAgentLogsTmp/PRState/38214/PRAgent/try-fix/attempt-2/*
    • CustomAgentLogsTmp/PRState/38214/PRAgent/try-fix-2/content.md
    • candidate 2 appended to CustomAgentLogsTmp/PRState/38214/PRAgent/try-fix/content.md

Exact test command and result

pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform android -TestFilter "Category=Window" -IncludeClasses "Microsoft.Maui.DeviceTests.WindowTests"

Outcome: NOT RUN. Baseline establishment failed before implementation/testing, and no safe editable baseline existed. The prior gate was not rerun and gate/content.md was not created or overwritten.

Saved output summary:

Test command (required):
pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform android -TestFilter "Category=Window" -IncludeClasses "Microsoft.Maui.DeviceTests.WindowTests"

Result: NOT RUN
Reason: Blocked before implementation/testing. EstablishBrokenBaseline.ps1 failed with "DIRTY WORKING DIRECTORY", and .github/.baseline-state.json was absent, so the baseline boundary prohibited all production/test edits. The prior gate was not rerun.

Full saved output: CustomAgentLogsTmp/PRState/38214/PRAgent/try-fix/attempt-2/test-output.log.

Failure analysis

The environment remained outside the skill's safe baseline boundary. Editing production code without a state file and RevertedFiles allow-list would risk touching files the restore script cannot restore. Harness-owned .github/ and eng/ changes could not be modified, cleaned, stashed, committed, or reverted. Consequently the distinct producer-side synchronous-commit hypothesis could not be implemented or empirically evaluated. If later attempted in a valid baseline, FragmentManager reentrancy/state-saved behavior and FlyoutPage's attach-time transaction path would require validation.

Result

Blocked

Inline expert self-review

  • findings_count: 0
  • reviewer-findings.json: []
  • No candidate code diff existed; the overarching and always-active dimensions were reviewed without findings.

Complete saved diff

# No candidate code changes were applied.
# EstablishBrokenBaseline.ps1 rejected pre-existing tracked harness changes and did not create .github/.baseline-state.json, so no RevertedFiles edit allow-list existed.

Restore completion

The exact mandatory restore command was run after artifact capture:

pwsh .github/scripts/EstablishBrokenBaseline.ps1 -Restore

Result: Restored=False, Message=No baseline state found. This is the expected successful completion for the verified no-state blocked path; no candidate edits were made. Pre-existing harness-owned changes were left untouched.


🏁 Report — Final Recommendation

⚠️ Final Recommendation: REQUEST CHANGES

Winning candidate

pr-plus-reviewer

The submitted production fix is technically coherent and received no actionable findings from the expert reviewer, but the reviewer-enhanced candidate also closes a concrete nullable callback hole in the new WindowHandlerStub test infrastructure. It then passed the exact required Android WindowTests validation: 32 passed, 0 failed, 0 skipped. Because the winning one-line guard is not present in submitted PR HEAD, the PR needs that change before approval.

Comparative ranking

Rank Candidate Implementation Regression evidence Assessment
1 pr-plus-reviewer Submitted PR plus a null guard before dereferencing the nullable discarded root Required Android WindowTests: PASS, 32/32 Winner. Preserves the reviewed production approach, resolves the identified callback edge case, and has the strongest targeted evidence.
2 pr Serialized, coalescing Android root-swap state machine with fragment draining/retry, prepared-root publication, scoped modal teardown, toolbar ownership, and lifecycle cleanup Trusted Gate INCONCLUSIVE for WindowTests; its FlyoutPage subset passed 2/2. Author reports additional API 34 validation. Expert review found no production defect, but submitted HEAD retains the nullable OnRootDiscarded dereference and lacks a successful trusted Window-class run.
3 try-fix-1 Proposed a persistent host-container swap barrier with callback-gated cleanup NOT RUN Blocked before implementation because baseline establishment failed; no source diff exists, so the mechanism remains hypothetical.
4 try-fix-2 Proposed synchronous commits in Shell/Flyout fragment producers NOT RUN Blocked before implementation because baseline establishment failed; no source diff exists, and reentrancy/state-saved behavior remains untested.

No candidate failed a regression test. The alternatives rank below both PR-based candidates because they produced neither executable changes nor regression evidence.

Expert review

The one permitted maui-expert-reviewer pass produced inline-findings.json as []. It traced root replacement, fragment-manager busy retries, reentrancy, stale-root disposal, toolbar remapping, modal scoping, overlay teardown, and disconnect/reconnect behavior without finding an actionable defect in the production implementation.

The initial expert verdict was NEEDS_DISCUSSION at low confidence because the trusted Gate was inconclusive. The successful sandbox run materially improves the evidence for pr-plus-reviewer, but it does not convert the raw submitted PR into the winner because the null-safety refinement is absent there.

Residual uncertainty

Validation was intentionally limited to the required Android WindowTests command on API 30; no full suite was run. The original Gate's broader verification remains inconclusive, so this report does not claim complete platform coverage.


📱 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 — reviewer changes required

The reviewer-enhanced candidate identified changes that are not yet in the submitted PR.

Why: The reviewer-enhanced PR preserves the submitted production fix, adds a necessary null guard in the new WindowHandlerStub discard callback, and passed the exact targeted Android WindowTests run with 32 of 32 tests passing. Both try-fix alternatives were blocked before implementation or validation.

Address the actionable findings in this review before merging.

@MauiBot MauiBot added s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-fix-win AI found a better alternative fix than the PR 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 4, 2026
@kubaflo

kubaflo commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

Tests Failure Analysis

@kubaflo — test-failure review results are available based on commit 563fa14.

Maintainers can request a fresh review after new comments, commits, or CI runs by commenting /review tests.

Overall Needs human investigation Failures 16 Baseline 4 on base Platform Multi-platform

Test Failure Review: Needs human investigation - click to expand

Overall verdict: Needs human investigation

No completed failure has a credible causal link to this Android root-replacement change. Four machine-deduplicated failures also occurred on the base build, the other concrete failures are documented flakes or unrelated infrastructure/platform failures, and all seven Helix device-test jobs reported zero failed work items. CI is not yet trustworthy-green because two macOS UI jobs were canceled at the 180-minute limit.

Coverage: 169 checks · 158 passing/neutral/skipped · 11 failing · 0 pending · 0 inaccessible · 2 unmapped · 17 unexplained build legs · 0 unaccounted failing checks · 2 aborted failing checks · 0 canceled-build checks · 0 device-test unverified · 12 unattributed · 4 regressed-vs-base. Deterministic ceiling: Not ready — Build Analysis/Build Insights are unmapped, two macOS checks were canceled, and several retry records were incomplete or unattributed.

Failure Verdict On base? Evidence
iOS SDK download, then missing test results/logs Likely unrelated regressed Both the integration and iOS UI legs hit OpenSSL EPROTO while downloading releases-index.json; the publish errors are direct cascades. This is network/tooling failure on iOS, while the PR is Android-scoped.
Android SDK platform-tools;35.0.2 provisioning Likely unrelated also-red The same provisioning warning/failure is present in main build 1583317.
SafeAreaNoWhiteSpaceAfterKeyboardDismissAndEdgeToggle Likely unrelated yes PR build 1583481 and the immediately preceding main build 1583317 have the identical assertion (Expected: less than 2705, But was: 2705). Also tracked as 7/10 recent main builds in #38135.
LayoutShouldBeCorrectOnFirstNavigation Likely unrelated yes Both PR and immediately preceding main logs report the same 1.80% Android snapshot mismatch; #38137 records it in 7/10 recent main builds.
ShellContentShouldRespectSafeAreaEdges_After_Navigation Likely unrelated leg also-red It passed one attempt and timed out on another within this PR build. #37653 records the identical Android test, timeout, and stack location on main in 3/10 builds.
macOS VerifyLabelWithTextWhenLineHeight Likely unrelated flaky-on-base The exact 2.40% mismatch is tracked in #38013, seen in 3/10 recent main builds; no macOS Label code changed.
Windows Issue18896Test Likely unrelated regressed in sampled window Windows is outside the PR scope, and this screenshot test has established instability in #33507 and #34017. The five sampled base legs were green, so a rerun is still required before treating the check as clean.
macOS CollectionView (GroupedCollectionViewItems, job canceled) Needs human investigation latest base job also canceled A 0.54% macOS-only snapshot mismatch triggered a full retry; the shard then hit the 180-minute job limit. The immediately preceding main build canceled the identical CollectionView shard at the same limit, and this PR changes no CollectionView or macOS rendering code. Cancellation prevents a complete result.
macOS Shell job canceled Needs human investigation no exact latest-base match The first attempt hit TabBarShouldbeVisibleNavigatingBackFromNonTabbedPage and ShellTitleViewWithXNameShouldNotLeakMemory; the latter is an established main flake (#36418). The retry was still actively passing tests when the 180-minute shard limit canceled it, so there is no complete result to classify.
macOS Layout retry Likely unrelated historical main match ChangingTranslationShouldNotCauseLayoutPassOnAncestors failed once, then the job succeeded on retry; the exact macOS failure is documented from main in #36051.

Recommended action

Rerun the failed/canceled maui-pr and maui-pr-uitests checks. The current evidence does not call for a PR code change, but the two canceled macOS shards must complete before CI can be considered merge-ready.

Evidence details
  • maui-pr build 1583480: 25 jobs passed; only RunOniOS_MauiRelease ARM64 failed at the SDK-download step.
  • maui-pr-devicetests build 1583482: Android Mono/CoreCLR, iOS, MacCatalyst, and Windows Helix aggregates all positively reported zero failed work items.
  • maui-pr-uitests build 1583481: Android SafeArea, Windows RefreshView, macOS Label, and iOS SDK-download failures completed; macOS Shell and CollectionView were canceled at 180 minutes; macOS Layout recovered on retry.
  • PR scope is nine Android-specific files plus a one-line cross-platform diagnostics-overlay subscription lifecycle change; it does not modify the failing UI tests, snapshots, macOS CollectionView/Label/Layout implementation, Windows RefreshView, or iOS tooling.
  • Limitation: Build Analysis and Build Insights expose aggregate failures without inspectable AzDO evidence, and the canceled shards/test-run overflow leave incomplete records. This is why the overall verdict remains Needs human investigation despite no likely PR-caused failure.

@kubaflo
kubaflo changed the base branch from main to inflight/current September 5, 2026 13:51
@kubaflo
kubaflo merged commit f2246d2 into inflight/current Sep 5, 2026
159 of 170 checks passed
@kubaflo
kubaflo deleted the kubaflo-android-root-replacement branch September 5, 2026 13:52
@github-actions github-actions Bot added this to the .NET 10 SR11 milestone Sep 5, 2026
kubaflo added a commit that referenced this pull request Sep 6, 2026
…eplacement (#38214)

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

### Root Cause

Android Shell and FlyoutPage create content through asynchronously
committed AndroidX fragment transactions. A same-turn `Window.Page`
replacement could detach the outgoing fragment container before those
transactions ran, terminating the process with
`IllegalArgumentException: No view found for id ... ShellItemRenderer`.

Skipping cleanup is not safe: the outgoing `ContainerView.CurrentView`
must still be cleared so the replaced MAUI view graph is not retained.

### Description of Change

- Serialize and coalesce navigation-root requests with last-request-wins
behavior under reentrancy.
- Drain committed transactions while the outgoing native root remains
attached, including the distinct Activity fragment manager used by
compatibility Shell during replacement.
- Retry boundedly through the Android main looper when AndroidX is
already executing transactions.
- Attach a prepared Window root before committing its content fragment,
and explicitly discard superseded roots and newly-created handlers.
- Preserve current toolbar mappings with identity/version tracking and
safe native reparenting.
- Keep modal disconnects scoped to their owning fragment manager to
avoid re-entering Activity-level dismissal transactions.
- Clear outgoing `ContainerView` content and release Visual Diagnostics
native Activity/view subscriptions during handler teardown.
- Add Android device regressions for Shell/Flyout root replacement,
reentrancy, retries, stale roots and toolbars, nested FlyoutPage hosts,
modal teardown, and disconnect/reconnect completion.

### What NOT to Do

- Do not remove `ContainerView.CurrentView` cleanup to hide the crash;
that retains the outgoing MAUI view graph.
- Do not use `MainThread.BeginInvokeOnMainThread` for the transaction
retry; it can execute inline on the UI thread before AndroidX clears its
executing state.
- Do not drain the Activity fragment manager during scoped modal
disconnect; that can re-enter the dismissal transaction already running
there.

### Empirical Validation

The failure still reproduced on current `main` on an Android API 34
emulator. The exact stress scenario alternated new Shell and FlyoutPage
roots in the same turn and crashed before the fix with the missing
fragment-container exception.

After the fix, all 50 iterations completed, the final Shell root was
attached, the process remained alive, and logcat contained no fatal
exception, missing-view exception, or fragment-manager busy exception.

Final targeted API 34 results:

| Category | Result |
|---|---:|
| Window | 34/34 passed |
| FlyoutPage | 17/17 passed |
| Modal | 44/44 passed |

The final Android Controls DeviceTests Release app also builds
successfully.

#### Before fix — reproduced on current main


https://github.com/user-attachments/assets/4f7c8e51-7a22-45c9-943b-00d061db3537

#### After fix — same 50-iteration stress scenario


https://github.com/user-attachments/assets/59efd50d-ff03-409d-9b40-7c608c3669f5

### Issues Fixed

Supersedes #36212. Follow-up to #35372 and #36152.

---------
kubaflo added a commit that referenced this pull request Sep 7, 2026
…eplacement (#38214)

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

### Root Cause

Android Shell and FlyoutPage create content through asynchronously
committed AndroidX fragment transactions. A same-turn `Window.Page`
replacement could detach the outgoing fragment container before those
transactions ran, terminating the process with
`IllegalArgumentException: No view found for id ... ShellItemRenderer`.

Skipping cleanup is not safe: the outgoing `ContainerView.CurrentView`
must still be cleared so the replaced MAUI view graph is not retained.

### Description of Change

- Serialize and coalesce navigation-root requests with last-request-wins
behavior under reentrancy.
- Drain committed transactions while the outgoing native root remains
attached, including the distinct Activity fragment manager used by
compatibility Shell during replacement.
- Retry boundedly through the Android main looper when AndroidX is
already executing transactions.
- Attach a prepared Window root before committing its content fragment,
and explicitly discard superseded roots and newly-created handlers.
- Preserve current toolbar mappings with identity/version tracking and
safe native reparenting.
- Keep modal disconnects scoped to their owning fragment manager to
avoid re-entering Activity-level dismissal transactions.
- Clear outgoing `ContainerView` content and release Visual Diagnostics
native Activity/view subscriptions during handler teardown.
- Add Android device regressions for Shell/Flyout root replacement,
reentrancy, retries, stale roots and toolbars, nested FlyoutPage hosts,
modal teardown, and disconnect/reconnect completion.

### What NOT to Do

- Do not remove `ContainerView.CurrentView` cleanup to hide the crash;
that retains the outgoing MAUI view graph.
- Do not use `MainThread.BeginInvokeOnMainThread` for the transaction
retry; it can execute inline on the UI thread before AndroidX clears its
executing state.
- Do not drain the Activity fragment manager during scoped modal
disconnect; that can re-enter the dismissal transaction already running
there.

### Empirical Validation

The failure still reproduced on current `main` on an Android API 34
emulator. The exact stress scenario alternated new Shell and FlyoutPage
roots in the same turn and crashed before the fix with the missing
fragment-container exception.

After the fix, all 50 iterations completed, the final Shell root was
attached, the process remained alive, and logcat contained no fatal
exception, missing-view exception, or fragment-manager busy exception.

Final targeted API 34 results:

| Category | Result |
|---|---:|
| Window | 34/34 passed |
| FlyoutPage | 17/17 passed |
| Modal | 44/44 passed |

The final Android Controls DeviceTests Release app also builds
successfully.

#### Before fix — reproduced on current main


https://github.com/user-attachments/assets/4f7c8e51-7a22-45c9-943b-00d061db3537

#### After fix — same 50-iteration stress scenario


https://github.com/user-attachments/assets/59efd50d-ff03-409d-9b40-7c608c3669f5

### Issues Fixed

Supersedes #36212. Follow-up to #35372 and #36152.

---------
kubaflo added a commit that referenced this pull request Sep 8, 2026
…eplacement (#38214)

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

### Root Cause

Android Shell and FlyoutPage create content through asynchronously
committed AndroidX fragment transactions. A same-turn `Window.Page`
replacement could detach the outgoing fragment container before those
transactions ran, terminating the process with
`IllegalArgumentException: No view found for id ... ShellItemRenderer`.

Skipping cleanup is not safe: the outgoing `ContainerView.CurrentView`
must still be cleared so the replaced MAUI view graph is not retained.

### Description of Change

- Serialize and coalesce navigation-root requests with last-request-wins
behavior under reentrancy.
- Drain committed transactions while the outgoing native root remains
attached, including the distinct Activity fragment manager used by
compatibility Shell during replacement.
- Retry boundedly through the Android main looper when AndroidX is
already executing transactions.
- Attach a prepared Window root before committing its content fragment,
and explicitly discard superseded roots and newly-created handlers.
- Preserve current toolbar mappings with identity/version tracking and
safe native reparenting.
- Keep modal disconnects scoped to their owning fragment manager to
avoid re-entering Activity-level dismissal transactions.
- Clear outgoing `ContainerView` content and release Visual Diagnostics
native Activity/view subscriptions during handler teardown.
- Add Android device regressions for Shell/Flyout root replacement,
reentrancy, retries, stale roots and toolbars, nested FlyoutPage hosts,
modal teardown, and disconnect/reconnect completion.

### What NOT to Do

- Do not remove `ContainerView.CurrentView` cleanup to hide the crash;
that retains the outgoing MAUI view graph.
- Do not use `MainThread.BeginInvokeOnMainThread` for the transaction
retry; it can execute inline on the UI thread before AndroidX clears its
executing state.
- Do not drain the Activity fragment manager during scoped modal
disconnect; that can re-enter the dismissal transaction already running
there.

### Empirical Validation

The failure still reproduced on current `main` on an Android API 34
emulator. The exact stress scenario alternated new Shell and FlyoutPage
roots in the same turn and crashed before the fix with the missing
fragment-container exception.

After the fix, all 50 iterations completed, the final Shell root was
attached, the process remained alive, and logcat contained no fatal
exception, missing-view exception, or fragment-manager busy exception.

Final targeted API 34 results:

| Category | Result |
|---|---:|
| Window | 34/34 passed |
| FlyoutPage | 17/17 passed |
| Modal | 44/44 passed |

The final Android Controls DeviceTests Release app also builds
successfully.

#### Before fix — reproduced on current main


https://github.com/user-attachments/assets/4f7c8e51-7a22-45c9-943b-00d061db3537

#### After fix — same 50-iteration stress scenario


https://github.com/user-attachments/assets/59efd50d-ff03-409d-9b40-7c608c3669f5

### Issues Fixed

Supersedes #36212. Follow-up to #35372 and #36152.

---------
kubaflo added a commit that referenced this pull request Sep 9, 2026
…eplacement (#38214)

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

### Root Cause

Android Shell and FlyoutPage create content through asynchronously
committed AndroidX fragment transactions. A same-turn `Window.Page`
replacement could detach the outgoing fragment container before those
transactions ran, terminating the process with
`IllegalArgumentException: No view found for id ... ShellItemRenderer`.

Skipping cleanup is not safe: the outgoing `ContainerView.CurrentView`
must still be cleared so the replaced MAUI view graph is not retained.

### Description of Change

- Serialize and coalesce navigation-root requests with last-request-wins
behavior under reentrancy.
- Drain committed transactions while the outgoing native root remains
attached, including the distinct Activity fragment manager used by
compatibility Shell during replacement.
- Retry boundedly through the Android main looper when AndroidX is
already executing transactions.
- Attach a prepared Window root before committing its content fragment,
and explicitly discard superseded roots and newly-created handlers.
- Preserve current toolbar mappings with identity/version tracking and
safe native reparenting.
- Keep modal disconnects scoped to their owning fragment manager to
avoid re-entering Activity-level dismissal transactions.
- Clear outgoing `ContainerView` content and release Visual Diagnostics
native Activity/view subscriptions during handler teardown.
- Add Android device regressions for Shell/Flyout root replacement,
reentrancy, retries, stale roots and toolbars, nested FlyoutPage hosts,
modal teardown, and disconnect/reconnect completion.

### What NOT to Do

- Do not remove `ContainerView.CurrentView` cleanup to hide the crash;
that retains the outgoing MAUI view graph.
- Do not use `MainThread.BeginInvokeOnMainThread` for the transaction
retry; it can execute inline on the UI thread before AndroidX clears its
executing state.
- Do not drain the Activity fragment manager during scoped modal
disconnect; that can re-enter the dismissal transaction already running
there.

### Empirical Validation

The failure still reproduced on current `main` on an Android API 34
emulator. The exact stress scenario alternated new Shell and FlyoutPage
roots in the same turn and crashed before the fix with the missing
fragment-container exception.

After the fix, all 50 iterations completed, the final Shell root was
attached, the process remained alive, and logcat contained no fatal
exception, missing-view exception, or fragment-manager busy exception.

Final targeted API 34 results:

| Category | Result |
|---|---:|
| Window | 34/34 passed |
| FlyoutPage | 17/17 passed |
| Modal | 44/44 passed |

The final Android Controls DeviceTests Release app also builds
successfully.

#### Before fix — reproduced on current main


https://github.com/user-attachments/assets/4f7c8e51-7a22-45c9-943b-00d061db3537

#### After fix — same 50-iteration stress scenario


https://github.com/user-attachments/assets/59efd50d-ff03-409d-9b40-7c608c3669f5

### Issues Fixed

Supersedes #36212. Follow-up to #35372 and #36152.

---------
kubaflo added a commit that referenced this pull request Sep 11, 2026
…eplacement (#38214)

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

### Root Cause

Android Shell and FlyoutPage create content through asynchronously
committed AndroidX fragment transactions. A same-turn `Window.Page`
replacement could detach the outgoing fragment container before those
transactions ran, terminating the process with
`IllegalArgumentException: No view found for id ... ShellItemRenderer`.

Skipping cleanup is not safe: the outgoing `ContainerView.CurrentView`
must still be cleared so the replaced MAUI view graph is not retained.

### Description of Change

- Serialize and coalesce navigation-root requests with last-request-wins
behavior under reentrancy.
- Drain committed transactions while the outgoing native root remains
attached, including the distinct Activity fragment manager used by
compatibility Shell during replacement.
- Retry boundedly through the Android main looper when AndroidX is
already executing transactions.
- Attach a prepared Window root before committing its content fragment,
and explicitly discard superseded roots and newly-created handlers.
- Preserve current toolbar mappings with identity/version tracking and
safe native reparenting.
- Keep modal disconnects scoped to their owning fragment manager to
avoid re-entering Activity-level dismissal transactions.
- Clear outgoing `ContainerView` content and release Visual Diagnostics
native Activity/view subscriptions during handler teardown.
- Add Android device regressions for Shell/Flyout root replacement,
reentrancy, retries, stale roots and toolbars, nested FlyoutPage hosts,
modal teardown, and disconnect/reconnect completion.

### What NOT to Do

- Do not remove `ContainerView.CurrentView` cleanup to hide the crash;
that retains the outgoing MAUI view graph.
- Do not use `MainThread.BeginInvokeOnMainThread` for the transaction
retry; it can execute inline on the UI thread before AndroidX clears its
executing state.
- Do not drain the Activity fragment manager during scoped modal
disconnect; that can re-enter the dismissal transaction already running
there.

### Empirical Validation

The failure still reproduced on current `main` on an Android API 34
emulator. The exact stress scenario alternated new Shell and FlyoutPage
roots in the same turn and crashed before the fix with the missing
fragment-container exception.

After the fix, all 50 iterations completed, the final Shell root was
attached, the process remained alive, and logcat contained no fatal
exception, missing-view exception, or fragment-manager busy exception.

Final targeted API 34 results:

| Category | Result |
|---|---:|
| Window | 34/34 passed |
| FlyoutPage | 17/17 passed |
| Modal | 44/44 passed |

The final Android Controls DeviceTests Release app also builds
successfully.

#### Before fix — reproduced on current main


https://github.com/user-attachments/assets/4f7c8e51-7a22-45c9-943b-00d061db3537

#### After fix — same 50-iteration stress scenario


https://github.com/user-attachments/assets/59efd50d-ff03-409d-9b40-7c608c3669f5

### Issues Fixed

Supersedes #36212. Follow-up to #35372 and #36152.

---------
kubaflo added a commit that referenced this pull request Sep 15, 2026
…eplacement (#38214)

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

### Root Cause

Android Shell and FlyoutPage create content through asynchronously
committed AndroidX fragment transactions. A same-turn `Window.Page`
replacement could detach the outgoing fragment container before those
transactions ran, terminating the process with
`IllegalArgumentException: No view found for id ... ShellItemRenderer`.

Skipping cleanup is not safe: the outgoing `ContainerView.CurrentView`
must still be cleared so the replaced MAUI view graph is not retained.

### Description of Change

- Serialize and coalesce navigation-root requests with last-request-wins
behavior under reentrancy.
- Drain committed transactions while the outgoing native root remains
attached, including the distinct Activity fragment manager used by
compatibility Shell during replacement.
- Retry boundedly through the Android main looper when AndroidX is
already executing transactions.
- Attach a prepared Window root before committing its content fragment,
and explicitly discard superseded roots and newly-created handlers.
- Preserve current toolbar mappings with identity/version tracking and
safe native reparenting.
- Keep modal disconnects scoped to their owning fragment manager to
avoid re-entering Activity-level dismissal transactions.
- Clear outgoing `ContainerView` content and release Visual Diagnostics
native Activity/view subscriptions during handler teardown.
- Add Android device regressions for Shell/Flyout root replacement,
reentrancy, retries, stale roots and toolbars, nested FlyoutPage hosts,
modal teardown, and disconnect/reconnect completion.

### What NOT to Do

- Do not remove `ContainerView.CurrentView` cleanup to hide the crash;
that retains the outgoing MAUI view graph.
- Do not use `MainThread.BeginInvokeOnMainThread` for the transaction
retry; it can execute inline on the UI thread before AndroidX clears its
executing state.
- Do not drain the Activity fragment manager during scoped modal
disconnect; that can re-enter the dismissal transaction already running
there.

### Empirical Validation

The failure still reproduced on current `main` on an Android API 34
emulator. The exact stress scenario alternated new Shell and FlyoutPage
roots in the same turn and crashed before the fix with the missing
fragment-container exception.

After the fix, all 50 iterations completed, the final Shell root was
attached, the process remained alive, and logcat contained no fatal
exception, missing-view exception, or fragment-manager busy exception.

Final targeted API 34 results:

| Category | Result |
|---|---:|
| Window | 34/34 passed |
| FlyoutPage | 17/17 passed |
| Modal | 44/44 passed |

The final Android Controls DeviceTests Release app also builds
successfully.

#### Before fix — reproduced on current main


https://github.com/user-attachments/assets/4f7c8e51-7a22-45c9-943b-00d061db3537

#### After fix — same 50-iteration stress scenario


https://github.com/user-attachments/assets/59efd50d-ff03-409d-9b40-7c608c3669f5

### Issues Fixed

Supersedes #36212. Follow-up to #35372 and #36152.

---------
kubaflo added a commit that referenced this pull request Sep 18, 2026
…eplacement (#38214)

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

### Root Cause

Android Shell and FlyoutPage create content through asynchronously
committed AndroidX fragment transactions. A same-turn `Window.Page`
replacement could detach the outgoing fragment container before those
transactions ran, terminating the process with
`IllegalArgumentException: No view found for id ... ShellItemRenderer`.

Skipping cleanup is not safe: the outgoing `ContainerView.CurrentView`
must still be cleared so the replaced MAUI view graph is not retained.

### Description of Change

- Serialize and coalesce navigation-root requests with last-request-wins
behavior under reentrancy.
- Drain committed transactions while the outgoing native root remains
attached, including the distinct Activity fragment manager used by
compatibility Shell during replacement.
- Retry boundedly through the Android main looper when AndroidX is
already executing transactions.
- Attach a prepared Window root before committing its content fragment,
and explicitly discard superseded roots and newly-created handlers.
- Preserve current toolbar mappings with identity/version tracking and
safe native reparenting.
- Keep modal disconnects scoped to their owning fragment manager to
avoid re-entering Activity-level dismissal transactions.
- Clear outgoing `ContainerView` content and release Visual Diagnostics
native Activity/view subscriptions during handler teardown.
- Add Android device regressions for Shell/Flyout root replacement,
reentrancy, retries, stale roots and toolbars, nested FlyoutPage hosts,
modal teardown, and disconnect/reconnect completion.

### What NOT to Do

- Do not remove `ContainerView.CurrentView` cleanup to hide the crash;
that retains the outgoing MAUI view graph.
- Do not use `MainThread.BeginInvokeOnMainThread` for the transaction
retry; it can execute inline on the UI thread before AndroidX clears its
executing state.
- Do not drain the Activity fragment manager during scoped modal
disconnect; that can re-enter the dismissal transaction already running
there.

### Empirical Validation

The failure still reproduced on current `main` on an Android API 34
emulator. The exact stress scenario alternated new Shell and FlyoutPage
roots in the same turn and crashed before the fix with the missing
fragment-container exception.

After the fix, all 50 iterations completed, the final Shell root was
attached, the process remained alive, and logcat contained no fatal
exception, missing-view exception, or fragment-manager busy exception.

Final targeted API 34 results:

| Category | Result |
|---|---:|
| Window | 34/34 passed |
| FlyoutPage | 17/17 passed |
| Modal | 44/44 passed |

The final Android Controls DeviceTests Release app also builds
successfully.

#### Before fix — reproduced on current main


https://github.com/user-attachments/assets/4f7c8e51-7a22-45c9-943b-00d061db3537

#### After fix — same 50-iteration stress scenario


https://github.com/user-attachments/assets/59efd50d-ff03-409d-9b40-7c608c3669f5

### Issues Fixed

Supersedes #36212. Follow-up to #35372 and #36152.

---------
kubaflo added a commit that referenced this pull request Sep 21, 2026
…eplacement (#38214)

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

### Root Cause

Android Shell and FlyoutPage create content through asynchronously
committed AndroidX fragment transactions. A same-turn `Window.Page`
replacement could detach the outgoing fragment container before those
transactions ran, terminating the process with
`IllegalArgumentException: No view found for id ... ShellItemRenderer`.

Skipping cleanup is not safe: the outgoing `ContainerView.CurrentView`
must still be cleared so the replaced MAUI view graph is not retained.

### Description of Change

- Serialize and coalesce navigation-root requests with last-request-wins
behavior under reentrancy.
- Drain committed transactions while the outgoing native root remains
attached, including the distinct Activity fragment manager used by
compatibility Shell during replacement.
- Retry boundedly through the Android main looper when AndroidX is
already executing transactions.
- Attach a prepared Window root before committing its content fragment,
and explicitly discard superseded roots and newly-created handlers.
- Preserve current toolbar mappings with identity/version tracking and
safe native reparenting.
- Keep modal disconnects scoped to their owning fragment manager to
avoid re-entering Activity-level dismissal transactions.
- Clear outgoing `ContainerView` content and release Visual Diagnostics
native Activity/view subscriptions during handler teardown.
- Add Android device regressions for Shell/Flyout root replacement,
reentrancy, retries, stale roots and toolbars, nested FlyoutPage hosts,
modal teardown, and disconnect/reconnect completion.

### What NOT to Do

- Do not remove `ContainerView.CurrentView` cleanup to hide the crash;
that retains the outgoing MAUI view graph.
- Do not use `MainThread.BeginInvokeOnMainThread` for the transaction
retry; it can execute inline on the UI thread before AndroidX clears its
executing state.
- Do not drain the Activity fragment manager during scoped modal
disconnect; that can re-enter the dismissal transaction already running
there.

### Empirical Validation

The failure still reproduced on current `main` on an Android API 34
emulator. The exact stress scenario alternated new Shell and FlyoutPage
roots in the same turn and crashed before the fix with the missing
fragment-container exception.

After the fix, all 50 iterations completed, the final Shell root was
attached, the process remained alive, and logcat contained no fatal
exception, missing-view exception, or fragment-manager busy exception.

Final targeted API 34 results:

| Category | Result |
|---|---:|
| Window | 34/34 passed |
| FlyoutPage | 17/17 passed |
| Modal | 44/44 passed |

The final Android Controls DeviceTests Release app also builds
successfully.

#### Before fix — reproduced on current main


https://github.com/user-attachments/assets/4f7c8e51-7a22-45c9-943b-00d061db3537

#### After fix — same 50-iteration stress scenario


https://github.com/user-attachments/assets/59efd50d-ff03-409d-9b40-7c608c3669f5

### Issues Fixed

Supersedes #36212. Follow-up to #35372 and #36152.

---------
kubaflo added a commit that referenced this pull request Sep 27, 2026
…eplacement (#38214)

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

### Root Cause

Android Shell and FlyoutPage create content through asynchronously
committed AndroidX fragment transactions. A same-turn `Window.Page`
replacement could detach the outgoing fragment container before those
transactions ran, terminating the process with
`IllegalArgumentException: No view found for id ... ShellItemRenderer`.

Skipping cleanup is not safe: the outgoing `ContainerView.CurrentView`
must still be cleared so the replaced MAUI view graph is not retained.

### Description of Change

- Serialize and coalesce navigation-root requests with last-request-wins
behavior under reentrancy.
- Drain committed transactions while the outgoing native root remains
attached, including the distinct Activity fragment manager used by
compatibility Shell during replacement.
- Retry boundedly through the Android main looper when AndroidX is
already executing transactions.
- Attach a prepared Window root before committing its content fragment,
and explicitly discard superseded roots and newly-created handlers.
- Preserve current toolbar mappings with identity/version tracking and
safe native reparenting.
- Keep modal disconnects scoped to their owning fragment manager to
avoid re-entering Activity-level dismissal transactions.
- Clear outgoing `ContainerView` content and release Visual Diagnostics
native Activity/view subscriptions during handler teardown.
- Add Android device regressions for Shell/Flyout root replacement,
reentrancy, retries, stale roots and toolbars, nested FlyoutPage hosts,
modal teardown, and disconnect/reconnect completion.

### What NOT to Do

- Do not remove `ContainerView.CurrentView` cleanup to hide the crash;
that retains the outgoing MAUI view graph.
- Do not use `MainThread.BeginInvokeOnMainThread` for the transaction
retry; it can execute inline on the UI thread before AndroidX clears its
executing state.
- Do not drain the Activity fragment manager during scoped modal
disconnect; that can re-enter the dismissal transaction already running
there.

### Empirical Validation

The failure still reproduced on current `main` on an Android API 34
emulator. The exact stress scenario alternated new Shell and FlyoutPage
roots in the same turn and crashed before the fix with the missing
fragment-container exception.

After the fix, all 50 iterations completed, the final Shell root was
attached, the process remained alive, and logcat contained no fatal
exception, missing-view exception, or fragment-manager busy exception.

Final targeted API 34 results:

| Category | Result |
|---|---:|
| Window | 34/34 passed |
| FlyoutPage | 17/17 passed |
| Modal | 44/44 passed |

The final Android Controls DeviceTests Release app also builds
successfully.

#### Before fix — reproduced on current main


https://github.com/user-attachments/assets/4f7c8e51-7a22-45c9-943b-00d061db3537

#### After fix — same 50-iteration stress scenario


https://github.com/user-attachments/assets/59efd50d-ff03-409d-9b40-7c608c3669f5

### Issues Fixed

Supersedes #36212. Follow-up to #35372 and #36152.

---------
kubaflo added a commit that referenced this pull request Sep 27, 2026
…eplacement (#38214)

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

### Root Cause

Android Shell and FlyoutPage create content through asynchronously
committed AndroidX fragment transactions. A same-turn `Window.Page`
replacement could detach the outgoing fragment container before those
transactions ran, terminating the process with
`IllegalArgumentException: No view found for id ... ShellItemRenderer`.

Skipping cleanup is not safe: the outgoing `ContainerView.CurrentView`
must still be cleared so the replaced MAUI view graph is not retained.

### Description of Change

- Serialize and coalesce navigation-root requests with last-request-wins
behavior under reentrancy.
- Drain committed transactions while the outgoing native root remains
attached, including the distinct Activity fragment manager used by
compatibility Shell during replacement.
- Retry boundedly through the Android main looper when AndroidX is
already executing transactions.
- Attach a prepared Window root before committing its content fragment,
and explicitly discard superseded roots and newly-created handlers.
- Preserve current toolbar mappings with identity/version tracking and
safe native reparenting.
- Keep modal disconnects scoped to their owning fragment manager to
avoid re-entering Activity-level dismissal transactions.
- Clear outgoing `ContainerView` content and release Visual Diagnostics
native Activity/view subscriptions during handler teardown.
- Add Android device regressions for Shell/Flyout root replacement,
reentrancy, retries, stale roots and toolbars, nested FlyoutPage hosts,
modal teardown, and disconnect/reconnect completion.

### What NOT to Do

- Do not remove `ContainerView.CurrentView` cleanup to hide the crash;
that retains the outgoing MAUI view graph.
- Do not use `MainThread.BeginInvokeOnMainThread` for the transaction
retry; it can execute inline on the UI thread before AndroidX clears its
executing state.
- Do not drain the Activity fragment manager during scoped modal
disconnect; that can re-enter the dismissal transaction already running
there.

### Empirical Validation

The failure still reproduced on current `main` on an Android API 34
emulator. The exact stress scenario alternated new Shell and FlyoutPage
roots in the same turn and crashed before the fix with the missing
fragment-container exception.

After the fix, all 50 iterations completed, the final Shell root was
attached, the process remained alive, and logcat contained no fatal
exception, missing-view exception, or fragment-manager busy exception.

Final targeted API 34 results:

| Category | Result |
|---|---:|
| Window | 34/34 passed |
| FlyoutPage | 17/17 passed |
| Modal | 44/44 passed |

The final Android Controls DeviceTests Release app also builds
successfully.

#### Before fix — reproduced on current main


https://github.com/user-attachments/assets/4f7c8e51-7a22-45c9-943b-00d061db3537

#### After fix — same 50-iteration stress scenario


https://github.com/user-attachments/assets/59efd50d-ff03-409d-9b40-7c608c3669f5

### Issues Fixed

Supersedes #36212. Follow-up to #35372 and #36152.

---------
kubaflo added a commit that referenced this pull request Oct 3, 2026
…eplacement (#38214)

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

### Root Cause

Android Shell and FlyoutPage create content through asynchronously
committed AndroidX fragment transactions. A same-turn `Window.Page`
replacement could detach the outgoing fragment container before those
transactions ran, terminating the process with
`IllegalArgumentException: No view found for id ... ShellItemRenderer`.

Skipping cleanup is not safe: the outgoing `ContainerView.CurrentView`
must still be cleared so the replaced MAUI view graph is not retained.

### Description of Change

- Serialize and coalesce navigation-root requests with last-request-wins
behavior under reentrancy.
- Drain committed transactions while the outgoing native root remains
attached, including the distinct Activity fragment manager used by
compatibility Shell during replacement.
- Retry boundedly through the Android main looper when AndroidX is
already executing transactions.
- Attach a prepared Window root before committing its content fragment,
and explicitly discard superseded roots and newly-created handlers.
- Preserve current toolbar mappings with identity/version tracking and
safe native reparenting.
- Keep modal disconnects scoped to their owning fragment manager to
avoid re-entering Activity-level dismissal transactions.
- Clear outgoing `ContainerView` content and release Visual Diagnostics
native Activity/view subscriptions during handler teardown.
- Add Android device regressions for Shell/Flyout root replacement,
reentrancy, retries, stale roots and toolbars, nested FlyoutPage hosts,
modal teardown, and disconnect/reconnect completion.

### What NOT to Do

- Do not remove `ContainerView.CurrentView` cleanup to hide the crash;
that retains the outgoing MAUI view graph.
- Do not use `MainThread.BeginInvokeOnMainThread` for the transaction
retry; it can execute inline on the UI thread before AndroidX clears its
executing state.
- Do not drain the Activity fragment manager during scoped modal
disconnect; that can re-enter the dismissal transaction already running
there.

### Empirical Validation

The failure still reproduced on current `main` on an Android API 34
emulator. The exact stress scenario alternated new Shell and FlyoutPage
roots in the same turn and crashed before the fix with the missing
fragment-container exception.

After the fix, all 50 iterations completed, the final Shell root was
attached, the process remained alive, and logcat contained no fatal
exception, missing-view exception, or fragment-manager busy exception.

Final targeted API 34 results:

| Category | Result |
|---|---:|
| Window | 34/34 passed |
| FlyoutPage | 17/17 passed |
| Modal | 44/44 passed |

The final Android Controls DeviceTests Release app also builds
successfully.

#### Before fix — reproduced on current main


https://github.com/user-attachments/assets/4f7c8e51-7a22-45c9-943b-00d061db3537

#### After fix — same 50-iteration stress scenario


https://github.com/user-attachments/assets/59efd50d-ff03-409d-9b40-7c608c3669f5

### Issues Fixed

Supersedes #36212. Follow-up to #35372 and #36152.

---------
kubaflo added a commit that referenced this pull request Oct 3, 2026
…eplacement (#38214)

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

### Root Cause

Android Shell and FlyoutPage create content through asynchronously
committed AndroidX fragment transactions. A same-turn `Window.Page`
replacement could detach the outgoing fragment container before those
transactions ran, terminating the process with
`IllegalArgumentException: No view found for id ... ShellItemRenderer`.

Skipping cleanup is not safe: the outgoing `ContainerView.CurrentView`
must still be cleared so the replaced MAUI view graph is not retained.

### Description of Change

- Serialize and coalesce navigation-root requests with last-request-wins
behavior under reentrancy.
- Drain committed transactions while the outgoing native root remains
attached, including the distinct Activity fragment manager used by
compatibility Shell during replacement.
- Retry boundedly through the Android main looper when AndroidX is
already executing transactions.
- Attach a prepared Window root before committing its content fragment,
and explicitly discard superseded roots and newly-created handlers.
- Preserve current toolbar mappings with identity/version tracking and
safe native reparenting.
- Keep modal disconnects scoped to their owning fragment manager to
avoid re-entering Activity-level dismissal transactions.
- Clear outgoing `ContainerView` content and release Visual Diagnostics
native Activity/view subscriptions during handler teardown.
- Add Android device regressions for Shell/Flyout root replacement,
reentrancy, retries, stale roots and toolbars, nested FlyoutPage hosts,
modal teardown, and disconnect/reconnect completion.

### What NOT to Do

- Do not remove `ContainerView.CurrentView` cleanup to hide the crash;
that retains the outgoing MAUI view graph.
- Do not use `MainThread.BeginInvokeOnMainThread` for the transaction
retry; it can execute inline on the UI thread before AndroidX clears its
executing state.
- Do not drain the Activity fragment manager during scoped modal
disconnect; that can re-enter the dismissal transaction already running
there.

### Empirical Validation

The failure still reproduced on current `main` on an Android API 34
emulator. The exact stress scenario alternated new Shell and FlyoutPage
roots in the same turn and crashed before the fix with the missing
fragment-container exception.

After the fix, all 50 iterations completed, the final Shell root was
attached, the process remained alive, and logcat contained no fatal
exception, missing-view exception, or fragment-manager busy exception.

Final targeted API 34 results:

| Category | Result |
|---|---:|
| Window | 34/34 passed |
| FlyoutPage | 17/17 passed |
| Modal | 44/44 passed |

The final Android Controls DeviceTests Release app also builds
successfully.

#### Before fix — reproduced on current main


https://github.com/user-attachments/assets/4f7c8e51-7a22-45c9-943b-00d061db3537

#### After fix — same 50-iteration stress scenario


https://github.com/user-attachments/assets/59efd50d-ff03-409d-9b40-7c608c3669f5

### Issues Fixed

Supersedes #36212. Follow-up to #35372 and #36152.

---------
@github-actions github-actions Bot locked and limited conversation to collaborators Oct 6, 2026
@github-actions github-actions Bot modified the milestones: .NET 10 SR11, .NET 10 SR12 Oct 21, 2026

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — 563fa14b Deployed Sep 4, 2026 by kubaflo via conclusion #1749
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

area-controls-window Window platform/android s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-fix-win AI found a better alternative fix than the PR 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.

7 participants