Skip to content

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

Closed
PureWeen wants to merge 22 commits into
mainfrom
android-flyoutpage-detail-childfm
Closed

PureWeen wants to merge 22 commits into
mainfrom
android-flyoutpage-detail-childfm

Conversation

@PureWeen

@PureWeen PureWeen commented Jun 29, 2026 •

Copy link
Copy Markdown
Member

Note

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

Root Cause

Android Shell and FlyoutPage render content through fragment transactions that can be committed asynchronously. During a same-turn Window.Page replacement, NavigationRootManager removed the outgoing native root before those transactions executed. AndroidX then tried to resolve a fragment target such as navigationlayout_content or Shell's generated frame ID after that target had been detached, terminating the process with IllegalArgumentException: No view found for id ....

The cleanup cannot simply be omitted: leaving ContainerView.CurrentView populated retains the replaced MAUI view graph, which was the leak fixed by #35372 and reverted by #36152 after exposing the transaction race.

Description of Change

  • Before clearing an outgoing live root, cancel deferred callbacks and execute already-committed transactions on the owning FragmentManager while target views still exist. During replacement, also settle a distinct activity manager because compatibility Shell can commit there.
  • Restore ContainerView.CurrentView = null after the drain so replaced Shell/Flyout roots release their managed and native view graphs.
  • Serialize root swaps and replay only the latest request when fragment or handler lifecycle code re-enters Connect/Disconnect. Each request completes exactly once as Applied, Superseded, Cancelled, or Failed.
  • Publish and attach a prepared Window root before committing its navigationlayout_content fragment. This preserves synchronous attachment on the normal path and prevents a pending fragment from targeting an unparented native root; terminal request completion remains separate.
  • If AndroidX reports that its FragmentManager is already executing transactions, retain the entire request and retry it through Android's main-looper Handler.Post after the current transaction unwinds.
  • Publish root, drawer, toolbar, coordinator, and inset-listener state atomically so an older construction frame cannot overwrite or detach the winning root.
  • Preserve toolbar mappings registered while a root request is deferred and explicitly reparent the native toolbar into the winning root's app bar.
  • Defer WindowHandler teardown completion with lifecycle generations so a stale disconnect callback cannot unsubscribe or clear a reconnected handler.
  • Limit disconnect-time settlement to the fragment manager that owns the root fragment. This avoids re-entering the activity manager from ModalFragment.OnDismiss while preserving production window fallback to the activity manager when no scoped manager exists.
  • Keep FlyoutViewHandler.Android.cs identical to main, preserving its deferred, cancellable lifecycle behavior and support for nested FlyoutPage hosts.
  • Add Android device regressions for:
    • Flyout detail replacement followed by same-turn Window root replacement;
    • stale ContainerView cleanup;
    • Shell item switching followed by same-turn Window root replacement;
    • Shell root replacement from page Loaded;
    • Flyout root replacement from detail Loaded;
    • ContentPage-to-Shell same-turn replacement;
    • synchronous mapper re-entry from an AndroidX fragment lifecycle callback;
    • root replacement while a FragmentManager is already executing, including final toolbar attachment;
    • root replacement re-entered from Disconnect;
    • Window replacement during FlyoutViewHandler.CreatePlatformView, including live content, toolbar ownership, and discarded-handler cleanup;
    • a FlyoutPage pushed inside a NavigationPage, matching the previous blank-detail negative control.

What NOT to Do

  • Do not validate Flyout detail ownership by comparing its container ID with the window-level navigation root. Nested FlyoutPage hosts have their own valid detail container; the previous guard rendered nested details blank.
  • Do not remove ContainerView.CurrentView cleanup to hide the crash. That retains the outgoing MAUI view graph.
  • Do not redesign Flyout detail hosting solely to avoid this teardown race. The race is shared by Shell and FlyoutPage and belongs at the root teardown boundary.
  • Do not use MainThread.BeginInvokeOnMainThread to retry this transaction. It executes inline when already on the UI thread and recursively retries before AndroidX clears its executing state.

Empirical Validation

The final implementation was tested on real Android emulators and compared against the previous PR head.

Scenario API 33 API 35
Category=FlyoutPage 17/17 passed 17/17 passed
Category=Window 24/24 passed 24/24 passed
Category=Modal 44/44 passed 44/44 passed on final rerun
Category=Memory 56/56 passed -
Nested Flyout UI scenarios 25/25 passed 25/25 passed
Relevant fatal/logcat exceptions none none

Nested UI validation covered NavigationPage and modal hosting, detail swaps, flyout interaction, navigation inside the detail, plain detail replacement, root teardown, rotation, background/resume, and final root replacement.

The full API 35 Controls device suite completed 975 tests without a fragment or process crash. Its nine failures were GC/leak assertions that reproduced when run alone on that emulator; the same Memory category passed 56/56 on API 33.

The previous active-container guard was run as a negative control on API 35: 1/25 passed and 24/25 failed, with the nested Flyout toolbar visible over a blank detail area. The final design passed the same 25/25 scenarios.

Exact-head device CI also reproduced the Shell interaction on both Android Mono and CoreCLR:

IllegalArgumentException: No view found for id ... for fragment ShellItemRenderer

Review

Fresh multi-model review identified that a synchronous handler map from inside Fragment.OnCreateView could re-enter Connect, call ExecutePendingTransactions() on a manager already executing, or let stale outer state clobber the newer root. A mechanism-targeted device test reproduced FragmentManager is already executing transactions.

The versioned implementation was then replaced with serialized, last-request-wins root swaps after review found stale-build and toolbar hazards. A full-suite probe exposed a cross-manager modal teardown crash in the first serialized candidate; disconnect now settles only its owning manager. Further adversarial review found and fixed transient released-root publication, production owner fallback, exception-path queue loss, deferred-callback ordering, a discarded Flyout handler leak, inline retry recursion, deferred toolbar reparenting, typed handler access after disconnect, main-looper shutdown handling, and the published-but-unparented fragment window. The latest diff received independent Claude Opus and GPT-5.6 adversarial reviews with no unresolved correctness findings.

Issues Fixed

Follow-up to #35372 and #36152.

Fixes the FlyoutPage detail-swap teardown crash that surfaces as the
SwappingDetailPageWorksForSplitFlyoutBehavior device test failure on the
inflight/candidate branch.

The FlyoutView was the only Android page-host that committed its content
fragment directly to the activity FragmentManager. When the FlyoutView is torn
down, NavigationRootManager.ClearPlatformParts() synchronously removes the
DrawerLayout that hosts navigationlayout_content. A detail-fragment Replace that
was queued just before teardown then runs against a container that is no longer
in the activity view tree and throws
java.lang.IllegalArgumentException: No view found for id ... navigationlayout_content,
killing the process.

