Skip to content

Fix and Re-enable "Window Does Not Leak" and "Does Not Leak" Memory Leak Device Test - #37310

Merged
kubaflo merged 2 commits into
dotnet:inflight/currentfrom
BagavathiPerumal:fix-36613
Aug 18, 2026
Merged

kubaflo merged 2 commits into
dotnet:inflight/currentfrom
BagavathiPerumal:fix-36613

Conversation

@BagavathiPerumal

@BagavathiPerumal BagavathiPerumal commented Aug 11, 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!

Issue Details

Device memory leak tests started failing in the Candidate branch after PR #35487, indicating regressions in memory leak validation across Windows, iOS, macOS, and Android. The affected Does Not Leak and Window Does Not Leak tests were failing on these platforms.

Issue1: Window Does Not Leak

Root cause

The WindowDoesNotLeak test failed intermittently because window and page were declared as locals inside an async Task method ( WindowDoesNotLeak ) and were referenced across await boundaries (both directly and inside the lambda passed to CreateHandlerAndAddToWindow ). The C# compiler hoists such locals into fields of the generated async state machine, and those fields are not guaranteed to be cleared once the locals are no longer needed. As a result, window and page remained artificially rooted by the state machine instance for the entire duration of the subsequent WaitForGC call, producing a false-positive "still alive" leak report rather than reflecting an actual product defect.

Solution description