Host the detail page in a long-lived FlyoutDetailFragment and commit detail
swaps to that fragment's ChildFragmentManager instead of the activity
FragmentManager. The detail container is then resolved within the host's own
(always-intact) view subtree, so a queued transaction can never orphan against
the activity FragmentManager; the child FragmentManager and any pending
transaction are torn down together with the host. This mirrors how every other
Android page-host scopes its content (NavigationViewFragment, FragmentContainer,
ShellFragmentContainer, and NavigationRootManager's own content fragment).

NavigationRootManager keeps the synchronous CurrentView = null behavior from
#35372, so the ReplacedFlyoutPageRootClearsOldContainerView leak test still
passes (no leak regression).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Host the detail container in a FragmentContainerView instead of a bare
FrameLayout. FragmentContainerView is the container type every other fragment
host on Android uses (navigationlayout_content, fragment_backstack,
NavigationViewFragment); it dispatches WindowInsets to the hosted fragment and
z-orders entering/exiting fragments correctly during transitions.

Route the detail transaction through the BeginTransactionEx/ReplaceEx wrappers
for consistency with the rest of the handler, and expand the RemoveDetailHost
comment to document why the reorder-allowed Remove collapses a still-pending
host add (Contains() stays true across that window).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@PureWeen

PureWeen commented Jul 1, 2026

Copy link
Copy Markdown
Member Author

/azp run maui-pr-devicetests, maui-pr-uitests

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines successfully started running 2 pipeline(s).

@kubaflo

This comment has been minimized.

@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 Jul 5, 2026
@MauiBot MauiBot removed the s/agent-review-in-progress AI review is currently running for this PR label Jul 5, 2026
@github-actions

This comment has been minimized.

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

Looks like there are some test failures

Base automatically changed from inflight/candidate to main July 6, 2026 14:09

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

🔍 AI-generated review (multi-model pipeline: Opus 4.8 · GPT-5.5 · Gemini 3.1 Pro), on behalf of @kubaflo. Each model reviewed independently; findings below are cross-pollinated, and the headline item had unanimous 3/3 agreement plus an AndroidX-source cross-check.

Review — #36212 [Android] Scope FlyoutView detail to a child FragmentManager

Independent assessment

The redesign — hosting the detail page in a long-lived FlyoutDetailFragment and committing detail swaps to that fragment's ChildFragmentManager instead of the activity FragmentManager — is architecturally sound and consistent with every other MAUI Android page-host (NavigationViewFragment, FragmentContainer, ShellFragmentContainer, NavigationRootManager). It correctly fixes the primary crash: a queued detail swap is now torn down together with its host and resolves its container inside the host's own (intact) view subtree. The NavigationRootManager leak fix from #35372 is preserved.

❌ Primary finding — the teardown-collapse guard rests on an incorrect AndroidX assumption (3/3 models agree)

FlyoutViewHandler.Android.cs:135-137 (comment) & :164 (guard).

The comment claims: "Contains() stays true across that window (FragmentManager.FindFragmentById resolves a fragment as soon as its add is committed)." This is factually wrong. Verified against AndroidX FragmentStore.java: findFragmentById searches only mAdded then mActive, and both are populated exclusively by addFragment()/makeActive(), which run during transaction execution (BackStackRecord.executeOps, next looper turn) — never at commit().

Consequence — in the exact edge the comment addresses (the host's own Replace(navigationlayout_content, host) is committed-but-not-executed and DisconnectHandler fires in the same frame): Contains(detailHost) is false, so !fragmentManager.Contains(detailHost) is true and RemoveDetailHost returns at :165-166 without committing the reorder-Remove. The pending Add is therefore never collapsed; if NavigationRootManager has synchronously detached navigationlayout_content, the queued Add executes on the next looper turn and throws the same IllegalArgumentException: No view found for id … navigationlayout_content this PR is fixing. The guard defeats the very collapse the comment says it enables. (On the synchronous-commit path RunOrWaitForResume returns null, so _pendingFragment is null and CancelPendingFragment can't cancel this add either.)

Fix (unanimous): don't gate the just-created host's teardown Remove on Contains — FragmentTransaction.Remove on a pending-add fragment is safe and is exactly what lets the FragmentManager collapse Add+Remove:

if (fragmentManager is null ||
    fragmentManager.IsDestroyed(context) ||
    fragmentManager.IsStateSaved)   // drop the !Contains(detailHost) condition
{
    return;
}

At minimum, correct the comment so it stops asserting a false AndroidX behavior. See the inline comment on :164.

Important calibration: this is not a new regression. The old code committed Replace(navigationlayout_content, ScopedFragment) on every detail swap, so it had a larger pending-window exposure against that container; this PR shrinks it to a single one-time host add and fixes the documented (detail-swap-then-teardown) crash — by then the host is fully added, Contains is trivially true, and Remove runs correctly. So the design is mergeable; this is a narrow, non-regressive hole in the defensive path that should be closed (trivially) before merge.

💡 Secondary (single-model, low severity)

  • No regression test — the diff touches 0 test files. A lifecycle/crash fix like this warrants a Category=FlyoutPage device/UI test reproducing the synchronous detail-swap-then-teardown kill; the repo strongly favors this. (Opus)
  • CancelPendingDetail leaves stale pending state (FlyoutDetailFragment.Android.cs:96) — it disposes _pendingDetail but leaves _hasPendingDetail/_pendingDetailView/_pendingDetailMauiContext populated, so a later OnViewCreated on a re-attached host could apply a cancelled detail. Clear those three fields too. (Gemini)
  • EnsureDetailHost caches the host even if the add is dropped (:111 sets the field before RunOrWaitForResume) — if the FM is destroyed the add is dropped but the field stays non-null, so it never retries. Benign (destroyed ⇒ nothing to render into), minor divergence from old code. (Opus)

CI

162 checks pass. The red legs are maui-pr-uitests (macOS UITests Controls ListView / CollectionView) — not plausibly caused by this change: both changed files are .Android.cs (excluded from the MacCatalyst binary), the concrete failure is MemoryLeakB42329 (a Catalyst test) timing out, and ~4/5 recent base builds of that suite also failed (systemic macOS UI-test instability). All Android device-test Helix jobs passed. Your existing CHANGES_REQUESTED ("test failures") points at that unrelated macOS flakiness.

Verdict: NEEDS_CHANGES (consensus)

Confidence: medium-high. The child-FragmentManager architecture is correct, matches the established MAUI pattern, and fixes the primary crash with no new regression. Before merge: (1) drop the !Contains(detailHost) condition (and fix the load-bearing comment), and (2) ideally add a Category=FlyoutPage regression test. Not LGTM yet, but the required change is small and doesn't touch the design.

ℹ Automated multi-model review. This is advisory — a human maintainer makes the final merge decision.

if (fragmentManager is null ||
fragmentManager.IsDestroyed(context) ||
fragmentManager.IsStateSaved ||
!fragmentManager.Contains(detailHost))

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.

🔍 AI-generated (multi-model, on behalf of @kubaflo) — this !fragmentManager.Contains(detailHost) condition undermines the mitigation the method comment describes.

Contains(detailHost) is FindFragmentById(host.Id) != null. Per AndroidX FragmentStore.findFragmentById, that searches only mAdded/mActive, which are populated by addFragment()/makeActive() during transaction execution (BackStackRecord.executeOps, next looper turn) — not at commit(). So while the host's own Replace(navigationlayout_content, host) is committed-but-not-executed, Contains returns false, this guard early-returns, and the reorder-Remove that's supposed to collapse the pending Add is never committed. If navigationlayout_content was synchronously detached, the pending Add then executes against a missing container → the exact No view found for id navigationlayout_content crash this PR fixes.

Suggested fix — drop this condition; FragmentTransaction.Remove on a pending-add fragment is safe and is what enables the Add+Remove collapse:

if (fragmentManager is null ||
    fragmentManager.IsDestroyed(context) ||
    fragmentManager.IsStateSaved)
{
    return;
}

(Note: on the synchronous-commit path RunOrWaitForResume returns null, so _pendingFragment is null and CancelPendingFragment can't cancel this add either.) At minimum, please correct the comment above, which asserts FindFragmentById resolves "as soon as its add is committed" — that AndroidX behavior does not hold.

@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 Jul 16, 2026
@MauiBot MauiBot added s/agent-fix-pr-picked AI could not beat the PR fix - PR is the best among all candidates s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review) labels Jul 16, 2026
MauiBot

This comment was marked as outdated.

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Expert Review — 2 findings

See inline comments for details.

// Cancels a detail transaction that has been queued but not yet committed.
public void CancelPendingDetail()
{
_pendingDetail?.Dispose();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[major] Android FragmentManager lifecycle — CancelPendingDetail() only disposes the pending RunOrWaitForResume callback, but it leaves _hasPendingDetail, _pendingDetailView, and _pendingDetailMauiContext intact. FlyoutViewHandler.CancelPendingFragment() calls this during disconnect/release; if the host fragment's view is later created or recreated, OnViewCreated will still apply that stale queued detail from the disconnected handler. Clear the queued detail fields here as well as disposing _pendingDetail.

if (fragmentManager is null ||
fragmentManager.IsDestroyed(context) ||
fragmentManager.IsStateSaved ||
!fragmentManager.Contains(detailHost))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[major] Android FragmentManager lifecycle — This Contains(detailHost) guard can skip the very removal needed to cancel a host transaction that has been committed but not executed yet. Contains() is FindFragmentById(fragment.Id), which does not reliably see a fragment still only present in a pending Replace op; returning here lets that pending host add execute after the FlyoutView has been torn down, recreating the original orphaned-container/crash path. Once the manager/context are valid and state is not saved, queue the remove for detailHost without gating on Contains, or track whether the add transaction was committed separately.

@MauiBot MauiBot removed the s/agent-review-in-progress AI review is currently running for this PR label Jul 17, 2026

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Expert Review — 8 findings

See inline comments for details.

MauiBot

This comment was marked as outdated.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: ebd11ef3-b6c2-474b-94af-6158ba87fc7e

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.

Review details

  • Files reviewed: 8/8 changed files
  • Comments generated: 2
  • Review effort level: Lite

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: ebd11ef3-b6c2-474b-94af-6158ba87fc7e

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.

Review details

Suppressed comments (1)

Previously missed (1) — in code that hasn't changed since the last review.

src/Core/src/Platform/Android/Navigation/NavigationRootManager.cs:350

  • StopRootSwapsPermanently() clears _viewFragment without removing the fragment transaction (and never calls SetContentView(null)), which can leave an ElementBasedFragment attached in the FragmentManager while the NavigationRootManager reports RootView=null. That risks retaining the outgoing MAUI view graph and skipping RootViewChanged notifications on this terminal path.
			var outgoingRootView = _rootView;
			_rootView = null;
			_viewFragment = null;
			ReleaseOutgoingRoot(outgoingRootView, clearToolbarElement: true);
  • Files reviewed: 8/8 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

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

Adversarial re-review of the latest fixes — one remaining test-coverage concern.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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.

Review details

  • Files reviewed: 8/8 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

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

Adversarial re-review of the strengthened teardown regression test — the prior concern is addressed; one assertion can still miss retained fragment state.

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Expert Review — 6 findings

See inline comments for details.

MauiBot

This comment was marked as outdated.

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

@PureWeen Cross-model arbitration of the six new MauiBot comments: I do not think they justify another production-code round. The modal non-Applied path has no ordinary same-manager reentrant caller; WindowHandler supersession drains the winning request and busy cancellation preserves the previous root; the permanent latch is restricted to monotonic Activity/looper shutdown; retry infrastructure is reused during an episode and released afterward; and the test seams follow the deterministic seam MauiBot previously requested. The one mechanically true case—forced disconnect retry exhaustion completing Cancelled before teardown—is low-reachability and primarily an optional coverage gap, not the claimed unrecoverable production leak.

The two material gates remain unchanged: please address the open FindFragmentById(navigationlayout_content) assertion comment so the test proves no active/detached fragment remains, and run the current head through Android device tests (Window, FlyoutPage, Modal, and Memory). Build 1556255 is green, but maui-pr does not execute these device tests.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: effc07d0-9f72-494c-ae82-2a157b8718d3

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.

Review details

Suppressed comments (2)

src/Controls/tests/DeviceTests/Elements/Window/WindowTests.cs:256

  • Shell.CurrentItem is typed as ShellItem, so assigning a ContentPage here will not compile. Create a ShellItem (e.g., FlyoutItem/TabBar) containing shellPage, add it to shell.Items, and set shell.CurrentItem to that item instead.
			var shellPage = new ContentPage { Content = new Label { Text = "Shell page" } };
			var replacementPage = new ContentPage
			{
				Content = new Label { Text = "Replacement page" }
			};
			var shell = new Shell { CurrentItem = shellPage };
			var window = new Window(shell);

src/Controls/tests/DeviceTests/Elements/Window/WindowTests.cs:317

  • Shell.CurrentItem expects a ShellItem, so setting it to shellPage (a ContentPage) will not compile. Wrap shellPage in a ShellItem (e.g., var item = new FlyoutItem { Items = { shellPage } };) and set shell.CurrentItem = item.
			var window = new Window(new ContentPage());
			var shellPage = new ContentPage { Content = new Label { Text = "Shell page" } };
			var shell = new Shell { CurrentItem = shellPage };

  • Files reviewed: 8/8 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

@kubaflo

This comment has been minimized.

1 similar comment
@kubaflo

kubaflo commented Aug 20, 2026

Copy link
Copy Markdown
Contributor

/review -b improved-reviewer -p android

@PureWeen PureWeen left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Adversarial review

❌ Regression — QuiesceOutgoingRoot treats a detached root as already quiesced, even when its content fragment remains active. A rapid root/detail swap can detach the outgoing view before its SetContentView transaction settles; the subsequent swap or disconnect then skips the owning FragmentManager drain and can leave that stale transaction to run against the replaced container. Restore a state-dependent guard for detached roots with an active content fragment, or otherwise defer/cancel until the manager is safe to drain.

Flagged by: 2/3 reviewers after adversarial dispute.

Test coverage: The added device tests cover detached roots after their fragment work has settled, but not detachment while the content transaction is still pending; add that interleaving to protect this teardown path.

Methodology: 3 independent reviewers with adversarial consensus. Existing reviews were checked and no matching adversarial review was present at this head.

@kubaflo

This comment has been minimized.

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Expert Review — 9 findings

See inline comments for details.

@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

@PureWeen — new AI review results are available based on commit 601bb52.

Gate Inconclusive Confidence Unknown Platform Android


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

Gate Result: ⚠️ INCONCLUSIVE

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

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

Test Without Fix (expect FAIL) With Fix (expect PASS)
📱 ControlsHandlerTestBase ControlsHandlerTestBase 🛠️ BUILD ERROR ⚠️ ENV ERROR
📱 FlyoutPageTests (SwappingDetailThenReplacingWindowRootDoesNotCrash, NestedFlyoutPageDetailSurvivesRootReplacement) Category=FlyoutPage 🛠️ BUILD ERROR ✅ PASS — 406s
🔴 Without fix — 📱 ControlsHandlerTestBase: 🛠️ BUILD ERROR · 171s

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

/home/vsts/work/1/s/src/Controls/tests/DeviceTests/Elements/Window/WindowTests.cs(912,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 · 394s

No log file found

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

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

/home/vsts/work/1/s/src/Controls/tests/DeviceTests/Elements/Window/WindowTests.cs(912,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 ✅ · 406s

(no coded error found; showing last 1200 chars)

59.640 18193 18306 I DOTNET  : Xml file was written to the provided writer.
      08-20 19:22:59.641 18193 18306 I DOTNET  : === TEST EXECUTION SUMMARY ===
      08-20 19:22:59.641 18193 18306 I DOTNET  : Tests run: 600 Passed: 15 Inconclusive: 0 Failed: 0 Ignored: 585 Skipped: 0
info: <<XHARNESS_RESULT_START>>
      {
        "version": 1,
        "machineName": "runnervmyebny",
        "exitCode": 0,
        "exitCodeName": "SUCCESS",
        "platform": "android",
        "instrumentationExitCode": 0,
        "device": "emulator-5554",
        "deviceOsVersion": "API 30",
        "architecture": "x86_64",
        "files": [
          {
            "name": "testResults-4837abc1862b48228cfc30e42530b8ef.xml",
            "type": "test-results"
          },
          {
            "name": "adb-logcat-com.microsoft.maui.controls.devicetests-default.log",
            "type": "logcat"
          }
        ]
      }
      <<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(912,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(912,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 (4 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

📋 Pre-Flight — Context & Validation

PR #36212 Pre-Flight

Identity

  • PR: dotnet/maui#36212 — [Android] Prevent fragment crashes during Shell and FlyoutPage root replacement
  • URL: #36212
  • Base: main (d48c3ba39b58c724e86aca99c3823458ca1df235 in this checkout)
  • PR head: 601bb5208d49a0a2b4767e73bb9ed6ff5f2ae226
  • Local review commit: 1cfe7e298afcb4c176b090815a5b0bdfd15a3a85 (PR #36212 squashed for review)
  • Platform: Android
  • Gate: INCONCLUSIVE because the tests could not be built/run due to a build or environment error. This is not evidence that the fix fails, and the gate must not be rerun in STEP 5a.

Problem Context

PR #35372 fixed a stale Android ContainerView leak by clearing CurrentView during a live Window.Page replacement. PR #36152 showed that this cleanup exposed a fragment race: Shell/Flyout fragment transactions could execute after their target root had already been detached, causing IllegalArgumentException: No view found for id .... PR #36212 attempts to retain the cleanup while settling or deferring fragment work before releasing the outgoing root.

Direct Diff Inspection

The PR changes 8 files (+1655/-59):

  • NavigationRootManager.cs replaces direct root replacement with serialized, last-request-wins RootRequest processing. Requests complete as Applied, Superseded, Cancelled, or Failed; reentrant requests are queued; busy fragment managers retry through a main-looper Handler with bounded exponential delay; and outgoing roots are quiesced before ContainerView.CurrentView is cleared.
  • NavigationRootManager.ConnectCore publishes the incoming root before committing its content fragment, discards stale constructed/published roots when reentered, protects toolbar state with a version, and preserves the winning root's drawer/coordinator/inset state.
  • NavigationRootManager.DisconnectCore drains only the scoped owning fragment manager, while replacement can also drain a distinct activity fragment manager for compatibility Shell.
  • WindowHandler.Android.cs uses root-prepared and terminal completion callbacks, guards disconnect/reconnect with a lifecycle generation, and avoids attaching a stale root to a destroyed/disconnecting activity.
  • ViewHandler.Android.cs reparents a native toolbar before adding it to the winning app bar.
  • ModalNavigationManager.Android.cs now requires modal root creation to complete synchronously.
  • Device-test infrastructure was extended so deferred/reentrant roots can be attached to the fake activity root.
  • Android device tests cover stale-container cleanup, same-turn Shell/Flyout replacement, replacement from Loaded, ContentPage-to-Shell replacement, fragment-callback reentry, busy-manager deferral/cancellation, toolbar ownership, disconnect reentry, construction-time replacement, and nested Flyout hosting.

The core risk surface is lifecycle ordering across two fragment managers, reentrant completion callbacks, stale native-root publication/disposal, toolbar ownership, and teardown after the Android activity/looper becomes unavailable.

Test Scope for STEP 5a

Do not run a full suite or broad category. Use only the primary targeted Android device test for the candidate's mechanism and directly affected regression tests already added by this PR. Relevant named regressions are:

  • SwappingDetailThenReplacingWindowRootDoesNotCrash
  • NestedFlyoutPageDetailSurvivesRootReplacement
  • ReplacedFlyoutPageRootClearsOldContainerView
  • ReplacingShellRootWhileSwitchingItemsDoesNotCrash
  • ReplacingShellRootFromPageLoadedDoesNotCrash
  • ReplacingFlyoutRootFromDetailLoadedDoesNotCrash
  • ReplacingContentRootWithShellInSameTurnDoesNotCrash
  • ReentrantRootReplacementDoesNotClobberNewRoot
  • RootReplacementDuringFragmentExecutionIsDeferred
  • OutgoingToolbarMappingDuringRootDrainIsIgnored
  • RootReplacementDuringFlyoutConstructionPublishesLatestRoot
  • SupersededRootRequestDoesNotReportApplied
  • NewToolbarElementReusingOutgoingToolbarWinsDuringRootDrain
  • DetachedRootWithActiveFragmentCanBeReplaced
  • DetachedRootWithActiveFragmentCanBeDisconnected
  • BusyRootReplacementCancelsAfterRetryLimit
  • UnavailableActivityPermanentlyStopsDeferredRootSwaps
  • RootReplacementDuringDisconnectAttachesLatestRoot
  • ReentrantRootRequestsYieldBeforeContinuing
  • NestedVirtualDisconnectsPreserveEveryCompletion

Workspace Constraint

The worktree contains extensive pre-existing modifications under .github/ and eng/. They do not overlap the PR's eight files. Candidate work must preserve them exactly, modify only files needed for its alternative, record its patch, and remove only its own candidate changes before returning.


🔬 Code Review — Deep Analysis

Expert PR Evaluation

Verdict

NEEDS_CHANGES with medium confidence. The Android-only request pipeline is thoughtfully designed and its exact-once completion, bounded retry, retry-resource cleanup, and reconnect subscription handling are internally coherent. However, the review found concrete lifecycle-contract gaps that can turn deferred or cancelled work into a modal crash or a silent blank window. The trusted Gate is inconclusive because of an environment/build error, so it neither proves nor disproves the fix.

Independent Assessment

The submitted fix replaces synchronous Android root replacement with a serialized, last-request-wins RootRequest pipeline. It drains outgoing fragment work while target views exist, publishes incoming roots before committing their content fragments, retries when a FragmentManager is already executing, reports terminal outcomes, protects toolbar state with a version, and guards deferred WindowHandler teardown with lifecycle generations.

The overall architecture addresses the fragment transaction race more comprehensively than the smaller STEP 5a alternatives. The request completion paths are exact-once, retry and reentrant-drain loops are bounded, posted retry infrastructure is released safely, and handler event subscriptions remain symmetric across reconnects.

Actionable Findings

  1. Major — ModalNavigationManager.Android.cs:337: NavigationRootManager.Connect() returning false represents deferred, superseded, or cancelled work rather than failure. Throwing from DialogFragment.OnCreateView converts a benign non-synchronous outcome into an application crash.
  2. Major — WindowHandler.Android.cs:45: the window path supplies only rootPrepared, not a terminal completion callback. A cancelled or superseded request can therefore leave the activity without an attached replacement root and without any diagnostic.
  3. Major — NavigationRootManager.cs:636: busy-manager detection depends on an AndroidX exception-message substring. Existing tests override the drain result and do not exercise this real classification boundary, so an AndroidX wording change can bypass deferral and reintroduce the exception.
  4. Moderate — NavigationRootManager.cs:592: using outgoingRootView.Parent is null as a reason not to drain can skip pending transactions for a detached root whose fragment is still active.
  5. Moderate — NavigationRootManager.cs:574: deferred disconnect clears toolbar state without the toolbar-version/reference guard used by connect, allowing newer toolbar mappings to be erased.
  6. Moderate — NavigationRootManager.cs:519: discarding a root after rootPrepared clears and disconnects it but does not remove the root already installed as the activity content view.
  7. Moderate — NavigationRootManager.cs:122: the completion stack couples a non-virtual overload to public virtual Disconnect() ordering and can misassociate completions under subclass reentry.
  8. Moderate — ViewHandler.Android.cs:246: unconditional toolbar reparenting can steal the shared native toolbar from a different still-live app bar.
  9. Moderate — NavigationRootManager.cs:344: _rootSwapsUnavailable is a permanent, silent latch reached from conditions that can be transient, making later root changes silently cancel.

The raw file-and-line findings are persisted in ../inline-findings.json.

Consolidated Reviewer Improvement

Use terminal RootRequestOutcome callbacks as the correctness contract for both Window and modal consumers rather than interpreting the immediate bool as success. Treat Applied as success, Superseded as benign, and make Cancelled/Failed observable without throwing merely because work was deferred. A focused refinement should also preserve newer toolbar mappings during deferred disconnect and remove the detached-root parent short-circuit; broader speculative redesign is not warranted in this pass.

Blast Radius and Evidence

The change affects every Android window-root connect/disconnect and Shell/Flyout/toolbar lifecycle, so confidence is capped below high. Device coverage is extensive but was not runnable in the current environment. The most important uncovered boundary is the real AndroidX busy exception classification; the Gate result remains INCONCLUSIVE, not failed.


🛠️ Try-Fix — Analysis & Comparison

PR #36212 — STEP 5a Try-Fix Aggregate

Candidate 1: Blocked (UNVERIFIED) — attach-gated fragment commit + synchronous quiesce of the outgoing content fragment. Compile-verified (Android build succeeded, 0 errors/0 warnings); targeted Android device tests could NOT be run in this environment (no emulator; same environment class that made the gate INCONCLUSIVE). Not demonstrably superior to the PR on available evidence.

Candidate 2: Blocked (NO IMPLEMENTATION) — a materially distinct FragmentTransaction RunOnCommit handoff was designed, but the mandatory baseline script rejected the pre-existing dirty .github//eng/ worktree and created no modification allow-list. No code or tests could be executed. The bounded two-candidate limit is complete; no further candidates were launched.


Status / Verdict

  • Result: Blocked (UNVERIFIED) — implementation complete and compiling; device tests could not be executed in this environment.
  • Compile evidence: Build succeeded. 0 Warning(s) 0 Error(s) for src/Core/src/Core.csproj -f net10.0-android36.0 with the candidate applied (build.log).
  • Runtime evidence: none. No Android emulator/device session is available in this Linux CI container and the Controls DeviceTests app cannot be deployed/run here (same class of environment failure that made the gate INCONCLUSIVE).
  • Assessment vs. the PR: the candidate is a materially smaller mechanism (+199/-… on one file vs. the PR's +717/-52 across four production files) that plausibly covers the primary crash path, but it does not cover several ordering cases the PR explicitly handles (reentrant fragment-callback replacement, busy-manager retry/cancel, activity-destroyed teardown, toolbar ownership during drain). On evidence available, it is not demonstrably superior to the PR; it is a leaner design point worth considering, unverified.

Baseline Setup (environment deviation, recorded)

pwsh .github/scripts/EstablishBrokenBaseline.ps1 refused to run:

EstablishBrokenBaseline.ps1 failed: Working directory is not clean.

The worktree legitimately contains extensive pre-existing user modifications under .github/ and eng/, which must be preserved, so the script's clean-tree precondition cannot be satisfied and no .github/.baseline-state.json was produced. Baseline was therefore established manually and reversibly, touching only the PR's four production files:

  1. Copied the four PR production files to try-fix-1/backup/.
  2. Rewrote each from git show origin/main:<path> (pre-PR / broken state). PR test files were intentionally left at PR state.
  3. Implemented the candidate on top of that broken baseline.
  4. Restored all four files byte-for-byte from backup/ afterwards (verified clean vs HEAD).

No git checkout/restore/reset/clean/stash was used and no pre-existing .github//eng/ change was touched.

Materially Distinct Approach

Name: attach-gated fragment commit + synchronous quiesce of the outgoing content fragment.

Two mechanisms, both inside NavigationRootManager only:

  1. Quiesce before release (outgoing side). Connect(...) and Disconnect(...) now begin with QuiesceOutgoingContent(), which

    • disposes the not-yet-handed-off pending runnable,
    • commits Remove(_viewFragment) with CommitAllowingStateLoss, and
    • synchronously drains the fragment manager via ExecutePendingTransactions() while the outgoing root is still inside the activity's view hierarchy, wrapped in a TryExecutePendingTransactions helper that swallows the reentrant IllegalStateException and logs.

    After this, no queued transaction referencing Resource.Id.navigationlayout_content of the outgoing root can survive the root swap.

  2. Attach-gated commit (incoming side). SetContentView(view) no longer commits the content fragment eagerly. It commits only when the incoming root is attached to a window:

    • if rootView.IsAttachedToWindow → commit immediately (preserves today's synchronous behaviour for the common first-Connect/modal path);
    • otherwise a self-unregistering RootAttachListener (View.IOnAttachStateChangeListener, stored in the existing _pendingFragment slot) commits on attach, and re-checks ReferenceEquals(_rootView, rootView) both at attach time and inside RunOrWaitForResume so a superseding Connect silently wins.

    Because _pendingFragment is disposed at the top of every Connect/SetContentView, a superseded root's listener is unregistered — "last root wins" falls out of the existing disposable slot rather than from an explicit request state machine.

  3. Compatibility facade (not the mechanism). To keep the PR's device-test call sites compiling, Connect gained Action<AView?>? rootPrepared + a bool return (always true: this design never defers a root request), plus Disconnect(Action<RootRequestOutcome, AView?>?), a nested RootRequestOutcome enum, and the TryExecutePendingTransactionsOverride test hook (which the drain path genuinely honours). WindowHandler.Android.cs, ViewHandler.Android.cs, and ModalNavigationManager.Android.cs were left at their pre-PR state — the candidate needs no changes there.

Prior approach avoided

The PR (#36212) treats the bug as a scheduling problem: it introduces a serialized, last-request-wins RootRequest pipeline with Applied/Superseded/Cancelled/Failed outcomes, queues reentrant requests, retries against a busy fragment manager through a main-looper Handler with bounded exponential backoff, threads terminal completion callbacks into WindowHandler (lifecycle generation + _disconnecting guard), and defers activity content-view attachment until a request wins. PR #35372 (clearing ContainerView.CurrentView on live replacement) is the change that exposed the race, and PR #36152 documented the resulting IllegalArgumentException: No view found for id ....

Mechanism-level difference

The PR's hypothesis is "the root swap must be scheduled so fragment work never straddles a root change". This candidate's hypothesis is "the root swap can stay synchronous if the fragment manager is never left holding work against a container that is about to leave, or against a container that has not yet arrived."

Cause-to-effect chain: the crash requires a fragment transaction to execute while its container id is unreachable from the activity's view tree. There are exactly two ways to reach that state — (a) a transaction queued against the outgoing container executes after the activity content view is replaced, or (b) a transaction committed against the incoming container executes before that root is attached. Mechanism 1 eliminates (a) by forcing the outgoing container's queued work to run before the caller detaches it (the drain happens inside Connect, before Activity.SetContentView(newRoot) is ever called). Mechanism 2 eliminates (b) by making the commit itself conditional on IsAttachedToWindow, so the transaction cannot be scheduled while the id is unreachable. With both edges closed, no request queue, retry timer, or outcome state machine is needed — supersession is handled by disposing the single pending-work slot that already existed in the file.

Targeted Tests

Per the pre-flight the primary targeted mechanism tests are SwappingDetailThenReplacingWindowRootDoesNotCrash, NestedFlyoutPageDetailSurvivesRootReplacement, and ReplacedFlyoutPageRootClearsOldContainerView (Android device tests, Controls.DeviceTests).

Commands attempted and results:

Command Result
pwsh .github/scripts/EstablishBrokenBaseline.ps1 ❌ refused — "Working directory is not clean" (pre-existing .github/+eng/ edits must be preserved). Manual reversible baseline used instead.
.dotnet/dotnet restore src/Essentials/src/Essentials.csproj ✅ exit 0
.dotnet/dotnet restore src/Core/src/Core.csproj ✅ exit 0
.dotnet/dotnet build src/Core/src/Core.csproj -f net10.0-android36.0 --no-restore ✅ Build succeeded, 0 warnings, 0 errors (build.log)
Run-DeviceTests.ps1 -Project Controls.DeviceTests -Platform android -TestFilter "…SwappingDetailThenReplacingWindowRootDoesNotCrash" ⛔ Not run — BLOCKED. No booted emulator/device in this Linux container; device-test deploy+run is the same environment class that made the gate INCONCLUSIVE, and booting an emulator + building the Controls DeviceTests app is outside this candidate's 40-minute budget.

Honest status: UNVERIFIED at runtime. The candidate is compile-verified only. No claim of Pass is made.

Inline Expert Self-Review

Reviewed against .github/agents/maui-expert-reviewer.md — Overarching Principles plus always-active dimensions (Logic & Correctness, Regression Prevention, Complexity Reduction) and the routed Android/platform + handler-lifecycle + threading dimensions.

Findings (severity — dimension — issue):

  1. [major] Logic & Correctness / Regression Prevention — content can be silently dropped if the incoming root never attaches. With attach-gating, a root that is constructed but never added to a window never commits its content fragment. Concrete scenario: a host that calls Connect(...) and then decides not to attach the returned root (e.g. WindowHandler.MapContent on a finishing activity, or a test harness that builds a root for assertions only). Pre-PR code would commit anyway (and crash or no-op); the PR handles this explicitly by cancelling the request and reporting a terminal outcome. Here the request just stalls with no diagnostic. Mitigation would be a "root discarded" log + explicit cancel on Disconnect — Disconnect does dispose the listener, so it leaks nothing, but the silent no-content state is a real behavioural gap.
  2. [major] Threading/Lifecycle — the reentrant drain failure path leaves the original crash window open. TryExecutePendingTransactions catches IllegalStateException ("FragmentManager is already executing transactions") and continues. In that path the outgoing Remove is queued but not executed, so if the caller then swaps the activity content view, the exact No view found for id crash can still occur. The PR covers this case with its busy-manager deferral/retry (RootReplacementDuringFragmentExecutionIsDeferred, BusyRootReplacementCancelsAfterRetryLimit). This is the single biggest coverage gap of the candidate.
  3. [moderate] Regression Prevention — RootViewChanged/toolbar timing moves later. OnWindowContentPlatformViewCreated (and therefore RootViewChanged and the IToolbarElement.Toolbar re-map) now fires after attach rather than after Connect. Consumers that read RootView content synchronously after Connect (visual-diagnostics overlay init, toolbar placement) will observe an empty content container for one attach cycle. No crash expected, but NestedFlyoutPageDetailSurvivesRootReplacement-style assertions could be timing sensitive.
  4. [moderate] Platform/Android — toolbar reparenting is not addressed. The PR's ViewHandler.Android.cs change (nativeToolBar == null guard + RemoveFromParent() before appbarLayout.AddView) is deliberately not part of this candidate. If a replacement root reuses the same native Toolbar instance, AddView can still throw "The specified child already has a parent". That defect is orthogonal to the fragment race and would need to be carried over independently.
  5. [minor] API surface — bool Connect(...) always returns true. The return value exists purely for source compatibility with the PR's tests/ModalNavigationManager call shape; in this design it carries no information. Keeping a non-informative bool on an internal API is mild dead weight.
  6. [minor] Complexity Reduction — positive note. The candidate adds ~130 net lines to one file and introduces one small listener type, versus the PR's ~665-line rewrite of NavigationRootManager plus lifecycle-generation state in WindowHandler. If findings 1–2 can be closed cheaply, the maintenance surface is dramatically smaller.

No [critical] findings. Findings 1 and 2 were left unfixed deliberately: closing #2 requires re-introducing deferral, which would converge on the PR's mechanism and violate the "materially distinct" constraint for this candidate.

Failure / Limitation Analysis

  • Why not Pass: the required proof (targeted Android device test run) is unavailable in this container — no emulator, and the device-test app build/deploy path is the same one that already failed for the gate. Reporting Pass on a clean compile alone would be false.
  • Why the candidate is probably not a drop-in replacement for the PR: the PR's own test list encodes behaviours this design does not implement — RootReplacementDuringFragmentExecutionIsDeferred, BusyRootReplacementCancelsAfterRetryLimit, UnavailableActivityPermanentlyStopsDeferredRootSwaps, SupersededRootRequestDoesNotReportApplied, ReentrantRootRequestsYieldBeforeContinuing, and the two toolbar-during-drain tests. Those are white-box tests of the PR's request pipeline; against this candidate they would fail (or assert on semantics the candidate does not model), even though the black-box crash regressions (SwappingDetailThenReplacingWindowRootDoesNotCrash, ReplacedFlyoutPageRootClearsOldContainerView, NestedFlyoutPageDetailSurvivesRootReplacement) are the ones the candidate targets.
  • Transferable insight for the PR review: the two edges identified above (drain-before-detach, commit-only-after-attach) are the minimal invariants for this crash. The PR satisfies both, but pays for them with a full request state machine. A reviewer could reasonably ask whether the retry/backoff Handler path is load-bearing beyond the reentrant-drain case (finding 2) — i.e. whether the PR's complexity could be reduced to "quiesce + attach-gate + defer only when the drain is refused". That is a concrete, evidence-backed review question this candidate produces.
  • Environment insight: EstablishBrokenBaseline.ps1 is unusable whenever the reviewer's worktree carries unrelated modifications; a -AllowDirtyPaths/scoped-clean option would let try-fix run normally in this configuration.

Candidate Diff (vs pre-PR baseline origin/main)

diff --git a/src/Core/src/Platform/Android/Navigation/NavigationRootManager.cs b/src/Core/src/Platform/Android/Navigation/NavigationRootManager.cs
index 712d24da52..fd05b1d0cc 100644
--- a/src/Core/src/Platform/Android/Navigation/NavigationRootManager.cs
+++ b/src/Core/src/Platform/Android/Navigation/NavigationRootManager.cs
@@ -48,8 +48,15 @@ namespace Microsoft.Maui.Platform
 			_toolbarElement = toolbarElement;
 		}
 
-		internal void Connect(IView? view, IMauiContext? mauiContext = null)
+		internal bool Connect(IView? view, IMauiContext? mauiContext = null, Action<AView?>? rootPrepared = null)
 		{
+			// Settle every fragment operation that targets the OUTGOING root while that root is
+			// still inside the activity's view hierarchy. Once the caller swaps the activity
+			// content view, a transaction that was merely queued can no longer resolve
+			// Resource.Id.navigationlayout_content and Android throws
+			// "IllegalArgumentException: No view found for id ...".
+			QuiesceOutgoingContent();
+
 			ClearPlatformParts();
 
 			mauiContext = mauiContext ?? _mauiContext;
@@ -111,6 +118,10 @@ namespace Microsoft.Maui.Platform
 			//
 			// if it's not a drawer layout then we just use our default CoordinatorLayout inside navigationlayout
 			// and place the content there
+			// Publish the new root before any content fragment is committed so the caller can
+			// attach it to the activity/dialog first.
+			rootPrepared?.Invoke(_rootView);
+
 			if (DrawerLayout == null)
 			{
 				SetContentView(view);
@@ -119,6 +130,66 @@ namespace Microsoft.Maui.Platform
 			{
 				SetContentView(null);
 			}
+
+			return true;
+		}
+
+		// Drains the fragment manager while the outgoing root is still attached, so no queued
+		// transaction can execute against a container that has already left the hierarchy.
+		void QuiesceOutgoingContent()
+		{
+			// Cancel anything that has not been handed to the fragment manager yet.
+			_pendingFragment?.Dispose();
+			_pendingFragment = null;
+
+			var context = _mauiContext?.Context;
+			var fragmentManager = _mauiContext?.GetFragmentManager();
+
+			if (context is null || fragmentManager.IsDestroyed(context))
+			{
+				_viewFragment = null;
+				return;
+			}
+
+			if (_viewFragment is not null)
+			{
+				fragmentManager!
+					.BeginTransactionEx()
+					.RemoveEx(_viewFragment)
+					.SetReorderingAllowedEx(true)
+					.CommitAllowingStateLossEx();
+			}
+
+			// Execute the removal (and anything queued before it) right now, while the outgoing
+			// container view is still resolvable.
+			var drained = TryExecutePendingTransactions(fragmentManager!, context);
+
+			if (drained || _viewFragment?.IsAdded != true)
+				_viewFragment = null;
+		}
+
+		internal Func<FragmentManager, Context, bool>? TryExecutePendingTransactionsOverride { get; set; }
+
+		bool TryExecutePendingTransactions(FragmentManager fragmentManager, Context context)
+		{
+			if (TryExecutePendingTransactionsOverride is { } custom)
+				return custom(fragmentManager, context);
+
+			try
+			{
+				fragmentManager.ExecutePendingTransactionsEx();
+				return true;
+			}
+			catch (Java.Lang.IllegalStateException e)
+			{
+				// The fragment manager is already executing transactions (reentrant call). The
+				// queued removal will run as part of the pass that is currently in flight.
+				_mauiContext?.CreateLogger<NavigationRootManager>()?.LogWarning(
+					e,
+					"NavigationRootManager: unable to drain pending fragment transactions for the outgoing root.");
+
+				return false;
+			}
 		}
 
 		// this is called after the Window.Content is created by
@@ -138,6 +209,24 @@ namespace Microsoft.Maui.Platform
 
 		public virtual void Disconnect()
 		{
+			Disconnect(null);
+		}
+
+		internal enum RootRequestOutcome
+		{
+			Applied,
+			Superseded,
+			Cancelled,
+			Failed
+		}
+
+		internal void Disconnect(Action<RootRequestOutcome, AView?>? completion)
+		{
+			var outgoingRoot = _rootView;
+
+			// Remove the content fragment while the outgoing root is still attached.
+			QuiesceOutgoingContent();
+
 			// Clean up the coordinator layout and local listener first
 			if (_managedCoordinatorLayout is not null)
 			{
@@ -146,6 +235,8 @@ namespace Microsoft.Maui.Platform
 
 			ClearPlatformParts();
 			SetContentView(null);
+
+			completion?.Invoke(RootRequestOutcome.Applied, outgoingRoot);
 		}
 
 		void ClearPlatformParts()
@@ -196,23 +287,97 @@ namespace Microsoft.Maui.Platform
 			}
 			else
 			{
+				var rootView = _rootView;
+				if (rootView is null)
+					return;
+
+				// Only commit the content fragment once the incoming root is actually attached to
+				// a window. Until then Resource.Id.navigationlayout_content is not reachable from
+				// the activity, which is exactly the state that produces
+				// "No view found for id ..." when a root is replaced mid-flight.
+				if (rootView.IsAttachedToWindow)
+				{
+					CommitContentFragment(view, rootView, context);
+				}
+				else
+				{
+					_pendingFragment = new RootAttachListener(
+						rootView,
+						() => CommitContentFragment(view, rootView, context));
+				}
+			}
+		}
+
+		void CommitContentFragment(IView view, AView rootView, Context context)
+		{
+			// The attach listener (if any) has already unregistered itself at this point.
+			_pendingFragment = null;
+
+			// A newer Connect may have superseded this root while it was waiting to attach.
+			if (!ReferenceEquals(_rootView, rootView))
+				return;
+
+			_pendingFragment =
+				FragmentManager
+					.RunOrWaitForResume(context, fm =>
+					{
+						if (!ReferenceEquals(_rootView, rootView))
+							return;
+
+						_viewFragment =
+							new ElementBasedFragment(
+								view,
+								_mauiContext,
+								OnWindowContentPlatformViewCreated);
+
+						fm
+							.BeginTransactionEx()
+							.ReplaceEx(Resource.Id.navigationlayout_content, _viewFragment)
+							.SetReorderingAllowedEx(true)
+							.Commit();
+					});
+		}
+
+		sealed class RootAttachListener : Java.Lang.Object, AView.IOnAttachStateChangeListener
+		{
+			AView? _view;
+			Action? _onAttached;
+
+			public RootAttachListener(AView view, Action onAttached)
+			{
+				_view = view;
+				_onAttached = onAttached;
+				view.AddOnAttachStateChangeListener(this);
+			}
+
+			public void OnViewAttachedToWindow(AView attachedView)
+			{
+				var onAttached = _onAttached;
+				Detach();
+				onAttached?.Invoke();
+			}
+
+			public void OnViewDetachedFromWindow(AView detachedView)
+			{
+			}
+
+			protected override void Dispose(bool disposing)
+			{
+				if (disposing)
+					Detach();
+
+				base.Dispose(disposing);
+			}
+
+			void Detach()
+			{
+				if (_view is not null)
+				{
+					_view.RemoveOnAttachStateChangeListener(this);
+					_view = null;
+				}
 
-				_pendingFragment =
-					FragmentManager
-						.RunOrWaitForResume(context, fm =>
-						{
-							_viewFragment =
-								new ElementBasedFragment(
-									view,
-									_mauiContext,
-									OnWindowContentPlatformViewCreated);
-
-							fm
-								.BeginTransactionEx()
-								.ReplaceEx(Resource.Id.navigationlayout_content, _viewFragment)
-								.SetReorderingAllowed(true)
-								.Commit();
-						});
+				_onAttached = null;
 			}
 		}
 

PR #36212 — STEP 5a Candidate 2

Status / Verdict

  • Result: Blocked (NO IMPLEMENTATION).
  • Verdict: The candidate was concretely designed but could not legally be applied. The mandatory try-fix baseline script rejected the explicitly pre-existing tracked .github/ and eng/ changes, produced no .github/.baseline-state.json, and therefore produced no RevertedFiles modification allow-list. The skill requires stopping before tracked edits in this state.
  • Evidence quality: No compile or runtime evidence. This candidate is inferior to the PR and candidate 1 on available evidence because it remained unimplemented.

Materially Distinct Approach

Name: Fragment-transaction completion handoff.

The intended implementation replaces eager Android root replacement with a two-phase handoff driven by FragmentTransaction.RunOnCommit:

  1. Enqueue removal of the outgoing root fragment while its navigationlayout_content container is still attached.
  2. Register the handoff with RunOnCommit, so all earlier queued fragment work and the removal complete before the activity root can change.
  3. In the callback, discard the constructed root if a monotonic generation is stale; otherwise attach the winning Shell/FlyoutPage root to the activity.
  4. Only after attachment, enqueue the incoming content fragment against the now-reachable container.

This uses no request queue, retry timer, terminal outcome state machine, attach-state listener, or synchronous ExecutePendingTransactions drain.

Prior approaches avoided

PR #36212 serializes last-request-wins requests, reports terminal outcomes, and retries a busy FragmentManager. Candidate 1 attach-gates incoming commits and synchronously drains outgoing work; its key unresolved flaw is that it continues when ExecutePendingTransactions is refused because the FragmentManager is already executing, preserving the original crash window.

Mechanism-level difference and rationale

RunOnCommit uses the FragmentManager's own ordered transaction completion as the handoff barrier. If the manager is already executing, the removal waits in its normal queue; the old activity root remains attached until that removal's completion callback, so queued work retains a resolvable container. The callback then attaches only the latest-generation root before its incoming fragment is committed. The mechanism therefore addresses the exact candidate-1 failure path without synchronous draining and addresses rapid replacement/reentrancy with a generation token rather than the PR's request queue. The same activity-root ordering is intended to cover Shell, FlyoutPage, and nested FlyoutPage roots.

Baseline Attempt / Environment Blocker

Exact command run:

pwsh .github/scripts/EstablishBrokenBaseline.ps1

Result:

ERROR: DIRTY WORKING DIRECTORY - Cannot establish baseline
EstablishBrokenBaseline.ps1 failed: Working directory is not clean.

The listed changes were the pre-existing user-owned .github/ and eng/ modifications identified in pre-flight. They cannot be discarded or committed. No baseline state was created. In accordance with the try-fix skill, no manual backup/baseline workaround was used and no tracked candidate file was edited.

The mandatory restore command was run after artifact capture:

pwsh .github/scripts/EstablishBrokenBaseline.ps1 -Restore
Restored: False
Message: No baseline state found

This is the accepted no-state restoration path because baseline establishment failed before any candidate edit.

Exact Candidate Diff

The actual candidate diff is empty because the mandatory baseline boundary blocked all tracked edits:

No PR or production file was modified.

Targeted Test Commands / Results

Command Result
pwsh .github/scripts/EstablishBrokenBaseline.ps1 BLOCKED — clean-worktree guard rejected pre-existing tracked .github//eng/ changes; no baseline state/allow-list.
pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls.DeviceTests -Platform android -TestFilter "SwappingDetailThenReplacingWindowRootDoesNotCrash" Not run — no candidate was applied; additionally, the invoker recorded no available Android device/emulator and prohibited retry/setup.
Same script for NestedFlyoutPageDetailSurvivesRootReplacement Not run — same blockers.
Same script for ReplacedFlyoutPageRootClearsOldContainerView Not run — same blockers.

No gate command was rerun and gate/content.md was not created or changed.

Inline Expert Self-Review

Reviewed the actual empty diff against .github/agents/maui-expert-reviewer.md: Overarching Principles; always-active Logic & Correctness, Regression Prevention, and Complexity Reduction; and the Android/platform/threading routing that the intended production location would activate.

  • Recorded findings: 0 (reviewer-findings.json is []) because there is no applied diff to annotate.
  • Design risks requiring validation if implemented: reentrant RunOnCommit ordering, stale-generation native-root disposal, destroyed/finishing activity teardown, toolbar ownership during handoff, and whether nested FlyoutPage uses a distinct fragment-manager scope. These are not findings against the empty diff and were not falsely marked resolved.

Failure / Limitation Analysis

  • This is a worktree-policy/environment blocker, not evidence that the mechanism succeeds or fails.
  • The try-fix skill allows edits only after its script creates .github/.baseline-state.json; the unrelated dirty tree prevented that and preservation requirements prevented cleaning it.
  • No compile result can be claimed, and device runtime was independently unavailable.
  • Compared with candidate 1, the design directly avoids the known already-executing FragmentManager hole by waiting for normal transaction completion rather than continuing after a failed synchronous drain. Compared with the PR, it avoids request queuing/retry/outcome machinery. But because it could not be implemented, it is inferior/unverified and should not replace the PR based on this attempt.

Bounded Search Completion

Candidate 2 is final. The bounded two-candidate limit is complete; no further candidates, skills, agents, reviewers, or audits were launched.


🏁 Report — Final Recommendation

⚠️ Final Recommendation: REQUEST CHANGES

Winner: pr-plus-reviewer

pr-plus-reviewer is the strongest candidate because it retains the submitted PR's comprehensive serialized root-swap mechanism, applies a bounded reviewer improvement for concrete published-root and modal lifecycle defects, and passes the single scoped Android validation run: 8 passed, 0 failed. Because the winning changes are not in the submitted PR and several expert findings remain unresolved, the submitted PR should not be approved as-is.

Comparative Ranking

Rank Candidate Evidence Assessment
1 pr-plus-reviewer Android targeted validation: 8/8 passed Best overall. Preserves the PR's busy-manager retry, exact-once outcomes, reentrancy, teardown, and toolbar machinery; additionally detaches a published root before discard, avoids treating a non-applied modal request as immediate failure when a winning root was published, logs permanently cancelled requests, and adds a focused regression.
2 pr Trusted Gate inconclusive; no current-run pass/fail evidence Architecturally much more complete than either try-fix candidate, with strong in-diff device coverage, but expert review found three major and six moderate concerns. In particular, raw code can discard an activity-published root without detaching it, treats modal Connect() == false as failure, and leaves important lifecycle outcomes or classification boundaries insufficiently observable/tested.
3 try-fix-1 Android Core compile passed; device regressions blocked Smaller attach-gated/quiesce design, but its own review identifies major gaps: when FragmentManager is already executing, its swallowed drain failure leaves the original crash window open; unattached roots can silently drop content; and PR-covered retry, teardown, toolbar, and reentrancy semantics are absent. It has no runtime proof.
4 try-fix-2 No implementation; no compile/runtime evidence RunOnCommit handoff is an interesting design, but the baseline guard blocked all edits. Its candidate diff is empty and its lifecycle, stale-generation, toolbar, and nested-manager behavior remain hypothetical.

No candidate has a recorded regression-test failure. The ordering therefore follows applicable passing evidence first, then implementation completeness and code-merit risk. pr-plus-reviewer is the only candidate with a focused runtime pass; try-fix-1 is compile-only and try-fix-2 is unimplemented.

Expert Review Reconciliation

The raw PR's request state machine has real strengths: exact-once completion, bounded busy retries, bounded reentrant draining, safe retry-runnable disposal, and reconnect-aware event subscription cleanup. The initial expert evaluation nevertheless recorded nine actionable findings in inline-findings.json. The one permitted consolidated patch addresses the modal boolean misuse, the attached discarded-root defect, and silent later cancellations; validation covered the new discard regression plus seven directly related Window/Flyout/Modal scenarios.

Residual concerns were deliberately recorded rather than iteratively repaired: the AndroidX busy detection still depends on exception text without a direct classifier test; detached roots can bypass quiescing; deferred disconnect can clear newer toolbar state; virtual Disconnect() completion association is fragile; toolbar reparenting can steal from a live foreign app bar; and the production Window path still does not consume terminal outcomes comprehensively.

Required Follow-up

Carry the pr-plus-reviewer patch into the submitted branch, then resolve or explicitly disposition the remaining expert findings before approval. The trusted Gate remains INCONCLUSIVE because of its earlier build/environment error; this report does not treat that result as a regression failure.


📱 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: pr-plus-reviewer retains the PR's comprehensive root-request design, fixes concrete modal and published-root lifecycle defects, and passed all 8 focused Android tests. It wins over the raw PR and both less-complete try-fix candidates, although remaining expert findings still require resolution.

Address the actionable findings in this review before merging.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 2b21c423-232d-4a81-b9e3-3d7d74dbc707

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

@PureWeen — adversarial re-review of 77ea710b completed with Claude Opus 5, GPT-5.6 Sol, Gemini 3.1 Pro, the MAUI expert reviewer, and final GPT-5.6 Terra arbitration. Each reviewer received the other models' complete concerns before final arbitration.

Verdict: NEEDS_CHANGES. One new high-confidence correctness defect survived. It is the missing identity case complementary to the earlier fixed thread: that thread covered a different toolbar element reusing the same toolbar; this one covers the same stable Window element receiving a different NavigationPageToolbar.

The latest required maui-pr build (1562634) is green and contains this head, but there is no maui-pr-devicetests or UI run for the exact head. The Android device tests also substitute WindowHandlerStub for the production WindowHandler.MapContent/disconnect path, so the relevant runtime coverage remains absent.

Prior findings were reconciled: the discarded-root callback and stronger fragment-container assertion at this head are sound. The detached-root/Shell and executing-disconnect theories were excluded as duplicate, not framework-reachable, or absorbed by the inline toolbar defect.

The title remains accurate. The body should be corrected before merge: its exact-head Mono/CoreCLR device-CI claim refers to older evidence, “no unresolved correctness findings” is no longer true, and the compatibility note should disclose that public Disconnect() can now return while RootView remains non-null.

// being torn down. Ignore only that stale element; a newer element that happens to
// reuse the same toolbar instance must remain protected by the version check.
var toolbar = toolbarElement.Toolbar;
if (_quiescingFragmentManagers && ReferenceEquals(toolbarElement, _toolbarElementBeingQuiesced))

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.

❌ Major — same element/new toolbar is dropped during a retry drain. Window is the stable IToolbarElement, but each NavigationPage.OnWindowChanged installs a new NavigationPageToolbar. During a reentrant Window.Page assignment while fragment transactions are being drained, OnPropertyChanged(Content) queues the winning root before OnPageChanged maps that new toolbar. This guard then rejects the valid mapping solely because the element is still the same Window; the queued request retains the prior toolbar/version, cleanup clears the manager state, and the winning navigation root can render without its app bar, title, back button, or toolbar items.

Suppress only the exact outgoing element + toolbar pair captured when quiescence begins, rather than every mapping from that element. Please add the missing regression cell: same toolbar element, different toolbar instance, mapped reentrantly during the drain (ideally through real Window/NavigationPage callbacks).

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

area-controls-flyoutpage FlyoutPage 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.

5 participants