The fix extracts the window/page creation and handler invocation logic out of WindowDoesNotLeak into a new, non-inlineable helper method, CreateWindowLeakReferencesAsync , marked with [MethodImpl(MethodImplOptions.NoInlining)] . This helper creates window and page , drives the handler lifecycle, and returns only the collected WeakReference list. Since window and page now live in the helper's own async state machine — which is discarded once the helper returns — they are no longer reachable from WindowDoesNotLeak 's state machine during the subsequent WaitForGC call, eliminating the artificial rooting. The dead conditional compilation guard ( #if TEST_FAILS_ON_ANDROID && TESTS_FAILS_ON_WINDOWS && TESTS_FAILS_ON_IOS && TESTS_FAILS_ON_MACCATALYST ) that had disabled the test was also removed to re-enable it.

Issue2: TabbedPageTests.DoesNotLeak

Root cause

The issue occurs because of two compounding factors. At the test level, the navPage local was captured by an async lambda and accessed again after an await , causing it to be hoisted into the compiler-generated closure and transitively keep the popped TabbedPage alive through its navigation stack. At the platform level on Android, MultiPageFragmentStateAdapter was constructed using the host Activity's long-lived Lifecycle , causing AndroidX to permanently register a lifecycle observer that was never released because the Activity's lifecycle never reached the destroyed state. This kept the adapter, and the TabbedPage it referenced, permanently rooted in memory, while AndroidX also failed to reclaim the associated child fragments.

Solution description

The fix involves nulling the navPage local before the WaitForGC call at the test level, combined with a production-level Android fix in MultiPageFragmentStateAdapter.cs that introduces a teardown routine to make AndroidX reclaim its fragments correctly and explicitly clears the adapter's page reference on disposal. Supporting changes in TabbedPageManager.cs and TabbedPage.Android.cs ensure the teardown routine executes before the adapter is detached and that manager references are cleared on disconnect. The resolution was verified through repeated on-device Android test runs, all passing successfully.

Issue3: NavigationPageTests.DoesNotLeak

Root Cause

The issue occurs because of the navPage and window locals in NavigationPageTests.DoesNotLeak being referenced across an await boundary — both directly and inside the lambda passed to CreateHandlerAndAddToWindow. The C# compiler hoists such locals into fields of the generated async state machine for the test method, and those fields are not guaranteed to be cleared once the locals are no longer needed. As a result, navPage and window remained artificially rooted by the state machine instance for the duration of the subsequent WaitForGC call, producing a false-positive "still alive" leak report rather than reflecting an actual product defect.

This issue was only replicated in Release mode, since Release-mode JIT/compiler optimizations affect how and when the hoisted state-machine fields are cleared, whereas Debug builds happened to clear or avoid rooting them, masking the problem locally.

Solution Description

The fix involves extracting the navPage/window creation and handler invocation logic out of DoesNotLeak into a new, non-inlineable helper method, CreateNavigationPageLeakReferencesAsync, marked with [MethodImpl(MethodImplOptions.NoInlining)]. This helper creates navPage and window, drives the handler lifecycle, and returns only the collected WeakReference list.

Since navPage and window now live in the helper's own async state machine — which is discarded once the helper returns — they are no longer reachable from DoesNotLeak's state machine during the subsequent WaitForGC call, eliminating the artificial rooting.

Validated the behavior in the following platforms

  • iOS
  • Mac
  • Android
  • Windows

Regression PR

PR #35487

Issues Fixed

Fixes #36613

Output Screenshot

Issue1: Window Does Not Leak

Platform Before After
Android
WindowDoesNotLeak.Android.-BeforeFix.mov
WindowDoesNotLeak.Android.-AfterFix.mov
Mac
WindowDoesNotLeak.Mac.-BeforeFix.mov
WindowDoesNotLeak.Mac.-AfterFix.mov
iOS
WindowDoesNotLeak.iOS.-BeforeFix.mov
WindowDoesNotLeak.iOS.-AfterFix.mov
Windows
WindowDoesNotLeak-BeforeFix.mp4
WindowDoesNotLeak-AfterFix.mp4

Issue2: TabbedPageTests.DoesNotLeak

Platform Before After
Android
DoesNotLeak.Android.-BeforeFix.mov
DoesNotLeak.Android.-AfterFix.mov

Issue3: NavigationPageTests.DoesNotLeak

Platform Before After
Mac
BeforeFix-Mac.NavigationPage-DoesNotleak.mov
AfterFix-Mac.NavigationPage-DoesNotleak.mov
iOS
BeforeFix-iOS.NavigationPage-DoesNotleak.mov
AfterFix-iOS.NavigationPage-DoesNotleak.mov

… in Window, NavigationPage, and TabbedPage device tests, and fixed an actual Android TabbedPage memory leak by releasing the FragmentStateAdapter lifecycle observer and page reference.
@github-actions

Copy link
Copy Markdown
Contributor

🚀 Dogfood this PR with:

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

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

Or

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

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

@BagavathiPerumal BagavathiPerumal added the community ✨ Community Contribution label Aug 11, 2026
@dotnet-policy-service dotnet-policy-service Bot added the partner/syncfusion Issues / PR's with Syncfusion collaboration label Aug 11, 2026
@vishnumenon2684

Copy link
Copy Markdown
Contributor

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

@azure-pipelines

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

…lse-Positive leak by extracting navPage/window creation into a NoInlining helper method.
@vishnumenon2684

Copy link
Copy Markdown
Contributor

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

@azure-pipelines

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

@azure-pipelines

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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR re-enables previously disabled memory leak device tests and adjusts both tests and Android TabbedPage infrastructure to avoid false-positive rooting and to ensure AndroidX fragments/adapters are properly torn down so leak validation is reliable across platforms.

Changes:

  • Refactors leak tests to avoid async-state-machine rooting by moving object creation/handler lifecycle into non-inlineable helper methods and/or clearing captured locals before WaitForGC.
  • Re-enables the “Window Does Not Leak” and “Does Not Leak” device tests by removing compile guards, while keeping existing platform-specific skips where applicable.
  • Adds explicit Android teardown/disposal behavior for TabbedPage’s ViewPager2 adapter/manager to help AndroidX reclaim fragments and release references.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
src/Controls/tests/DeviceTests/Memory/MemoryTests.cs Re-enables and refactors WindowDoesNotLeak to avoid false positives from hoisted locals.
src/Controls/tests/DeviceTests/Elements/TabbedPage/TabbedPageTests.cs Re-enables the leak test and clears captured locals before WaitForGC.
src/Controls/tests/DeviceTests/Elements/NavigationPage/NavigationPageTests.cs Re-enables and refactors DoesNotLeak to avoid state-machine-rooted locals.
src/Controls/src/Core/TabbedPage/TabbedPage.Android.cs Ensures TabbedPage manager is nulled out on handler disconnect.
src/Controls/src/Core/Platform/Android/TabbedPageManager.cs Adds defensive event unsubscription and explicit adapter teardown/disposal ordering.
src/Controls/src/Core/Platform/Android/MultiPageFragmentStateAdapter.cs Introduces teardown/dispose guarding to reduce risk of fragment creation/access after adapter teardown.

Comment on lines 68 to 76
public override bool ContainsItem(long itemId)
{
if (_tearingDown)
{
return false;
}

return GetItemByItemId(itemId) != null;
}
@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 Aug 18, 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.

AI Review Summary

@BagavathiPerumal — new AI review results are available based on commit c1e7601.

Gate Inconclusive Confidence Medium Platform iOS


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

Gate Result: ⚠️ INCONCLUSIVE

Platform: IOS · Base: main · Merge base: 5d354a6a

🌐 Fix not relevant to the IOS gate — every changed code file is platform-specific for a different platform (an iOS/MacCatalyst/Android/Windows-only change). On IOS the change is a no-op, so the repro test behaves identically with and without the fix and the gate cannot verify it here. This is inconclusive, not a fix failure — verify this PR on its own platform.

⏭️ Gate skipped up front — because the fix cannot affect this platform's binary, the gate skipped the build + device-test cycle instead of running it to a guaranteed INCONCLUSIVE result, saving the full test-time budget.

Test Status
CarouselView2 (DeviceTest) ⏭️ SKIPPED (not run on this platform)
NavigationPageTests (DeviceTest) ⏭️ SKIPPED (not run on this platform)

Changed fix file(s) — all platform-specific for another platform:

  • src/Controls/src/Core/Platform/Android/MultiPageFragmentStateAdapter.cs
  • src/Controls/src/Core/Platform/Android/TabbedPageManager.cs
  • src/Controls/src/Core/TabbedPage/TabbedPage.Android.cs

📋 Pre-Flight — Context & Validation

PR #37310 Pre-Flight

Context

  • Title: Fix and Re-enable "Window Does Not Leak" and "Does Not Leak" Memory Leak Device Test
  • Base / materialized head: origin/main (5d354a6a) / local squashed review commit 4f5aa7a2
  • Related issue: #36613 reports Window Does Not Leak and Does Not Leak failures on iOS, Mac Catalyst, Android, and Windows after #35487.
  • Requested test platform: ios
  • Gate: INCONCLUSIVE. It intentionally skipped execution because all changed product files are Android-only and therefore cannot affect an iOS binary. This is not evidence that the PR fix fails.

Existing PR Approach

The PR combines test-lifetime corrections with an Android product-lifetime fix:

  1. MemoryTests.WindowDoesNotLeak and NavigationPageTests.DoesNotLeak move strong locals into non-inlineable async helpers so the caller's state machine retains only weak references during WaitForGC.
  2. TabbedPageTests.DoesNotLeak clears the captured NavigationPage local before waiting for collection.
  3. MultiPageFragmentStateAdapter adds teardown/disposal state, reports zero items during teardown, clears item keys, guards fragment/id callbacks, and releases its TabbedPage reference.
  4. TabbedPageManager begins adapter teardown before detaching and disposing it, unsubscribes RootViewChanged, disposes pending fragment work, and clears previousPage.
  5. TabbedPage.Android drops the manager reference when the handler disconnects.

The alternative candidates must not merely reproduce the PR's explicit adapter teardown plus callback guards. A useful candidate needs a different root-cause mechanism, such as eliminating the long-lived owner/reference at construction or changing lifecycle ownership so AndroidX unregisters naturally.

Changed Product Files (Try-Fix Modification Boundary)

  • src/Controls/src/Core/Platform/Android/MultiPageFragmentStateAdapter.cs
  • src/Controls/src/Core/Platform/Android/TabbedPageManager.cs
  • src/Controls/src/Core/TabbedPage/TabbedPage.Android.cs

The changed device-test files are evidence and must remain read-only during try-fix attempts:

  • src/Controls/tests/DeviceTests/Elements/NavigationPage/NavigationPageTests.cs
  • src/Controls/tests/DeviceTests/Elements/TabbedPage/TabbedPageTests.cs
  • src/Controls/tests/DeviceTests/Memory/MemoryTests.cs

After EstablishBrokenBaseline.ps1, .github/.baseline-state.json is authoritative: edit only paths in RevertedFiles; if it is missing or NewFiles is non-empty, record Blocked.

Targeted Test Matrix

No gate rerun and no full suite are allowed. One implementation/test pass consists only of these targeted Controls device-test commands, in order:

  1. Primary: pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform ios -TestFilter "Category=TabbedPage"
  2. Regression: pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform ios -TestFilter "Category=Memory"
  3. Regression: pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform ios -TestFilter "Category=NavigationPage"

At most one focused correction/retest is allowed, and it may rerun only the command that exposed the candidate defect. Because the product files compile only for Android, an iOS pass cannot validate the Android mechanism; report that limitation explicitly rather than treating it as Android proof.

Worktree Safety

The worktree contains extensive pre-existing changes under .github/ and eng/ from the review harness. Do not modify, restore, delete, or include them in a candidate diff. The only permitted cleanup is:

pwsh .github/scripts/EstablishBrokenBaseline.ps1 -Restore

Each attempt must complete the try-fix skill's inline expert self-review, persist all attempt artifacts, and confirm restoration before returning.


🔬 Code Review — Deep Analysis

Expert Evaluation — PR #37310

Verdict: NEEDS_CHANGES
Confidence: Medium-high

The submitted fix has sound test-lifetime changes, but its Android adapter teardown is not safe as written:

  1. TabbedPageManager disposes the managed peer of a Java FragmentStateAdapter that can still receive delayed AndroidX callbacks. Those callbacks can occur after detachment and can no longer reach the new teardown guards once the peer is disposed.
  2. BeginTeardown() clears AdapterItemKey instances without calling Disconnect(). Their Page.HandlerChanging and Page.HandlerChanged subscriptions can therefore retain the keys and adapter, preserving the leak path the change is intended to break.
  3. Returning a view-less Fragment from CreateFragment during teardown can leave AndroidX FragmentLifecycleCallbacks registered because onFragmentViewCreated never occurs.
  4. Removing the ineffective compile guards enables the memory and navigation leak tests on platforms not covered by the Android production fix. The fixed Gate is inconclusive, so those newly enabled paths remain unverified rather than failed.

The non-inlineable helper extractions, clearing the captured navPage, defensive RootViewChanged unsubscription, clearing previousPage, and releasing the handler's manager reference are directionally correct. A consolidated refinement should preserve those changes while disconnecting adapter keys and avoiding unsafe Java-peer disposal/placeholder-fragment behavior.


🛠️ Try-Fix — Analysis & Comparison

PR #37310 — Try-Fix Candidates (Aggregate)

Bounded candidate-generation phase. Candidates 1 and 2 below; both are complete.


Candidate 1 — Self-Scoped Adapter Lifecycle (Blocked)

Result: Blocked (baseline could not be established; no tracked code was edited, no test command was run)

Approach

Self-scoped adapter lifecycle — designed, not applied.

Intended change, one file only: src/Controls/src/Core/Platform/Android/MultiPageFragmentStateAdapter.cs.
Replace the Activity-scoped lifecycle handed to the AndroidX FragmentStateAdapter base constructor:

: base(fragmentManager, context.GetActivity().Lifecycle)

with a LifecycleRegistry owned by the adapter itself (a small nested Java.Lang.Object
implementing AndroidX.Lifecycle.ILifecycleOwner, driven to Resumed at construction so
FragmentMaxLifecycleEnforcer still promotes the current page's fragment). Nothing else:
no teardown flags, no callback guards, no Dispose override, no edits to
TabbedPageManager.cs or TabbedPage.Android.cs.

Prior Approach Avoided

The existing PR fixes the Android side with defensive teardown state:
_tearingDown/_disposed fields and BeginTeardown() on MultiPageFragmentStateAdapter
(zero CountOverride, keys.Clear(), NotifyDataSetChanged()); CreateFragment,
GetItemId and ContainsItem guards returning an empty Fragment, NO_ID (-1) and
false; _page = null! in Dispose(bool); ordered teardown in TabbedPageManager.SetElement
(BeginTeardown() → Adapter = null → Dispose()) plus defensive RootViewChanged
unsubscription and previousPage = null; and _tabbedPageManager = null on handler
disconnect in TabbedPage.Android.cs. On the test side it moves strong window/page/
navPage locals into non-inlineable async helpers or nulls them before WaitForGC.

Their shared failure mechanism assumption is: an explicit teardown path will always be
reached, so make that path drop the Controls references and survive AndroidX callbacks that
are still in flight.
Correctness therefore depends on teardown running, running in the right
order, and covering every reference — precisely the fragile surface that produced the
retained Window/NavigationPage/TabbedPage reports after #35487. This candidate must not
be the same adapter-teardown checks relocated, so it changes the ownership decision instead.

Mechanism-Level Difference (cause → effect)

Different root-cause hypothesis: the retained graph is not caused by missing teardown, it is
caused by ownership chosen at construction.

  1. context.GetActivity().Lifecycle is the Activity's LifecycleRegistry, which outlives
    every window and page.
  2. AndroidX registers observers on that registry on the adapter's behalf — the
    FragmentMaxLifecycleEnforcer observer added from onAttachedToRecyclerView, and the
    grace-period observer scheduled by restoreState() that is only removed on ON_DESTROY of
    the Activity. Each creates a strong edge Activity → observer → adapter.
  3. The adapter strongly owns _page (the TabbedPage) and the keys list of
    AdapterItemKey, each holding a child Page.
  4. So a single missed unregistration roots the whole Controls tree:
    Activity → adapter → Page → Page.Parent → NavigationPage → Window.

If the adapter instead supplies a registry it owns, every AndroidX observer edge points
into the collectable subgraph: registry → observer → adapter → registry is a cycle the .NET
GC collects, and the Activity holds no edge to the adapter at all. The observers "unregister
naturally" by becoming unreachable. Cause-to-effect contrast: the PR removes the edges out
of
the adapter at teardown time; this candidate removes the edge into the adapter at
construction time, so collectibility of TabbedPage/Window no longer depends on teardown
running, on its ordering, or on guards for in-flight callbacks.

Files Changed

None. The attempt was blocked before any tracked file was edited. git status --porcelain --untracked-files=no -- src/ is empty before and after; the 39 pre-existing harness
modifications under .github/ and eng/ are untouched.

Exact Saved Diff

CustomAgentLogsTmp/PRState/37310/PRAgent/try-fix/attempt-1/fix.diff is empty (0 bytes):

Test Results (per command)

# Command Result
1 pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform ios -TestFilter "Category=TabbedPage" NOT RUN (blocked before any fix was applied)
2 pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform ios -TestFilter "Category=Memory" NOT RUN (blocked)
3 pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform ios -TestFilter "Category=NavigationPage" NOT RUN (blocked)

No correction/retest round was consumed. The gate was not rerun and no full suite was run.

Pass / Fail / Blocked

Blocked.

Blocker Analysis

pwsh .github/scripts/EstablishBrokenBaseline.ps1 aborted at its fail-fast clean-tree gate:

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

The gate runs git status --porcelain --untracked-files=no and sees 39 pre-existing tracked
modifications/deletions under .github/scripts/, .github/skills/, and eng/scripts/ that
belong to the review harness and predate this attempt. The script's own remedies
(git add . && git commit, or git checkout -- .) are both forbidden here: the attempt must
preserve all pre-existing worktree changes, and the try-fix skill permits no git
revert/clean/stash/commit operations. The script's auto-restore branch does not help because
no prior baseline exists, so .github/.baseline-state.json was never created.

Per the try-fix baseline-file boundary rule, an absent baseline state means the attempt must
record Blocked before editing tracked code: without a RevertedFiles allow-list there is
no restorable modification set and -Restore could not undo the edits. Accordingly no product
file was modified and no device test was launched.

Actionable remedy for the orchestrator: either commit/stash the harness drift before invoking
try-fix, or narrow EstablishBrokenBaseline.ps1's dirty gate to the detected fix-file set
(e.g. src/) so harness drift is not conflated with an unrestored previous attempt.

Self-Review

0 findings — reviewer-findings.json is [] (no diff exists to review;
reviewer-findings.diff is correspondingly empty).

iOS Relevance Limitation

Explicitly called out: all three target product files
(MultiPageFragmentStateAdapter.cs, TabbedPageManager.cs, TabbedPage.Android.cs) are
Android-only — they are not compiled into an iOS binary. The allowed test matrix is iOS
only, so even a fully green iOS device-test pass would have shown only the absence of
cross-platform Controls regressions; it could never compile, execute, or validate the Android
retention mechanism this candidate targets. Any Android claim for this candidate would be
unverified, including whether the designed AndroidX LifecycleRegistry/ILifecycleOwner
usage compiles against the repo's AndroidX bindings (no other LifecycleRegistry usage exists
in src/ to pattern-match against). The pre-flight gate was INCONCLUSIVE for the same reason
and was not rerun.

Findings Count

0

Artifact Directory

CustomAgentLogsTmp/PRState/37310/PRAgent/try-fix/attempt-1/
(baseline.log, approach.md, reviewer-findings.json, reviewer-findings.diff,
result.txt, fix.diff, test-output.log, analysis.md)

Restoration Result

pwsh .github/scripts/EstablishBrokenBaseline.ps1 -Restore completed with:

No baseline state found. Nothing to restore.
Restored   False
Message    No baseline state found

Restored False is the expected and accepted outcome for this verified no-state path: Step 2
reported Blocked before any file was changed and never created
.github/.baseline-state.json. Post-restore verification confirms src/ has zero
modifications and the worktree still shows exactly the same 39 pre-existing harness changes
plus untracked harness paths that were present before the attempt.


Candidate 2 — Reference-Neutral Adapter State (Blocked)

Result: Blocked (baseline could not be established; no tracked code was edited, no test command was run)

Approach

Reference-neutral adapter state — designed, not applied.

Intended change, one file only: src/Controls/src/Core/Platform/Android/MultiPageFragmentStateAdapter.cs.

Replace the adapter's strong _page ownership with a WeakReference<MultiPage<T>> and replace its strong List<AdapterItemKey> index with reference-neutral stable-ID state: a ConditionalWeakTable<Page, AdapterItemKey> for page-to-key identity and weak item-ID entries for reverse lookup. A live FragmentContainer would continue to strongly own its AdapterItemKey, and that key would continue to own the page it is actively displaying. While a page is live, the conditional table returns the same key and generated ItemId; the existing invalidation callback can remove the mapping after handler disconnect.

This was not applied because baseline establishment failed before edits. Therefore its exact API shape, compilation, stable-ID behavior across late callbacks, and runtime effect remain unverified rather than asserted.

Prior Approaches Avoided

The existing PR's test-side approach is not reused: non-inlineable async helpers for WindowDoesNotLeak/DoesNotLeak, plus nulling captured locals before WaitForGC.

The existing PR's Android explicit teardown-and-guard mechanism is also not reused: _tearingDown/_disposed, BeginTeardown(), zero CountOverride, key clearing, NotifyDataSetChanged(), CreateFragment/GetItemId/ContainsItem guards, _page clearing during dispose, ordered manager BeginTeardown → adapter detach/dispose, RootViewChanged unsubscription, pending fragment and previousPage clearing, and manager clearing on handler disconnect.

Candidate 1's designed adapter-owned/self-scoped LifecycleRegistry, custom lifecycle owner, and ownership-at-construction hypothesis are likewise not reused.

The PR's shared mechanism assumes explicit teardown must sever managed edges and protect against callbacks that arrive afterward. Candidate 1 instead assumes the Activity lifecycle is the problematic long-lived owner and relocates lifecycle ownership. Candidate 2 does neither.

Mechanism-Level Difference (cause → effect)

Candidate 2 leaves context.GetActivity().Lifecycle, AndroidX observer registration, and teardown timing unchanged. Its distinct hypothesis is that retention becomes harmful because the observer-rooted adapter strongly owns the Controls graph:

  1. AndroidX may leave Activity → lifecycle observer → adapter reachable.
  2. Baseline adapter state then adds adapter → _page → TabbedPage and adapter → keys → AdapterItemKey → child Page.
  3. Those Pages connect through Controls parent/navigation state to NavigationPage and Window.
  4. Making _page weak and key indexes conditional/weak breaks the adapter's outbound strong edges, so a surviving observer can retain the adapter without necessarily retaining the Controls tree.
  5. Active fragments still retain their displayed AdapterItemKey and Page, while live pages retain stable identity through the conditional table. Their lifetimes follow active native presentation rather than the adapter observer's lifetime.

Thus the PR removes edges during explicit teardown; candidate 1 removes the Activity-to-adapter lifecycle ownership edge at construction; candidate 2 preserves that incoming edge but makes the adapter's outbound Control state reference-neutral.

Local Feasibility Evidence

The supplied baseline code shows that MultiPageFragmentStateAdapter is the target that holds both _page and the strong keys list. AdapterItemKey strongly stores Page, generates ItemId once, subscribes handler events, and invokes an invalidation callback on disconnect. FragmentContainer strongly stores the key while displaying the page. This supports a conditional/weak adapter index without modifying those read-only files. It also exposes an unresolved risk: callbacks after all live page/key owners disappear need a valid AndroidX response. Since the baseline blocker prohibited implementation and testing, this risk is recorded rather than hidden.

Files Changed

None. .github/.baseline-state.json was absent, so no RevertedFiles allow-list existed. Tracked src/ files were clean before the attempt and remained untouched. All pre-existing tracked/untracked harness changes were preserved.

Exact Saved Diff

CustomAgentLogsTmp/PRState/37310/PRAgent/try-fix/attempt-2/fix.diff is empty (0 bytes):

Test Results (per command)

# Command Result
1 pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform ios -TestFilter "Category=TabbedPage" NOT RUN — blocked before edits/tests
2 pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform ios -TestFilter "Category=Memory" NOT RUN — command 1 never started
3 pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform ios -TestFilter "Category=NavigationPage" NOT RUN — command 1 never started

No correction/retest was consumed. No full suite, gate verification, manual build, or other test was run.

Pass / Fail / Blocked

Blocked. This is an honest no-state baseline blocker, not a candidate pass or fail.

Blocker / Failure Analysis

pwsh .github/scripts/EstablishBrokenBaseline.ps1 failed its clean-tree gate on the same 39 pre-existing tracked harness changes under .github/ and eng/ recorded by candidate 1:

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

The invocation forbade modifying the dirty-tree gate, touching harness files, or using any cleanup other than the restore script. The baseline command created no .github/.baseline-state.json; a direct check reported STATE_ABSENT, and git status --porcelain --untracked-files=no -- src/ was empty. Under the skill's boundary rule, that required Blocked before tracked edits. The candidate therefore supplies a locally grounded design but no implementation claim.

iOS Relevance Limitation

All three target product files are Android-only and do not compile into an iOS binary. Even if the permitted iOS commands had run and passed, they could only have indicated absence of cross-platform regressions; they could not compile, execute, or validate this Android reference-retention mechanism. The gate had already returned INCONCLUSIVE for this reason and was not rerun.

Expert Self-Review

0 findings. reviewer-findings.json contains [], and reviewer-findings.diff is empty because no candidate diff exists. Inline review covered all eight overarching principles, the always-active Logic and Correctness, Regression Prevention, and Complexity Reduction dimensions, and the relevant Android/memory concerns. No file/line finding can be attached without a diff. The unimplemented design's late-callback/stable-ID risk is documented above rather than counted as a code finding.

Artifact Directory

CustomAgentLogsTmp/PRState/37310/PRAgent/try-fix/attempt-2/

Required artifacts present:

  • baseline.log
  • approach.md
  • reviewer-findings.json
  • reviewer-findings.diff
  • result.txt
  • fix.diff
  • test-output.log
  • analysis.md

Restoration Result

The only permitted cleanup command was run exactly and completed:

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

Restored False is the expected accepted result for this verified no-state path: baseline failed before any attempt edit and no state file existed. No product or harness file was changed by candidate 2.


Final Comparison / Status

Both bounded candidates are complete and both are Blocked before edits/tests by the same pre-existing dirty-harness baseline gate. Candidate 1 designed a self-scoped adapter lifecycle that would remove the Activity-owned observer edge; candidate 2 designed reference-neutral adapter state that would leave lifecycle ownership unchanged but remove strong adapter-to-Control edges. Neither design was applied or empirically validated, and neither may be claimed to fix Android behavior. No third candidate is pending.


📝 PR Finalize — Recommended Title & Description

Assessment: ✏️ Recommend updating — the current title lacks a platform/component prefix, and the otherwise detailed description should describe the submitted Android teardown mechanics and key files more precisely.

Recommended title

[Android] TabbedPage: Fix teardown leaks and re-enable memory device tests

Recommended description

### Description of Change

Device memory-leak tests began failing in the Candidate branch after https://github.com/dotnet/maui/pull/35487. This change fixes false-positive test roots in `WindowDoesNotLeak` and `NavigationPageTests.DoesNotLeak`, clears the captured navigation root in `TabbedPageTests.DoesNotLeak`, and adds Android `TabbedPage` adapter teardown so the page/manager graph can be released.

### Issue 1: `MemoryTests.WindowDoesNotLeak`

#### Root cause

`window` and `page` were locals in the async `WindowDoesNotLeak` method and were referenced across `await` boundaries, including by the callback passed to `CreateHandlerAndAddToWindow`. The compiler can hoist those locals into the generated async state machine and retain them while `WaitForGC` runs, producing a false-positive leak report.

#### Fix

Window/page creation and handler work now run in `CreateWindowLeakReferencesAsync`, a non-inlineable helper marked with `[MethodImpl(MethodImplOptions.NoInlining)]`. It returns only the collected `WeakReference` instances, so the caller does not retain strong `window` or `page` locals while waiting for collection.

The ineffective `TEST_FAILS_ON_ANDROID` / `TESTS_FAILS_ON_WINDOWS` / `TESTS_FAILS_ON_IOS` / `TESTS_FAILS_ON_MACCATALYST` conditional guard was also removed to re-enable the test.

### Issue 2: `TabbedPageTests.DoesNotLeak`

#### Root cause

Two retention paths compounded the failure:

1. The test's `navPage` local was captured by an async callback and remained in the generated closure while `WaitForGC` ran, transitively retaining the popped `TabbedPage`.
2. On Android, `MultiPageFragmentStateAdapter` uses the host Activity lifecycle and strongly references its `TabbedPage` and item keys. The existing disconnect path did not explicitly transition the adapter to an empty teardown state before detachment or clear all manager references.

#### Fix

- `TabbedPageTests.DoesNotLeak` clears the captured `navPage` local before `WaitForGC`.
- `MultiPageFragmentStateAdapter.cs` adds teardown/disposal state, reports zero items during teardown, clears its key list, notifies AndroidX of the data change, guards `CreateFragment`, `GetItemId`, and `ContainsItem` during teardown, and clears its page reference when disposed.
- `TabbedPageManager.cs` starts adapter teardown before detaching and disposing the adapter, defensively unsubscribes `RootViewChanged`, and clears `previousPage`.
- `TabbedPage.Android.cs` clears `_tabbedPageManager` when the handler disconnects so the old manager is not retained.

### Issue 3: `NavigationPageTests.DoesNotLeak`

#### Root cause

`navPage` and `window` were referenced across an `await` boundary in `NavigationPageTests.DoesNotLeak`, both directly and by the callback passed to `CreateHandlerAndAddToWindow`. Those locals could remain in the generated async state machine while `WaitForGC` ran. The failure reproduced in Release mode, where state-machine/JIT lifetime behavior differed from Debug.

#### Fix

Navigation-page creation and handler work now run in `CreateNavigationPageLeakReferencesAsync`, marked with `[MethodImpl(MethodImplOptions.NoInlining)]`. The helper returns only the `WeakReference` list, preventing the caller's state machine from retaining `navPage` and `window` during `WaitForGC`.

### Key files

- `src/Controls/src/Core/Platform/Android/MultiPageFragmentStateAdapter.cs`
- `src/Controls/src/Core/Platform/Android/TabbedPageManager.cs`
- `src/Controls/src/Core/TabbedPage/TabbedPage.Android.cs`
- `src/Controls/tests/DeviceTests/Memory/MemoryTests.cs`
- `src/Controls/tests/DeviceTests/Elements/TabbedPage/TabbedPageTests.cs`
- `src/Controls/tests/DeviceTests/Elements/NavigationPage/NavigationPageTests.cs`

### Validation

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

### Regression PR

https://github.com/dotnet/maui/pull/35487

### Issues Fixed

Fixes https://github.com/dotnet/maui/issues/36613

Related test tracking: https://github.com/dotnet/maui/issues/35985

### Before/after recordings

#### `WindowDoesNotLeak`

| Platform | Before | After |
|---|---|---|
| Android | <video src="https://github.com/user-attachments/assets/1d3986aa-5c5f-4d97-ab6e-96c586e53488"> | <video src="https://github.com/user-attachments/assets/3670bafa-6a75-47a8-8505-797901e7abeb"> |
| Mac Catalyst | <video src="https://github.com/user-attachments/assets/461534f8-21dd-46ab-bb62-c10a5f8ac71a"> | <video src="https://github.com/user-attachments/assets/d862eb7f-c33f-4866-a553-5264b1cda411"> |
| iOS | <video src="https://github.com/user-attachments/assets/41b71c49-26ac-4dcc-9e01-87dce42d5000"> | <video src="https://github.com/user-attachments/assets/9e03f7ca-d803-49b9-a159-4057320591a7"> |
| Windows | <video src="https://github.com/user-attachments/assets/73300a73-a9be-403b-b77e-2cc4418d10c9"> | <video src="https://github.com/user-attachments/assets/173cf2e3-5bde-4383-b07a-0b6b8422d03b"> |

#### `TabbedPageTests.DoesNotLeak`

| Platform | Before | After |
|---|---|---|
| Android | <video src="https://github.com/user-attachments/assets/604316e5-5849-4195-9e16-1c96d710c125"> | <video src="https://github.com/user-attachments/assets/50bc614c-814d-43d1-912b-446886086886"> |

#### `NavigationPageTests.DoesNotLeak`

| Platform | Before | After |
|---|---|---|
| Mac Catalyst | <video src="https://github.com/user-attachments/assets/cd6831a8-e8f6-4954-baff-055a2575a576"> | <video src="https://github.com/user-attachments/assets/6198e780-82e9-4eec-b3f5-a805f79d0ddd"> |
| iOS | <video src="https://github.com/user-attachments/assets/47edefd0-a416-4245-bbce-3e54c80aefa0"> | <video src="https://github.com/user-attachments/assets/84f2c31c-0d9d-4c3e-9f21-9a8f634e671f"> |

🏁 Report — Final Recommendation

⚠️ Final Recommendation: REQUEST CHANGES

Winner: pr-plus-reviewer

The submitted PR contains valid test-lifetime improvements, but the expert review found concrete Android teardown defects in the raw fix. The consolidated pr-plus-reviewer candidate preserves the good changes while removing unsafe Java-peer disposal, disconnecting retained adapter keys, clearing the adapter's page reference, and ensuring a late teardown fragment creates a view. Because those corrections are not present in the submitted PR, approval is not appropriate.

Comparative ranking

Rank Candidate Implementation Validation Assessment
1 pr-plus-reviewer Complete sandbox patch Blocked by Xcode/SDK mismatch; no tests ran Best code-level fix. It addresses the expert's concrete crash and retention paths without discarding the submitted state-machine fixes.
2 pr Submitted Gate INCONCLUSIVE The NoInlining helpers, captured-local clearing, event unsubscription, and handler reference release are sound, but explicit adapter disposal can break delayed JNI callbacks, undisconnected AdapterItemKey subscriptions retain the adapter graph, and the view-less placeholder can retain AndroidX callbacks.
3 try-fix-1 Design only; no diff Blocked before build/test Adapter-owned lifecycle is a plausible ownership-level alternative, but its AndroidX lifecycle contract and bindings were never implemented or compiled.
4 try-fix-2 Design only; no diff Blocked before build/test Reference-neutral adapter state is conceptually distinct, but stable-ID and late-callback behavior remain unresolved and no implementation exists.

No candidate passed or failed a regression assertion: the raw Gate was inconclusive, both try-fix candidates were blocked before edits, and all three pr-plus-reviewer commands stopped at the host's Xcode 26.5 versus iOS SDK 26.0 requirement. The environment failures therefore do not lower pr-plus-reviewer as regression failures, but they leave all runtime claims unverified. In particular, iOS/Mac Catalyst/Windows coverage newly enabled by the submitted test changes and the Android teardown mechanism still require valid platform execution.

Required submitted changes

Apply the pr-plus-reviewer/reviewer.patch behavior to the PR: disconnect keys before clearing them, release _page during teardown, do not explicitly dispose the AndroidX adapter peer, and avoid a view-less fallback fragment. The trusted Gate's inconclusive result is not itself a reason for this recommendation; the request for changes is based on the concrete lifecycle and retention defects.


📱 UI Tests — TabbedPage

Detected UI test categories: TabbedPage

✅ Deep UI tests — 46 passed, 0 failed, 5 skipped across 1 category on platform-pool agent (replaces in-process counts above).

🧪 UI Test Execution Results (deep, platform pool)

Category Tests Snapshot diffs
TabbedPage 46/51 (5 skipped) ✓ —
📎 Download drop-deep-uitests artifact (TRX + snapshot diffs)

🧭 Next Steps — reviewer patch required (pr-plus-reviewer)

The reviewer-enhanced candidate won, so the submitted PR still needs those changes.

Why: The reviewer-refined PR preserves the submitted test-lifetime fixes while correcting concrete AndroidX teardown crash and retention paths. Its targeted validations were blocked by an Xcode/iOS SDK mismatch rather than failed regression assertions, while both try-fix alternatives have no implementation.

Apply PRAgent/pr-plus-reviewer/reviewer.patch from the CopilotLogs
artifact (or follow the report's Required submitted-PR change), push the update, and run
the review again.

@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 Aug 18, 2026
kubaflo

This comment was marked as off-topic.

@kubaflo
kubaflo changed the base branch from main to inflight/current August 18, 2026 22:45
@kubaflo
kubaflo merged commit 349dfc9 into dotnet:inflight/current Aug 18, 2026
151 of 166 checks passed
@github-actions github-actions Bot added this to the .NET 10 SR11 milestone Aug 18, 2026
kubaflo pushed a commit that referenced this pull request Aug 27, 2026
…eak Device Test (#37310)

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


<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Issue Details

Device memory leak tests started failing in the Candidate branch after
PR #35487, indicating regressions in
memory leak validation across Windows, iOS, macOS, and Android. The
affected Does Not Leak and Window Does Not Leak tests were failing on
these platforms.

### Issue1: Window Does Not Leak 

### Root cause

The WindowDoesNotLeak test failed intermittently because window and page
were declared as locals inside an async Task method ( WindowDoesNotLeak
) and were referenced across await boundaries (both directly and inside
the lambda passed to CreateHandlerAndAddToWindow ). The C# compiler
hoists such locals into fields of the generated async state machine, and
those fields are not guaranteed to be cleared once the locals are no
longer needed. As a result, window and page remained artificially rooted
by the state machine instance for the entire duration of the subsequent
WaitForGC call, producing a false-positive "still alive" leak report
rather than reflecting an actual product defect.

### Solution description

The fix extracts the window/page creation and handler invocation logic
out of WindowDoesNotLeak into a new, non-inlineable helper method,
CreateWindowLeakReferencesAsync , marked with
[MethodImpl(MethodImplOptions.NoInlining)] . This helper creates window
and page , drives the handler lifecycle, and returns only the collected
WeakReference list. Since window and page now live in the helper's own
async state machine — which is discarded once the helper returns — they
are no longer reachable from WindowDoesNotLeak 's state machine during
the subsequent WaitForGC call, eliminating the artificial rooting. The
dead conditional compilation guard ( #if TEST_FAILS_ON_ANDROID &&
TESTS_FAILS_ON_WINDOWS && TESTS_FAILS_ON_IOS &&
TESTS_FAILS_ON_MACCATALYST ) that had disabled the test was also removed
to re-enable it.

### Issue2: TabbedPageTests.DoesNotLeak

### Root cause

The issue occurs because of two compounding factors. At the test level,
the navPage local was captured by an async lambda and accessed again
after an await , causing it to be hoisted into the compiler-generated
closure and transitively keep the popped TabbedPage alive through its
navigation stack. At the platform level on Android,
MultiPageFragmentStateAdapter was constructed using the host Activity's
long-lived Lifecycle , causing AndroidX to permanently register a
lifecycle observer that was never released because the Activity's
lifecycle never reached the destroyed state. This kept the adapter, and
the TabbedPage it referenced, permanently rooted in memory, while
AndroidX also failed to reclaim the associated child fragments.

### Solution description

The fix involves nulling the navPage local before the WaitForGC call at
the test level, combined with a production-level Android fix in
MultiPageFragmentStateAdapter.cs that introduces a teardown routine to
make AndroidX reclaim its fragments correctly and explicitly clears the
adapter's page reference on disposal. Supporting changes in
TabbedPageManager.cs and TabbedPage.Android.cs ensure the teardown
routine executes before the adapter is detached and that manager
references are cleared on disconnect. The resolution was verified
through repeated on-device Android test runs, all passing successfully.

### Issue3: NavigationPageTests.DoesNotLeak

### Root Cause
 
The issue occurs because of the `navPage` and `window` locals in
`NavigationPageTests.DoesNotLeak` being referenced across an `await`
boundary — both directly and inside the lambda passed to
`CreateHandlerAndAddToWindow`. The C# compiler hoists such locals into
fields of the generated async state machine for the test method, and
those fields are not guaranteed to be cleared once the locals are no
longer needed. As a result, `navPage` and `window` remained artificially
rooted by the state machine instance for the duration of the subsequent
`WaitForGC` call, producing a false-positive "still alive" leak report
rather than reflecting an actual product defect.
 
This issue was only replicated in Release mode, since Release-mode
JIT/compiler optimizations affect how and when the hoisted state-machine
fields are cleared, whereas Debug builds happened to clear or avoid
rooting them, masking the problem locally.
 
### Solution Description
 
The fix involves extracting the `navPage`/`window` creation and handler
invocation logic out of `DoesNotLeak` into a new, non-inlineable helper
method, `CreateNavigationPageLeakReferencesAsync`, marked with
`[MethodImpl(MethodImplOptions.NoInlining)]`. This helper creates
`navPage` and `window`, drives the handler lifecycle, and returns only
the collected `WeakReference` list.
 
Since `navPage` and `window` now live in the helper's own async state
machine — which is discarded once the helper returns — they are no
longer reachable from `DoesNotLeak`'s state machine during the
subsequent `WaitForGC` call, eliminating the artificial rooting.

Validated the behavior in the following platforms
 
- [x] iOS
- [x] Mac
- [x] Android
- [x] Windows

### Regression PR

PR #35487
 
### Issues Fixed
  
Fixes #36613

### Output  Screenshot

### Issue1: Window Does Not Leak 

|Platform|Before|After|
|--|--|--|
|Android| <video
src="https://github.com/user-attachments/assets/1d3986aa-5c5f-4d97-ab6e-96c586e53488"
>| <video
src="https://github.com/user-attachments/assets/3670bafa-6a75-47a8-8505-797901e7abeb">|
|Mac|<video
src="https://github.com/user-attachments/assets/461534f8-21dd-46ab-bb62-c10a5f8ac71a">
|<video
src="https://github.com/user-attachments/assets/d862eb7f-c33f-4866-a553-5264b1cda411">|
|iOS|<video
src="https://github.com/user-attachments/assets/41b71c49-26ac-4dcc-9e01-87dce42d5000">|<video
src="https://github.com/user-attachments/assets/9e03f7ca-d803-49b9-a159-4057320591a7">|
|Windows|<video
src="https://github.com/user-attachments/assets/73300a73-a9be-403b-b77e-2cc4418d10c9">|<video
src="https://github.com/user-attachments/assets/173cf2e3-5bde-4383-b07a-0b6b8422d03b">
|

### Issue2: TabbedPageTests.DoesNotLeak

|Platform|Before|After|
|--|--|--|
|Android| <video
src="https://github.com/user-attachments/assets/604316e5-5849-4195-9e16-1c96d710c125"
>| <video
src="https://github.com/user-attachments/assets/50bc614c-814d-43d1-912b-446886086886">|

### Issue3: NavigationPageTests.DoesNotLeak

|Platform|Before|After|
|--|--|--|
|Mac|<video
src="https://github.com/user-attachments/assets/cd6831a8-e8f6-4954-baff-055a2575a576">
|<video
src="https://github.com/user-attachments/assets/6198e780-82e9-4eec-b3f5-a805f79d0ddd">|
|iOS|<video
src="https://github.com/user-attachments/assets/47edefd0-a416-4245-bbce-3e54c80aefa0">|<video
src="https://github.com/user-attachments/assets/84f2c31c-0d9d-4c3e-9f21-9a8f634e671f">|
kubaflo pushed a commit that referenced this pull request Sep 2, 2026
…eak Device Test (#37310)

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

<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

Device memory leak tests started failing in the Candidate branch after
PR #35487, indicating regressions in
memory leak validation across Windows, iOS, macOS, and Android. The
affected Does Not Leak and Window Does Not Leak tests were failing on
these platforms.

The WindowDoesNotLeak test failed intermittently because window and page
were declared as locals inside an async Task method ( WindowDoesNotLeak
) and were referenced across await boundaries (both directly and inside
the lambda passed to CreateHandlerAndAddToWindow ). The C# compiler
hoists such locals into fields of the generated async state machine, and
those fields are not guaranteed to be cleared once the locals are no
longer needed. As a result, window and page remained artificially rooted
by the state machine instance for the entire duration of the subsequent
WaitForGC call, producing a false-positive "still alive" leak report
rather than reflecting an actual product defect.

The fix extracts the window/page creation and handler invocation logic
out of WindowDoesNotLeak into a new, non-inlineable helper method,
CreateWindowLeakReferencesAsync , marked with
[MethodImpl(MethodImplOptions.NoInlining)] . This helper creates window
and page , drives the handler lifecycle, and returns only the collected
WeakReference list. Since window and page now live in the helper's own
async state machine — which is discarded once the helper returns — they
are no longer reachable from WindowDoesNotLeak 's state machine during
the subsequent WaitForGC call, eliminating the artificial rooting. The
dead conditional compilation guard ( #if TEST_FAILS_ON_ANDROID &&
TESTS_FAILS_ON_WINDOWS && TESTS_FAILS_ON_IOS &&
TESTS_FAILS_ON_MACCATALYST ) that had disabled the test was also removed
to re-enable it.

The issue occurs because of two compounding factors. At the test level,
the navPage local was captured by an async lambda and accessed again
after an await , causing it to be hoisted into the compiler-generated
closure and transitively keep the popped TabbedPage alive through its
navigation stack. At the platform level on Android,
MultiPageFragmentStateAdapter was constructed using the host Activity's
long-lived Lifecycle , causing AndroidX to permanently register a
lifecycle observer that was never released because the Activity's
lifecycle never reached the destroyed state. This kept the adapter, and
the TabbedPage it referenced, permanently rooted in memory, while
AndroidX also failed to reclaim the associated child fragments.

The fix involves nulling the navPage local before the WaitForGC call at
the test level, combined with a production-level Android fix in
MultiPageFragmentStateAdapter.cs that introduces a teardown routine to
make AndroidX reclaim its fragments correctly and explicitly clears the
adapter's page reference on disposal. Supporting changes in
TabbedPageManager.cs and TabbedPage.Android.cs ensure the teardown
routine executes before the adapter is detached and that manager
references are cleared on disconnect. The resolution was verified
through repeated on-device Android test runs, all passing successfully.

The issue occurs because of the `navPage` and `window` locals in
`NavigationPageTests.DoesNotLeak` being referenced across an `await`
boundary — both directly and inside the lambda passed to
`CreateHandlerAndAddToWindow`. The C# compiler hoists such locals into
fields of the generated async state machine for the test method, and
those fields are not guaranteed to be cleared once the locals are no
longer needed. As a result, `navPage` and `window` remained artificially
rooted by the state machine instance for the duration of the subsequent
`WaitForGC` call, producing a false-positive "still alive" leak report
rather than reflecting an actual product defect.

This issue was only replicated in Release mode, since Release-mode
JIT/compiler optimizations affect how and when the hoisted state-machine
fields are cleared, whereas Debug builds happened to clear or avoid
rooting them, masking the problem locally.

The fix involves extracting the `navPage`/`window` creation and handler
invocation logic out of `DoesNotLeak` into a new, non-inlineable helper
method, `CreateNavigationPageLeakReferencesAsync`, marked with
`[MethodImpl(MethodImplOptions.NoInlining)]`. This helper creates
`navPage` and `window`, drives the handler lifecycle, and returns only
the collected `WeakReference` list.

Since `navPage` and `window` now live in the helper's own async state
machine — which is discarded once the helper returns — they are no
longer reachable from `DoesNotLeak`'s state machine during the
subsequent `WaitForGC` call, eliminating the artificial rooting.

Validated the behavior in the following platforms

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

PR #35487

Fixes #36613

|Platform|Before|After|
|--|--|--|
|Android| <video
src="https://github.com/user-attachments/assets/1d3986aa-5c5f-4d97-ab6e-96c586e53488"
>| <video
src="https://github.com/user-attachments/assets/3670bafa-6a75-47a8-8505-797901e7abeb">|
|Mac|<video
src="https://github.com/user-attachments/assets/461534f8-21dd-46ab-bb62-c10a5f8ac71a">
|<video
src="https://github.com/user-attachments/assets/d862eb7f-c33f-4866-a553-5264b1cda411">|
|iOS|<video
src="https://github.com/user-attachments/assets/41b71c49-26ac-4dcc-9e01-87dce42d5000">|<video
src="https://github.com/user-attachments/assets/9e03f7ca-d803-49b9-a159-4057320591a7">|
|Windows|<video
src="https://github.com/user-attachments/assets/73300a73-a9be-403b-b77e-2cc4418d10c9">|<video
src="https://github.com/user-attachments/assets/173cf2e3-5bde-4383-b07a-0b6b8422d03b">
|

|Platform|Before|After|
|--|--|--|
|Android| <video
src="https://github.com/user-attachments/assets/604316e5-5849-4195-9e16-1c96d710c125"
>| <video
src="https://github.com/user-attachments/assets/50bc614c-814d-43d1-912b-446886086886">|

|Platform|Before|After|
|--|--|--|
|Mac|<video
src="https://github.com/user-attachments/assets/cd6831a8-e8f6-4954-baff-055a2575a576">
|<video
src="https://github.com/user-attachments/assets/6198e780-82e9-4eec-b3f5-a805f79d0ddd">|
|iOS|<video
src="https://github.com/user-attachments/assets/47edefd0-a416-4245-bbce-3e54c80aefa0">|<video
src="https://github.com/user-attachments/assets/84f2c31c-0d9d-4c3e-9f21-9a8f634e671f">|
kubaflo pushed a commit that referenced this pull request Sep 3, 2026
…eak Device Test (#37310)

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


<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Issue Details

Device memory leak tests started failing in the Candidate branch after
PR #35487, indicating regressions in
memory leak validation across Windows, iOS, macOS, and Android. The
affected Does Not Leak and Window Does Not Leak tests were failing on
these platforms.

### Issue1: Window Does Not Leak 

### Root cause

The WindowDoesNotLeak test failed intermittently because window and page
were declared as locals inside an async Task method ( WindowDoesNotLeak
) and were referenced across await boundaries (both directly and inside
the lambda passed to CreateHandlerAndAddToWindow ). The C# compiler
hoists such locals into fields of the generated async state machine, and
those fields are not guaranteed to be cleared once the locals are no
longer needed. As a result, window and page remained artificially rooted
by the state machine instance for the entire duration of the subsequent
WaitForGC call, producing a false-positive "still alive" leak report
rather than reflecting an actual product defect.

### Solution description

The fix extracts the window/page creation and handler invocation logic
out of WindowDoesNotLeak into a new, non-inlineable helper method,
CreateWindowLeakReferencesAsync , marked with
[MethodImpl(MethodImplOptions.NoInlining)] . This helper creates window
and page , drives the handler lifecycle, and returns only the collected
WeakReference list. Since window and page now live in the helper's own
async state machine — which is discarded once the helper returns — they
are no longer reachable from WindowDoesNotLeak 's state machine during
the subsequent WaitForGC call, eliminating the artificial rooting. The
dead conditional compilation guard ( #if TEST_FAILS_ON_ANDROID &&
TESTS_FAILS_ON_WINDOWS && TESTS_FAILS_ON_IOS &&
TESTS_FAILS_ON_MACCATALYST ) that had disabled the test was also removed
to re-enable it.

### Issue2: TabbedPageTests.DoesNotLeak

### Root cause

The issue occurs because of two compounding factors. At the test level,
the navPage local was captured by an async lambda and accessed again
after an await , causing it to be hoisted into the compiler-generated
closure and transitively keep the popped TabbedPage alive through its
navigation stack. At the platform level on Android,
MultiPageFragmentStateAdapter was constructed using the host Activity's
long-lived Lifecycle , causing AndroidX to permanently register a
lifecycle observer that was never released because the Activity's
lifecycle never reached the destroyed state. This kept the adapter, and
the TabbedPage it referenced, permanently rooted in memory, while
AndroidX also failed to reclaim the associated child fragments.

### Solution description

The fix involves nulling the navPage local before the WaitForGC call at
the test level, combined with a production-level Android fix in
MultiPageFragmentStateAdapter.cs that introduces a teardown routine to
make AndroidX reclaim its fragments correctly and explicitly clears the
adapter's page reference on disposal. Supporting changes in
TabbedPageManager.cs and TabbedPage.Android.cs ensure the teardown
routine executes before the adapter is detached and that manager
references are cleared on disconnect. The resolution was verified
through repeated on-device Android test runs, all passing successfully.

### Issue3: NavigationPageTests.DoesNotLeak

### Root Cause
 
The issue occurs because of the `navPage` and `window` locals in
`NavigationPageTests.DoesNotLeak` being referenced across an `await`
boundary — both directly and inside the lambda passed to
`CreateHandlerAndAddToWindow`. The C# compiler hoists such locals into
fields of the generated async state machine for the test method, and
those fields are not guaranteed to be cleared once the locals are no
longer needed. As a result, `navPage` and `window` remained artificially
rooted by the state machine instance for the duration of the subsequent
`WaitForGC` call, producing a false-positive "still alive" leak report
rather than reflecting an actual product defect.
 
This issue was only replicated in Release mode, since Release-mode
JIT/compiler optimizations affect how and when the hoisted state-machine
fields are cleared, whereas Debug builds happened to clear or avoid
rooting them, masking the problem locally.
 
### Solution Description
 
The fix involves extracting the `navPage`/`window` creation and handler
invocation logic out of `DoesNotLeak` into a new, non-inlineable helper
method, `CreateNavigationPageLeakReferencesAsync`, marked with
`[MethodImpl(MethodImplOptions.NoInlining)]`. This helper creates
`navPage` and `window`, drives the handler lifecycle, and returns only
the collected `WeakReference` list.
 
Since `navPage` and `window` now live in the helper's own async state
machine — which is discarded once the helper returns — they are no
longer reachable from `DoesNotLeak`'s state machine during the
subsequent `WaitForGC` call, eliminating the artificial rooting.

Validated the behavior in the following platforms
 
- [x] iOS
- [x] Mac
- [x] Android
- [x] Windows

### Regression PR

PR #35487
 
### Issues Fixed
  
Fixes #36613

### Output  Screenshot

### Issue1: Window Does Not Leak 

|Platform|Before|After|
|--|--|--|
|Android| <video
src="https://github.com/user-attachments/assets/1d3986aa-5c5f-4d97-ab6e-96c586e53488"
>| <video
src="https://github.com/user-attachments/assets/3670bafa-6a75-47a8-8505-797901e7abeb">|
|Mac|<video
src="https://github.com/user-attachments/assets/461534f8-21dd-46ab-bb62-c10a5f8ac71a">
|<video
src="https://github.com/user-attachments/assets/d862eb7f-c33f-4866-a553-5264b1cda411">|
|iOS|<video
src="https://github.com/user-attachments/assets/41b71c49-26ac-4dcc-9e01-87dce42d5000">|<video
src="https://github.com/user-attachments/assets/9e03f7ca-d803-49b9-a159-4057320591a7">|
|Windows|<video
src="https://github.com/user-attachments/assets/73300a73-a9be-403b-b77e-2cc4418d10c9">|<video
src="https://github.com/user-attachments/assets/173cf2e3-5bde-4383-b07a-0b6b8422d03b">
|

### Issue2: TabbedPageTests.DoesNotLeak

|Platform|Before|After|
|--|--|--|
|Android| <video
src="https://github.com/user-attachments/assets/604316e5-5849-4195-9e16-1c96d710c125"
>| <video
src="https://github.com/user-attachments/assets/50bc614c-814d-43d1-912b-446886086886">|

### Issue3: NavigationPageTests.DoesNotLeak

|Platform|Before|After|
|--|--|--|
|Mac|<video
src="https://github.com/user-attachments/assets/cd6831a8-e8f6-4954-baff-055a2575a576">
|<video
src="https://github.com/user-attachments/assets/6198e780-82e9-4eec-b3f5-a805f79d0ddd">|
|iOS|<video
src="https://github.com/user-attachments/assets/47edefd0-a416-4245-bbce-3e54c80aefa0">|<video
src="https://github.com/user-attachments/assets/84f2c31c-0d9d-4c3e-9f21-9a8f634e671f">|
kubaflo pushed a commit that referenced this pull request Sep 6, 2026
…eak Device Test (#37310)

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


<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Issue Details

Device memory leak tests started failing in the Candidate branch after
PR #35487, indicating regressions in
memory leak validation across Windows, iOS, macOS, and Android. The
affected Does Not Leak and Window Does Not Leak tests were failing on
these platforms.

### Issue1: Window Does Not Leak 

### Root cause

The WindowDoesNotLeak test failed intermittently because window and page
were declared as locals inside an async Task method ( WindowDoesNotLeak
) and were referenced across await boundaries (both directly and inside
the lambda passed to CreateHandlerAndAddToWindow ). The C# compiler
hoists such locals into fields of the generated async state machine, and
those fields are not guaranteed to be cleared once the locals are no
longer needed. As a result, window and page remained artificially rooted
by the state machine instance for the entire duration of the subsequent
WaitForGC call, producing a false-positive "still alive" leak report
rather than reflecting an actual product defect.

### Solution description

The fix extracts the window/page creation and handler invocation logic
out of WindowDoesNotLeak into a new, non-inlineable helper method,
CreateWindowLeakReferencesAsync , marked with
[MethodImpl(MethodImplOptions.NoInlining)] . This helper creates window
and page , drives the handler lifecycle, and returns only the collected
WeakReference list. Since window and page now live in the helper's own
async state machine — which is discarded once the helper returns — they
are no longer reachable from WindowDoesNotLeak 's state machine during
the subsequent WaitForGC call, eliminating the artificial rooting. The
dead conditional compilation guard ( #if TEST_FAILS_ON_ANDROID &&
TESTS_FAILS_ON_WINDOWS && TESTS_FAILS_ON_IOS &&
TESTS_FAILS_ON_MACCATALYST ) that had disabled the test was also removed
to re-enable it.

### Issue2: TabbedPageTests.DoesNotLeak

### Root cause

The issue occurs because of two compounding factors. At the test level,
the navPage local was captured by an async lambda and accessed again
after an await , causing it to be hoisted into the compiler-generated
closure and transitively keep the popped TabbedPage alive through its
navigation stack. At the platform level on Android,
MultiPageFragmentStateAdapter was constructed using the host Activity's
long-lived Lifecycle , causing AndroidX to permanently register a
lifecycle observer that was never released because the Activity's
lifecycle never reached the destroyed state. This kept the adapter, and
the TabbedPage it referenced, permanently rooted in memory, while
AndroidX also failed to reclaim the associated child fragments.

### Solution description

The fix involves nulling the navPage local before the WaitForGC call at
the test level, combined with a production-level Android fix in
MultiPageFragmentStateAdapter.cs that introduces a teardown routine to
make AndroidX reclaim its fragments correctly and explicitly clears the
adapter's page reference on disposal. Supporting changes in
TabbedPageManager.cs and TabbedPage.Android.cs ensure the teardown
routine executes before the adapter is detached and that manager
references are cleared on disconnect. The resolution was verified
through repeated on-device Android test runs, all passing successfully.

### Issue3: NavigationPageTests.DoesNotLeak

### Root Cause
 
The issue occurs because of the `navPage` and `window` locals in
`NavigationPageTests.DoesNotLeak` being referenced across an `await`
boundary — both directly and inside the lambda passed to
`CreateHandlerAndAddToWindow`. The C# compiler hoists such locals into
fields of the generated async state machine for the test method, and
those fields are not guaranteed to be cleared once the locals are no
longer needed. As a result, `navPage` and `window` remained artificially
rooted by the state machine instance for the duration of the subsequent
`WaitForGC` call, producing a false-positive "still alive" leak report
rather than reflecting an actual product defect.
 
This issue was only replicated in Release mode, since Release-mode
JIT/compiler optimizations affect how and when the hoisted state-machine
fields are cleared, whereas Debug builds happened to clear or avoid
rooting them, masking the problem locally.
 
### Solution Description
 
The fix involves extracting the `navPage`/`window` creation and handler
invocation logic out of `DoesNotLeak` into a new, non-inlineable helper
method, `CreateNavigationPageLeakReferencesAsync`, marked with
`[MethodImpl(MethodImplOptions.NoInlining)]`. This helper creates
`navPage` and `window`, drives the handler lifecycle, and returns only
the collected `WeakReference` list.
 
Since `navPage` and `window` now live in the helper's own async state
machine — which is discarded once the helper returns — they are no
longer reachable from `DoesNotLeak`'s state machine during the
subsequent `WaitForGC` call, eliminating the artificial rooting.

Validated the behavior in the following platforms
 
- [x] iOS
- [x] Mac
- [x] Android
- [x] Windows

### Regression PR

PR #35487
 
### Issues Fixed
  
Fixes #36613

### Output  Screenshot

### Issue1: Window Does Not Leak 

|Platform|Before|After|
|--|--|--|
|Android| <video
src="https://github.com/user-attachments/assets/1d3986aa-5c5f-4d97-ab6e-96c586e53488"
>| <video
src="https://github.com/user-attachments/assets/3670bafa-6a75-47a8-8505-797901e7abeb">|
|Mac|<video
src="https://github.com/user-attachments/assets/461534f8-21dd-46ab-bb62-c10a5f8ac71a">
|<video
src="https://github.com/user-attachments/assets/d862eb7f-c33f-4866-a553-5264b1cda411">|
|iOS|<video
src="https://github.com/user-attachments/assets/41b71c49-26ac-4dcc-9e01-87dce42d5000">|<video
src="https://github.com/user-attachments/assets/9e03f7ca-d803-49b9-a159-4057320591a7">|
|Windows|<video
src="https://github.com/user-attachments/assets/73300a73-a9be-403b-b77e-2cc4418d10c9">|<video
src="https://github.com/user-attachments/assets/173cf2e3-5bde-4383-b07a-0b6b8422d03b">
|

### Issue2: TabbedPageTests.DoesNotLeak

|Platform|Before|After|
|--|--|--|
|Android| <video
src="https://github.com/user-attachments/assets/604316e5-5849-4195-9e16-1c96d710c125"
>| <video
src="https://github.com/user-attachments/assets/50bc614c-814d-43d1-912b-446886086886">|

### Issue3: NavigationPageTests.DoesNotLeak

|Platform|Before|After|
|--|--|--|
|Mac|<video
src="https://github.com/user-attachments/assets/cd6831a8-e8f6-4954-baff-055a2575a576">
|<video
src="https://github.com/user-attachments/assets/6198e780-82e9-4eec-b3f5-a805f79d0ddd">|
|iOS|<video
src="https://github.com/user-attachments/assets/47edefd0-a416-4245-bbce-3e54c80aefa0">|<video
src="https://github.com/user-attachments/assets/84f2c31c-0d9d-4c3e-9f21-9a8f634e671f">|
kubaflo pushed a commit that referenced this pull request Sep 7, 2026
…eak Device Test (#37310)

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


<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Issue Details

Device memory leak tests started failing in the Candidate branch after
PR #35487, indicating regressions in
memory leak validation across Windows, iOS, macOS, and Android. The
affected Does Not Leak and Window Does Not Leak tests were failing on
these platforms.

### Issue1: Window Does Not Leak 

### Root cause

The WindowDoesNotLeak test failed intermittently because window and page
were declared as locals inside an async Task method ( WindowDoesNotLeak
) and were referenced across await boundaries (both directly and inside
the lambda passed to CreateHandlerAndAddToWindow ). The C# compiler
hoists such locals into fields of the generated async state machine, and
those fields are not guaranteed to be cleared once the locals are no
longer needed. As a result, window and page remained artificially rooted
by the state machine instance for the entire duration of the subsequent
WaitForGC call, producing a false-positive "still alive" leak report
rather than reflecting an actual product defect.

### Solution description

The fix extracts the window/page creation and handler invocation logic
out of WindowDoesNotLeak into a new, non-inlineable helper method,
CreateWindowLeakReferencesAsync , marked with
[MethodImpl(MethodImplOptions.NoInlining)] . This helper creates window
and page , drives the handler lifecycle, and returns only the collected
WeakReference list. Since window and page now live in the helper's own
async state machine — which is discarded once the helper returns — they
are no longer reachable from WindowDoesNotLeak 's state machine during
the subsequent WaitForGC call, eliminating the artificial rooting. The
dead conditional compilation guard ( #if TEST_FAILS_ON_ANDROID &&
TESTS_FAILS_ON_WINDOWS && TESTS_FAILS_ON_IOS &&
TESTS_FAILS_ON_MACCATALYST ) that had disabled the test was also removed
to re-enable it.

### Issue2: TabbedPageTests.DoesNotLeak

### Root cause

The issue occurs because of two compounding factors. At the test level,
the navPage local was captured by an async lambda and accessed again
after an await , causing it to be hoisted into the compiler-generated
closure and transitively keep the popped TabbedPage alive through its
navigation stack. At the platform level on Android,
MultiPageFragmentStateAdapter was constructed using the host Activity's
long-lived Lifecycle , causing AndroidX to permanently register a
lifecycle observer that was never released because the Activity's
lifecycle never reached the destroyed state. This kept the adapter, and
the TabbedPage it referenced, permanently rooted in memory, while
AndroidX also failed to reclaim the associated child fragments.

### Solution description

The fix involves nulling the navPage local before the WaitForGC call at
the test level, combined with a production-level Android fix in
MultiPageFragmentStateAdapter.cs that introduces a teardown routine to
make AndroidX reclaim its fragments correctly and explicitly clears the
adapter's page reference on disposal. Supporting changes in
TabbedPageManager.cs and TabbedPage.Android.cs ensure the teardown
routine executes before the adapter is detached and that manager
references are cleared on disconnect. The resolution was verified
through repeated on-device Android test runs, all passing successfully.

### Issue3: NavigationPageTests.DoesNotLeak

### Root Cause
 
The issue occurs because of the `navPage` and `window` locals in
`NavigationPageTests.DoesNotLeak` being referenced across an `await`
boundary — both directly and inside the lambda passed to
`CreateHandlerAndAddToWindow`. The C# compiler hoists such locals into
fields of the generated async state machine for the test method, and
those fields are not guaranteed to be cleared once the locals are no
longer needed. As a result, `navPage` and `window` remained artificially
rooted by the state machine instance for the duration of the subsequent
`WaitForGC` call, producing a false-positive "still alive" leak report
rather than reflecting an actual product defect.
 
This issue was only replicated in Release mode, since Release-mode
JIT/compiler optimizations affect how and when the hoisted state-machine
fields are cleared, whereas Debug builds happened to clear or avoid
rooting them, masking the problem locally.
 
### Solution Description
 
The fix involves extracting the `navPage`/`window` creation and handler
invocation logic out of `DoesNotLeak` into a new, non-inlineable helper
method, `CreateNavigationPageLeakReferencesAsync`, marked with
`[MethodImpl(MethodImplOptions.NoInlining)]`. This helper creates
`navPage` and `window`, drives the handler lifecycle, and returns only
the collected `WeakReference` list.
 
Since `navPage` and `window` now live in the helper's own async state
machine — which is discarded once the helper returns — they are no
longer reachable from `DoesNotLeak`'s state machine during the
subsequent `WaitForGC` call, eliminating the artificial rooting.

Validated the behavior in the following platforms
 
- [x] iOS
- [x] Mac
- [x] Android
- [x] Windows

### Regression PR

PR #35487
 
### Issues Fixed
  
Fixes #36613

### Output  Screenshot

### Issue1: Window Does Not Leak 

|Platform|Before|After|
|--|--|--|
|Android| <video
src="https://github.com/user-attachments/assets/1d3986aa-5c5f-4d97-ab6e-96c586e53488"
>| <video
src="https://github.com/user-attachments/assets/3670bafa-6a75-47a8-8505-797901e7abeb">|
|Mac|<video
src="https://github.com/user-attachments/assets/461534f8-21dd-46ab-bb62-c10a5f8ac71a">
|<video
src="https://github.com/user-attachments/assets/d862eb7f-c33f-4866-a553-5264b1cda411">|
|iOS|<video
src="https://github.com/user-attachments/assets/41b71c49-26ac-4dcc-9e01-87dce42d5000">|<video
src="https://github.com/user-attachments/assets/9e03f7ca-d803-49b9-a159-4057320591a7">|
|Windows|<video
src="https://github.com/user-attachments/assets/73300a73-a9be-403b-b77e-2cc4418d10c9">|<video
src="https://github.com/user-attachments/assets/173cf2e3-5bde-4383-b07a-0b6b8422d03b">
|

### Issue2: TabbedPageTests.DoesNotLeak

|Platform|Before|After|
|--|--|--|
|Android| <video
src="https://github.com/user-attachments/assets/604316e5-5849-4195-9e16-1c96d710c125"
>| <video
src="https://github.com/user-attachments/assets/50bc614c-814d-43d1-912b-446886086886">|

### Issue3: NavigationPageTests.DoesNotLeak

|Platform|Before|After|
|--|--|--|
|Mac|<video
src="https://github.com/user-attachments/assets/cd6831a8-e8f6-4954-baff-055a2575a576">
|<video
src="https://github.com/user-attachments/assets/6198e780-82e9-4eec-b3f5-a805f79d0ddd">|
|iOS|<video
src="https://github.com/user-attachments/assets/47edefd0-a416-4245-bbce-3e54c80aefa0">|<video
src="https://github.com/user-attachments/assets/84f2c31c-0d9d-4c3e-9f21-9a8f634e671f">|
kubaflo pushed a commit that referenced this pull request Sep 8, 2026
…eak Device Test (#37310)

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


<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Issue Details

Device memory leak tests started failing in the Candidate branch after
PR #35487, indicating regressions in
memory leak validation across Windows, iOS, macOS, and Android. The
affected Does Not Leak and Window Does Not Leak tests were failing on
these platforms.

### Issue1: Window Does Not Leak 

### Root cause

The WindowDoesNotLeak test failed intermittently because window and page
were declared as locals inside an async Task method ( WindowDoesNotLeak
) and were referenced across await boundaries (both directly and inside
the lambda passed to CreateHandlerAndAddToWindow ). The C# compiler
hoists such locals into fields of the generated async state machine, and
those fields are not guaranteed to be cleared once the locals are no
longer needed. As a result, window and page remained artificially rooted
by the state machine instance for the entire duration of the subsequent
WaitForGC call, producing a false-positive "still alive" leak report
rather than reflecting an actual product defect.

### Solution description

The fix extracts the window/page creation and handler invocation logic
out of WindowDoesNotLeak into a new, non-inlineable helper method,
CreateWindowLeakReferencesAsync , marked with
[MethodImpl(MethodImplOptions.NoInlining)] . This helper creates window
and page , drives the handler lifecycle, and returns only the collected
WeakReference list. Since window and page now live in the helper's own
async state machine — which is discarded once the helper returns — they
are no longer reachable from WindowDoesNotLeak 's state machine during
the subsequent WaitForGC call, eliminating the artificial rooting. The
dead conditional compilation guard ( #if TEST_FAILS_ON_ANDROID &&
TESTS_FAILS_ON_WINDOWS && TESTS_FAILS_ON_IOS &&
TESTS_FAILS_ON_MACCATALYST ) that had disabled the test was also removed
to re-enable it.

### Issue2: TabbedPageTests.DoesNotLeak

### Root cause

The issue occurs because of two compounding factors. At the test level,
the navPage local was captured by an async lambda and accessed again
after an await , causing it to be hoisted into the compiler-generated
closure and transitively keep the popped TabbedPage alive through its
navigation stack. At the platform level on Android,
MultiPageFragmentStateAdapter was constructed using the host Activity's
long-lived Lifecycle , causing AndroidX to permanently register a
lifecycle observer that was never released because the Activity's
lifecycle never reached the destroyed state. This kept the adapter, and
the TabbedPage it referenced, permanently rooted in memory, while
AndroidX also failed to reclaim the associated child fragments.

### Solution description

The fix involves nulling the navPage local before the WaitForGC call at
the test level, combined with a production-level Android fix in
MultiPageFragmentStateAdapter.cs that introduces a teardown routine to
make AndroidX reclaim its fragments correctly and explicitly clears the
adapter's page reference on disposal. Supporting changes in
TabbedPageManager.cs and TabbedPage.Android.cs ensure the teardown
routine executes before the adapter is detached and that manager
references are cleared on disconnect. The resolution was verified
through repeated on-device Android test runs, all passing successfully.

### Issue3: NavigationPageTests.DoesNotLeak

### Root Cause
 
The issue occurs because of the `navPage` and `window` locals in
`NavigationPageTests.DoesNotLeak` being referenced across an `await`
boundary — both directly and inside the lambda passed to
`CreateHandlerAndAddToWindow`. The C# compiler hoists such locals into
fields of the generated async state machine for the test method, and
those fields are not guaranteed to be cleared once the locals are no
longer needed. As a result, `navPage` and `window` remained artificially
rooted by the state machine instance for the duration of the subsequent
`WaitForGC` call, producing a false-positive "still alive" leak report
rather than reflecting an actual product defect.
 
This issue was only replicated in Release mode, since Release-mode
JIT/compiler optimizations affect how and when the hoisted state-machine
fields are cleared, whereas Debug builds happened to clear or avoid
rooting them, masking the problem locally.
 
### Solution Description
 
The fix involves extracting the `navPage`/`window` creation and handler
invocation logic out of `DoesNotLeak` into a new, non-inlineable helper
method, `CreateNavigationPageLeakReferencesAsync`, marked with
`[MethodImpl(MethodImplOptions.NoInlining)]`. This helper creates
`navPage` and `window`, drives the handler lifecycle, and returns only
the collected `WeakReference` list.
 
Since `navPage` and `window` now live in the helper's own async state
machine — which is discarded once the helper returns — they are no
longer reachable from `DoesNotLeak`'s state machine during the
subsequent `WaitForGC` call, eliminating the artificial rooting.

Validated the behavior in the following platforms
 
- [x] iOS
- [x] Mac
- [x] Android
- [x] Windows

### Regression PR

PR #35487
 
### Issues Fixed
  
Fixes #36613

### Output  Screenshot

### Issue1: Window Does Not Leak 

|Platform|Before|After|
|--|--|--|
|Android| <video
src="https://github.com/user-attachments/assets/1d3986aa-5c5f-4d97-ab6e-96c586e53488"
>| <video
src="https://github.com/user-attachments/assets/3670bafa-6a75-47a8-8505-797901e7abeb">|
|Mac|<video
src="https://github.com/user-attachments/assets/461534f8-21dd-46ab-bb62-c10a5f8ac71a">
|<video
src="https://github.com/user-attachments/assets/d862eb7f-c33f-4866-a553-5264b1cda411">|
|iOS|<video
src="https://github.com/user-attachments/assets/41b71c49-26ac-4dcc-9e01-87dce42d5000">|<video
src="https://github.com/user-attachments/assets/9e03f7ca-d803-49b9-a159-4057320591a7">|
|Windows|<video
src="https://github.com/user-attachments/assets/73300a73-a9be-403b-b77e-2cc4418d10c9">|<video
src="https://github.com/user-attachments/assets/173cf2e3-5bde-4383-b07a-0b6b8422d03b">
|

### Issue2: TabbedPageTests.DoesNotLeak

|Platform|Before|After|
|--|--|--|
|Android| <video
src="https://github.com/user-attachments/assets/604316e5-5849-4195-9e16-1c96d710c125"
>| <video
src="https://github.com/user-attachments/assets/50bc614c-814d-43d1-912b-446886086886">|

### Issue3: NavigationPageTests.DoesNotLeak

|Platform|Before|After|
|--|--|--|
|Mac|<video
src="https://github.com/user-attachments/assets/cd6831a8-e8f6-4954-baff-055a2575a576">
|<video
src="https://github.com/user-attachments/assets/6198e780-82e9-4eec-b3f5-a805f79d0ddd">|
|iOS|<video
src="https://github.com/user-attachments/assets/47edefd0-a416-4245-bbce-3e54c80aefa0">|<video
src="https://github.com/user-attachments/assets/84f2c31c-0d9d-4c3e-9f21-9a8f634e671f">|
kubaflo pushed a commit that referenced this pull request Sep 9, 2026
…eak Device Test (#37310)

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


<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Issue Details

Device memory leak tests started failing in the Candidate branch after
PR #35487, indicating regressions in
memory leak validation across Windows, iOS, macOS, and Android. The
affected Does Not Leak and Window Does Not Leak tests were failing on
these platforms.

### Issue1: Window Does Not Leak 

### Root cause

The WindowDoesNotLeak test failed intermittently because window and page
were declared as locals inside an async Task method ( WindowDoesNotLeak
) and were referenced across await boundaries (both directly and inside
the lambda passed to CreateHandlerAndAddToWindow ). The C# compiler
hoists such locals into fields of the generated async state machine, and
those fields are not guaranteed to be cleared once the locals are no
longer needed. As a result, window and page remained artificially rooted
by the state machine instance for the entire duration of the subsequent
WaitForGC call, producing a false-positive "still alive" leak report
rather than reflecting an actual product defect.

### Solution description

The fix extracts the window/page creation and handler invocation logic
out of WindowDoesNotLeak into a new, non-inlineable helper method,
CreateWindowLeakReferencesAsync , marked with
[MethodImpl(MethodImplOptions.NoInlining)] . This helper creates window
and page , drives the handler lifecycle, and returns only the collected
WeakReference list. Since window and page now live in the helper's own
async state machine — which is discarded once the helper returns — they
are no longer reachable from WindowDoesNotLeak 's state machine during
the subsequent WaitForGC call, eliminating the artificial rooting. The
dead conditional compilation guard ( #if TEST_FAILS_ON_ANDROID &&
TESTS_FAILS_ON_WINDOWS && TESTS_FAILS_ON_IOS &&
TESTS_FAILS_ON_MACCATALYST ) that had disabled the test was also removed
to re-enable it.

### Issue2: TabbedPageTests.DoesNotLeak

### Root cause

The issue occurs because of two compounding factors. At the test level,
the navPage local was captured by an async lambda and accessed again
after an await , causing it to be hoisted into the compiler-generated
closure and transitively keep the popped TabbedPage alive through its
navigation stack. At the platform level on Android,
MultiPageFragmentStateAdapter was constructed using the host Activity's
long-lived Lifecycle , causing AndroidX to permanently register a
lifecycle observer that was never released because the Activity's
lifecycle never reached the destroyed state. This kept the adapter, and
the TabbedPage it referenced, permanently rooted in memory, while
AndroidX also failed to reclaim the associated child fragments.

### Solution description

The fix involves nulling the navPage local before the WaitForGC call at
the test level, combined with a production-level Android fix in
MultiPageFragmentStateAdapter.cs that introduces a teardown routine to
make AndroidX reclaim its fragments correctly and explicitly clears the
adapter's page reference on disposal. Supporting changes in
TabbedPageManager.cs and TabbedPage.Android.cs ensure the teardown
routine executes before the adapter is detached and that manager
references are cleared on disconnect. The resolution was verified
through repeated on-device Android test runs, all passing successfully.

### Issue3: NavigationPageTests.DoesNotLeak

### Root Cause
 
The issue occurs because of the `navPage` and `window` locals in
`NavigationPageTests.DoesNotLeak` being referenced across an `await`
boundary — both directly and inside the lambda passed to
`CreateHandlerAndAddToWindow`. The C# compiler hoists such locals into
fields of the generated async state machine for the test method, and
those fields are not guaranteed to be cleared once the locals are no
longer needed. As a result, `navPage` and `window` remained artificially
rooted by the state machine instance for the duration of the subsequent
`WaitForGC` call, producing a false-positive "still alive" leak report
rather than reflecting an actual product defect.
 
This issue was only replicated in Release mode, since Release-mode
JIT/compiler optimizations affect how and when the hoisted state-machine
fields are cleared, whereas Debug builds happened to clear or avoid
rooting them, masking the problem locally.
 
### Solution Description
 
The fix involves extracting the `navPage`/`window` creation and handler
invocation logic out of `DoesNotLeak` into a new, non-inlineable helper
method, `CreateNavigationPageLeakReferencesAsync`, marked with
`[MethodImpl(MethodImplOptions.NoInlining)]`. This helper creates
`navPage` and `window`, drives the handler lifecycle, and returns only
the collected `WeakReference` list.
 
Since `navPage` and `window` now live in the helper's own async state
machine — which is discarded once the helper returns — they are no
longer reachable from `DoesNotLeak`'s state machine during the
subsequent `WaitForGC` call, eliminating the artificial rooting.

Validated the behavior in the following platforms
 
- [x] iOS
- [x] Mac
- [x] Android
- [x] Windows

### Regression PR

PR #35487
 
### Issues Fixed
  
Fixes #36613

### Output  Screenshot

### Issue1: Window Does Not Leak 

|Platform|Before|After|
|--|--|--|
|Android| <video
src="https://github.com/user-attachments/assets/1d3986aa-5c5f-4d97-ab6e-96c586e53488"
>| <video
src="https://github.com/user-attachments/assets/3670bafa-6a75-47a8-8505-797901e7abeb">|
|Mac|<video
src="https://github.com/user-attachments/assets/461534f8-21dd-46ab-bb62-c10a5f8ac71a">
|<video
src="https://github.com/user-attachments/assets/d862eb7f-c33f-4866-a553-5264b1cda411">|
|iOS|<video
src="https://github.com/user-attachments/assets/41b71c49-26ac-4dcc-9e01-87dce42d5000">|<video
src="https://github.com/user-attachments/assets/9e03f7ca-d803-49b9-a159-4057320591a7">|
|Windows|<video
src="https://github.com/user-attachments/assets/73300a73-a9be-403b-b77e-2cc4418d10c9">|<video
src="https://github.com/user-attachments/assets/173cf2e3-5bde-4383-b07a-0b6b8422d03b">
|

### Issue2: TabbedPageTests.DoesNotLeak

|Platform|Before|After|
|--|--|--|
|Android| <video
src="https://github.com/user-attachments/assets/604316e5-5849-4195-9e16-1c96d710c125"
>| <video
src="https://github.com/user-attachments/assets/50bc614c-814d-43d1-912b-446886086886">|

### Issue3: NavigationPageTests.DoesNotLeak

|Platform|Before|After|
|--|--|--|
|Mac|<video
src="https://github.com/user-attachments/assets/cd6831a8-e8f6-4954-baff-055a2575a576">
|<video
src="https://github.com/user-attachments/assets/6198e780-82e9-4eec-b3f5-a805f79d0ddd">|
|iOS|<video
src="https://github.com/user-attachments/assets/47edefd0-a416-4245-bbce-3e54c80aefa0">|<video
src="https://github.com/user-attachments/assets/84f2c31c-0d9d-4c3e-9f21-9a8f634e671f">|
kubaflo pushed a commit that referenced this pull request Sep 11, 2026
…eak Device Test (#37310)

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


<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Issue Details

Device memory leak tests started failing in the Candidate branch after
PR #35487, indicating regressions in
memory leak validation across Windows, iOS, macOS, and Android. The
affected Does Not Leak and Window Does Not Leak tests were failing on
these platforms.

### Issue1: Window Does Not Leak 

### Root cause

The WindowDoesNotLeak test failed intermittently because window and page
were declared as locals inside an async Task method ( WindowDoesNotLeak
) and were referenced across await boundaries (both directly and inside
the lambda passed to CreateHandlerAndAddToWindow ). The C# compiler
hoists such locals into fields of the generated async state machine, and
those fields are not guaranteed to be cleared once the locals are no
longer needed. As a result, window and page remained artificially rooted
by the state machine instance for the entire duration of the subsequent
WaitForGC call, producing a false-positive "still alive" leak report
rather than reflecting an actual product defect.

### Solution description

The fix extracts the window/page creation and handler invocation logic
out of WindowDoesNotLeak into a new, non-inlineable helper method,
CreateWindowLeakReferencesAsync , marked with
[MethodImpl(MethodImplOptions.NoInlining)] . This helper creates window
and page , drives the handler lifecycle, and returns only the collected
WeakReference list. Since window and page now live in the helper's own
async state machine — which is discarded once the helper returns — they
are no longer reachable from WindowDoesNotLeak 's state machine during
the subsequent WaitForGC call, eliminating the artificial rooting. The
dead conditional compilation guard ( #if TEST_FAILS_ON_ANDROID &&
TESTS_FAILS_ON_WINDOWS && TESTS_FAILS_ON_IOS &&
TESTS_FAILS_ON_MACCATALYST ) that had disabled the test was also removed
to re-enable it.

### Issue2: TabbedPageTests.DoesNotLeak

### Root cause

The issue occurs because of two compounding factors. At the test level,
the navPage local was captured by an async lambda and accessed again
after an await , causing it to be hoisted into the compiler-generated
closure and transitively keep the popped TabbedPage alive through its
navigation stack. At the platform level on Android,
MultiPageFragmentStateAdapter was constructed using the host Activity's
long-lived Lifecycle , causing AndroidX to permanently register a
lifecycle observer that was never released because the Activity's
lifecycle never reached the destroyed state. This kept the adapter, and
the TabbedPage it referenced, permanently rooted in memory, while
AndroidX also failed to reclaim the associated child fragments.

### Solution description

The fix involves nulling the navPage local before the WaitForGC call at
the test level, combined with a production-level Android fix in
MultiPageFragmentStateAdapter.cs that introduces a teardown routine to
make AndroidX reclaim its fragments correctly and explicitly clears the
adapter's page reference on disposal. Supporting changes in
TabbedPageManager.cs and TabbedPage.Android.cs ensure the teardown
routine executes before the adapter is detached and that manager
references are cleared on disconnect. The resolution was verified
through repeated on-device Android test runs, all passing successfully.

### Issue3: NavigationPageTests.DoesNotLeak

### Root Cause
 
The issue occurs because of the `navPage` and `window` locals in
`NavigationPageTests.DoesNotLeak` being referenced across an `await`
boundary — both directly and inside the lambda passed to
`CreateHandlerAndAddToWindow`. The C# compiler hoists such locals into
fields of the generated async state machine for the test method, and
those fields are not guaranteed to be cleared once the locals are no
longer needed. As a result, `navPage` and `window` remained artificially
rooted by the state machine instance for the duration of the subsequent
`WaitForGC` call, producing a false-positive "still alive" leak report
rather than reflecting an actual product defect.
 
This issue was only replicated in Release mode, since Release-mode
JIT/compiler optimizations affect how and when the hoisted state-machine
fields are cleared, whereas Debug builds happened to clear or avoid
rooting them, masking the problem locally.
 
### Solution Description
 
The fix involves extracting the `navPage`/`window` creation and handler
invocation logic out of `DoesNotLeak` into a new, non-inlineable helper
method, `CreateNavigationPageLeakReferencesAsync`, marked with
`[MethodImpl(MethodImplOptions.NoInlining)]`. This helper creates
`navPage` and `window`, drives the handler lifecycle, and returns only
the collected `WeakReference` list.
 
Since `navPage` and `window` now live in the helper's own async state
machine — which is discarded once the helper returns — they are no
longer reachable from `DoesNotLeak`'s state machine during the
subsequent `WaitForGC` call, eliminating the artificial rooting.

Validated the behavior in the following platforms
 
- [x] iOS
- [x] Mac
- [x] Android
- [x] Windows

### Regression PR

PR #35487
 
### Issues Fixed
  
Fixes #36613

### Output  Screenshot

### Issue1: Window Does Not Leak 

|Platform|Before|After|
|--|--|--|
|Android| <video
src="https://github.com/user-attachments/assets/1d3986aa-5c5f-4d97-ab6e-96c586e53488"
>| <video
src="https://github.com/user-attachments/assets/3670bafa-6a75-47a8-8505-797901e7abeb">|
|Mac|<video
src="https://github.com/user-attachments/assets/461534f8-21dd-46ab-bb62-c10a5f8ac71a">
|<video
src="https://github.com/user-attachments/assets/d862eb7f-c33f-4866-a553-5264b1cda411">|
|iOS|<video
src="https://github.com/user-attachments/assets/41b71c49-26ac-4dcc-9e01-87dce42d5000">|<video
src="https://github.com/user-attachments/assets/9e03f7ca-d803-49b9-a159-4057320591a7">|
|Windows|<video
src="https://github.com/user-attachments/assets/73300a73-a9be-403b-b77e-2cc4418d10c9">|<video
src="https://github.com/user-attachments/assets/173cf2e3-5bde-4383-b07a-0b6b8422d03b">
|

### Issue2: TabbedPageTests.DoesNotLeak

|Platform|Before|After|
|--|--|--|
|Android| <video
src="https://github.com/user-attachments/assets/604316e5-5849-4195-9e16-1c96d710c125"
>| <video
src="https://github.com/user-attachments/assets/50bc614c-814d-43d1-912b-446886086886">|

### Issue3: NavigationPageTests.DoesNotLeak

|Platform|Before|After|
|--|--|--|
|Mac|<video
src="https://github.com/user-attachments/assets/cd6831a8-e8f6-4954-baff-055a2575a576">
|<video
src="https://github.com/user-attachments/assets/6198e780-82e9-4eec-b3f5-a805f79d0ddd">|
|iOS|<video
src="https://github.com/user-attachments/assets/47edefd0-a416-4245-bbce-3e54c80aefa0">|<video
src="https://github.com/user-attachments/assets/84f2c31c-0d9d-4c3e-9f21-9a8f634e671f">|
kubaflo pushed a commit that referenced this pull request Sep 15, 2026
…eak Device Test (#37310)

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


<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Issue Details

Device memory leak tests started failing in the Candidate branch after
PR #35487, indicating regressions in
memory leak validation across Windows, iOS, macOS, and Android. The
affected Does Not Leak and Window Does Not Leak tests were failing on
these platforms.

### Issue1: Window Does Not Leak 

### Root cause

The WindowDoesNotLeak test failed intermittently because window and page
were declared as locals inside an async Task method ( WindowDoesNotLeak
) and were referenced across await boundaries (both directly and inside
the lambda passed to CreateHandlerAndAddToWindow ). The C# compiler
hoists such locals into fields of the generated async state machine, and
those fields are not guaranteed to be cleared once the locals are no
longer needed. As a result, window and page remained artificially rooted
by the state machine instance for the entire duration of the subsequent
WaitForGC call, producing a false-positive "still alive" leak report
rather than reflecting an actual product defect.

### Solution description

The fix extracts the window/page creation and handler invocation logic
out of WindowDoesNotLeak into a new, non-inlineable helper method,
CreateWindowLeakReferencesAsync , marked with
[MethodImpl(MethodImplOptions.NoInlining)] . This helper creates window
and page , drives the handler lifecycle, and returns only the collected
WeakReference list. Since window and page now live in the helper's own
async state machine — which is discarded once the helper returns — they
are no longer reachable from WindowDoesNotLeak 's state machine during
the subsequent WaitForGC call, eliminating the artificial rooting. The
dead conditional compilation guard ( #if TEST_FAILS_ON_ANDROID &&
TESTS_FAILS_ON_WINDOWS && TESTS_FAILS_ON_IOS &&
TESTS_FAILS_ON_MACCATALYST ) that had disabled the test was also removed
to re-enable it.

### Issue2: TabbedPageTests.DoesNotLeak

### Root cause

The issue occurs because of two compounding factors. At the test level,
the navPage local was captured by an async lambda and accessed again
after an await , causing it to be hoisted into the compiler-generated
closure and transitively keep the popped TabbedPage alive through its
navigation stack. At the platform level on Android,
MultiPageFragmentStateAdapter was constructed using the host Activity's
long-lived Lifecycle , causing AndroidX to permanently register a
lifecycle observer that was never released because the Activity's
lifecycle never reached the destroyed state. This kept the adapter, and
the TabbedPage it referenced, permanently rooted in memory, while
AndroidX also failed to reclaim the associated child fragments.

### Solution description

The fix involves nulling the navPage local before the WaitForGC call at
the test level, combined with a production-level Android fix in
MultiPageFragmentStateAdapter.cs that introduces a teardown routine to
make AndroidX reclaim its fragments correctly and explicitly clears the
adapter's page reference on disposal. Supporting changes in
TabbedPageManager.cs and TabbedPage.Android.cs ensure the teardown
routine executes before the adapter is detached and that manager
references are cleared on disconnect. The resolution was verified
through repeated on-device Android test runs, all passing successfully.

### Issue3: NavigationPageTests.DoesNotLeak

### Root Cause
 
The issue occurs because of the `navPage` and `window` locals in
`NavigationPageTests.DoesNotLeak` being referenced across an `await`
boundary — both directly and inside the lambda passed to
`CreateHandlerAndAddToWindow`. The C# compiler hoists such locals into
fields of the generated async state machine for the test method, and
those fields are not guaranteed to be cleared once the locals are no
longer needed. As a result, `navPage` and `window` remained artificially
rooted by the state machine instance for the duration of the subsequent
`WaitForGC` call, producing a false-positive "still alive" leak report
rather than reflecting an actual product defect.
 
This issue was only replicated in Release mode, since Release-mode
JIT/compiler optimizations affect how and when the hoisted state-machine
fields are cleared, whereas Debug builds happened to clear or avoid
rooting them, masking the problem locally.
 
### Solution Description
 
The fix involves extracting the `navPage`/`window` creation and handler
invocation logic out of `DoesNotLeak` into a new, non-inlineable helper
method, `CreateNavigationPageLeakReferencesAsync`, marked with
`[MethodImpl(MethodImplOptions.NoInlining)]`. This helper creates
`navPage` and `window`, drives the handler lifecycle, and returns only
the collected `WeakReference` list.
 
Since `navPage` and `window` now live in the helper's own async state
machine — which is discarded once the helper returns — they are no
longer reachable from `DoesNotLeak`'s state machine during the
subsequent `WaitForGC` call, eliminating the artificial rooting.

Validated the behavior in the following platforms
 
- [x] iOS
- [x] Mac
- [x] Android
- [x] Windows

### Regression PR

PR #35487
 
### Issues Fixed
  
Fixes #36613

### Output  Screenshot

### Issue1: Window Does Not Leak 

|Platform|Before|After|
|--|--|--|
|Android| <video
src="https://github.com/user-attachments/assets/1d3986aa-5c5f-4d97-ab6e-96c586e53488"
>| <video
src="https://github.com/user-attachments/assets/3670bafa-6a75-47a8-8505-797901e7abeb">|
|Mac|<video
src="https://github.com/user-attachments/assets/461534f8-21dd-46ab-bb62-c10a5f8ac71a">
|<video
src="https://github.com/user-attachments/assets/d862eb7f-c33f-4866-a553-5264b1cda411">|
|iOS|<video
src="https://github.com/user-attachments/assets/41b71c49-26ac-4dcc-9e01-87dce42d5000">|<video
src="https://github.com/user-attachments/assets/9e03f7ca-d803-49b9-a159-4057320591a7">|
|Windows|<video
src="https://github.com/user-attachments/assets/73300a73-a9be-403b-b77e-2cc4418d10c9">|<video
src="https://github.com/user-attachments/assets/173cf2e3-5bde-4383-b07a-0b6b8422d03b">
|

### Issue2: TabbedPageTests.DoesNotLeak

|Platform|Before|After|
|--|--|--|
|Android| <video
src="https://github.com/user-attachments/assets/604316e5-5849-4195-9e16-1c96d710c125"
>| <video
src="https://github.com/user-attachments/assets/50bc614c-814d-43d1-912b-446886086886">|

### Issue3: NavigationPageTests.DoesNotLeak

|Platform|Before|After|
|--|--|--|
|Mac|<video
src="https://github.com/user-attachments/assets/cd6831a8-e8f6-4954-baff-055a2575a576">
|<video
src="https://github.com/user-attachments/assets/6198e780-82e9-4eec-b3f5-a805f79d0ddd">|
|iOS|<video
src="https://github.com/user-attachments/assets/47edefd0-a416-4245-bbce-3e54c80aefa0">|<video
src="https://github.com/user-attachments/assets/84f2c31c-0d9d-4c3e-9f21-9a8f634e671f">|
@github-actions github-actions Bot locked and limited conversation to collaborators Sep 18, 2026
@github-actions github-actions Bot modified the milestones: .NET 10 SR11, .NET 10 SR12 Oct 21, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

community ✨ Community Contribution partner/syncfusion Issues / PR's with Syncfusion collaboration 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.

[Testing] Re-enable Window Memory Leak Device Test for June 08 Candidate Branch

5 participants