Repository navigation
[leak-fix] Fix BackButtonBehavior.Command memory leak (Fixes #36345) - #36370
Conversation
Route the BackButtonBehavior ICommand.CanExecuteChanged subscription through the existing WeakCommandSubscription helper (DependentHandle-based) so the command no longer roots the BackButtonBehavior via a strong event delegate. Dispose the prior subscription when the command changes. Adds two rows to the Controls.Core.UnitTests CommandsSubscribedToCanExecuteCollect theory that fail without this fix. Generated by the Memory Leak Fixer agentic workflow (dotnet/maui). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Pull request overview
Fixes a managed memory leak in Microsoft.Maui.Controls.BackButtonBehavior.Command by switching the ICommand.CanExecuteChanged subscription from a strong event handler to the existing weak-subscription helper used elsewhere in Controls. This prevents long-lived commands (e.g., shared view-model commands) from rooting BackButtonBehavior instances after the behavior is no longer referenced.
Changes:
- Replace the strong
CanExecuteChangedsubscription inBackButtonBehaviorwithWeakCommandSubscriptionand dispose the previous subscription on command changes. - Extend the existing command collection regression test matrix to cover
BackButtonBehaviorfor both weak-event and strong-eventICommandimplementations.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.
| File | Description |
|---|---|
| src/Controls/src/Core/Shell/BackButtonBehavior.cs | Switches command CanExecuteChanged hookup to WeakCommandSubscription to avoid rooting the behavior via strong event handlers. |
| src/Controls/tests/Core.UnitTests/CommandTests.cs | Adds BackButtonBehavior to the existing leak-regression theory to validate collection with strong-event commands. |
This comment has been minimized.
This comment has been minimized.
|
🤖 Automated update from the Memory Leak Fixer workflow (Track C — review response). This comment and the commit just pushed to this branch were generated by an AI agent. Thanks for the review — I applied the suggested refactor. AppliedRouted
Net diff: 1 file, +7 / −41 ( No test change needed (the test got stronger for free)
Empirical re-validation this run (red → green)Built MAUI from source and ran the theory on the
So the regression coverage stays intact and the leak remains fixed via the idiomatic shared path. /review rerun
|
This comment has been minimized.
This comment has been minimized.
MauiBot
left a comment
There was a problem hiding this comment.
AI Review Summary
@github-actions[bot] — new AI review results are available based on this last commit:
7748750. To request a fresh review after new comments or commits, comment/review rerun.
🗂️ Review Sessions — click to expand
🚦 Gate — Test Before & After Fix
Gate Result: ✅ PASSED
Platform: ANDROID · Base: main · Merge base: 5535b43c
| Test | Without Fix (expect FAIL) | With Fix (expect PASS) |
|---|---|---|
🧪 CommandTests CommandTests |
✅ FAIL — 169s | ✅ PASS — 130s |
🔴 Without fix — 🧪 CommandTests: FAIL ✅ · 169s
Determining projects to restore...
Restored /home/vsts/work/1/s/src/TestUtils/src/TestUtils/TestUtils.csproj (in 4.16 sec).
Restored /home/vsts/work/1/s/src/Graphics/src/Graphics/Graphics.csproj (in 195 ms).
Restored /home/vsts/work/1/s/src/Essentials/src/Essentials.csproj (in 2.99 sec).
Restored /home/vsts/work/1/s/src/Core/src/Core.csproj (in 889 ms).
Restored /home/vsts/work/1/s/src/Core/maps/src/Maps.csproj (in 9.4 sec).
Restored /home/vsts/work/1/s/src/Controls/src/Xaml/Controls.Xaml.csproj (in 72 ms).
Restored /home/vsts/work/1/s/src/Controls/src/Core/Controls.Core.csproj (in 73 ms).
Restored /home/vsts/work/1/s/src/Controls/Maps/src/Controls.Maps.csproj (in 71 ms).
Restored /home/vsts/work/1/s/src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj (in 2.14 sec).
1 of 10 projects are up-to-date for restore.
##vso[build.updatebuildnumber]10.0.90-ci+azdo.14610779
Graphics -> /home/vsts/work/1/s/artifacts/bin/Graphics/Debug/net10.0/Microsoft.Maui.Graphics.dll
##vso[build.updatebuildnumber]10.0.90-ci+azdo.14610779
Essentials -> /home/vsts/work/1/s/artifacts/bin/Essentials/Debug/net10.0/Microsoft.Maui.Essentials.dll
##vso[build.updatebuildnumber]10.0.90-ci+azdo.14610779
Core -> /home/vsts/work/1/s/artifacts/bin/Core/Debug/net10.0/Microsoft.Maui.dll
##vso[build.updatebuildnumber]10.0.90-ci+azdo.14610779
Maps -> /home/vsts/work/1/s/artifacts/bin/Maps/Debug/net10.0/Microsoft.Maui.Maps.dll
Controls.BindingSourceGen -> /home/vsts/work/1/s/artifacts/bin/Controls.BindingSourceGen/Debug/netstandard2.0/Microsoft.Maui.Controls.BindingSourceGen.dll
##vso[build.updatebuildnumber]10.0.90-ci+azdo.14610779
Controls.Core -> /home/vsts/work/1/s/artifacts/bin/Controls.Core/Debug/net10.0/Microsoft.Maui.Controls.dll
##vso[build.updatebuildnumber]10.0.90-ci+azdo.14610779
Controls.Xaml -> /home/vsts/work/1/s/artifacts/bin/Controls.Xaml/Debug/net10.0/Microsoft.Maui.Controls.Xaml.dll
##vso[build.updatebuildnumber]10.0.90-ci+azdo.14610779
Controls.Maps -> /home/vsts/work/1/s/artifacts/bin/Controls.Maps/Debug/net10.0/Microsoft.Maui.Controls.Maps.dll
TestUtils -> /home/vsts/work/1/s/artifacts/bin/TestUtils/Debug/netstandard2.0/Microsoft.Maui.TestUtils.dll
Controls.Core.UnitTests -> /home/vsts/work/1/s/artifacts/bin/Controls.Core.UnitTests/Debug/net10.0/Microsoft.Maui.Controls.Core.UnitTests.dll
Test run for /home/vsts/work/1/s/artifacts/bin/Controls.Core.UnitTests/Debug/net10.0/Microsoft.Maui.Controls.Core.UnitTests.dll (.NETCoreApp,Version=v10.0)
VSTest version 18.0.1 (x64)
Starting test execution, please wait...
A total of 1 test files matched the specified pattern.
[xUnit.net 00:00:00.00] xUnit.net VSTest Adapter v2.8.2+699d445a1a (64-bit .NET 10.0.0)
[xUnit.net 00:00:00.24] Discovering: Microsoft.Maui.Controls.Core.UnitTests
[xUnit.net 00:00:02.29] Discovered: Microsoft.Maui.Controls.Core.UnitTests
[xUnit.net 00:00:02.32] Starting: Microsoft.Maui.Controls.Core.UnitTests
Passed CanExecuteReturnsFalseIfParameterIsWrongValueType [15 ms]
Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.SearchBar), useWeakEventHandler: False) [141 ms]
Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.MenuItem), useWeakEventHandler: True) [88 ms]
Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.ImageButton), useWeakEventHandler: False) [175 ms]
Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.Button), useWeakEventHandler: False) [178 ms]
[xUnit.net 00:00:04.33] Assert.False() Failure
[xUnit.net 00:00:04.33] Expected: False
[xUnit.net 00:00:04.33] Actual: True
[xUnit.net 00:00:04.33] CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.BackButtonBehavior), useWeakEventHandler: False) [FAIL]
[xUnit.net 00:00:04.40] Stack Trace:
[xUnit.net 00:00:04.40] /_/src/Controls/tests/Core.UnitTests/CommandTests.cs(354,0): at Microsoft.Maui.Controls.Core.UnitTests.CommandTests.CommandsSubscribedToCanExecuteCollect(Type controlType, Boolean useWeakEventHandler)
[xUnit.net 00:00:04.40] --- End of stack trace from previous location ---
Failed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.BackButtonBehavior), useWeakEventHandler: False) [1 s]
Error Message:
Assert.False() Failure
Expected: False
Actual: True
Stack Trace:
at Microsoft.Maui.Controls.Core.UnitTests.CommandTests.CommandsSubscribedToCanExecuteCollect(Type controlType, Boolean useWeakEventHandler) in /_/src/Controls/tests/Core.UnitTests/CommandTests.cs:line 354
--- End of stack trace from previous location ---
Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.ImageButton), useWeakEventHandler: True) [139 ms]
Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.BackButtonBehavior), useWeakEventHandler: True) [83 ms]
Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.RefreshView), useWeakEventHandler: False) [114 ms]
Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.TextCell), useWeakEventHandler: False) [152 ms]
Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.SearchHandler), useWeakEventHandler: True) [86 ms]
Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.MenuItem), useWeakEventHandler: False) [58 ms]
Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.RefreshView), useWeakEventHandler: True) [60 ms]
Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.TextCell), useWeakEventHandler: True) [198 ms]
Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.Button), useWeakEventHandler: True) [171 ms]
Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.SearchBar), useWeakEventHandler: True) [84 ms]
Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.SearchHandler), useWeakEventHandler: False) [85 ms]
Passed ExecuteDoesNotRunIfParameterIsWrongReferenceType [1 ms]
Passed ExecuteRunsIfReferenceTypeAndSetToNull [< 1 ms]
Passed CanExecuteIgnoresParameterIfValueTypeAndSetToNull [< 1 ms]
Passed CanExecute(expected: True) [5 ms]
Passed CanExecute(expected: False) [< 1 ms]
Passed GenericExecuteWithCanExecute [1 ms]
Passed GenericThrowsWithNullExecute [< 1 ms]
Passed Execute [< 1 ms]
Passed GenericCanExecute(expected: True) [< 1 ms]
Passed GenericCanExecute(expected: False) [< 1 ms]
Passed ThrowsWithNullConstructor [< 1 ms]
Passed ExecuteDoesNotRunIfParameterIsWrongValueType [1 ms]
Passed GenericThrowsWithNullExecuteAndCanExecuteValid [< 1 ms]
Passed ThrowsWithNullExecuteValidCanExecute [< 1 ms]
Passed CanExecuteUsesParameterIfReferenceTypeAndSetToNull [< 1 ms]
Passed ChangeCanExecute [< 1 ms]
Passed GenericExecute [< 1 ms]
Passed ThrowsWithNullCanExecute [< 1 ms]
Passed ThrowsWithNullParameterizedConstructor [< 1 ms]
Passed CanExecuteUsesParameterIfNullableAndSetToNull [2 ms]
Passed ExecuteDoesNotRunIfValueTypeAndSetToNull [< 1 ms]
Passed Constructor [< 1 ms]
Passed ThrowsWithNullParameterizedCanExecute [< 1 ms]
Passed ExecuteRunsIfNullableAndSetToNull [< 1 ms]
[xUnit.net 00:00:05.63] Finished: Microsoft.Maui.Controls.Core.UnitTests
Passed ExecuteParameterized [5 ms]
Passed GenericThrowsWithValidExecuteAndCanExecuteNull [< 1 ms]
Passed ExecuteWithCanExecute [< 1 ms]
Passed CanExecuteReturnsFalseIfParameterIsWrongReferenceType [< 1 ms]
Test Run Failed.
Total tests: 45
Passed: 44
Failed: 1
Total time: 6.3678 Seconds
🟢 With fix — 🧪 CommandTests: PASS ✅ · 130s
Determining projects to restore...
All projects are up-to-date for restore.
##vso[build.updatebuildnumber]10.0.90-ci+azdo.14610779
Graphics -> /home/vsts/work/1/s/artifacts/bin/Graphics/Debug/net10.0/Microsoft.Maui.Graphics.dll
##vso[build.updatebuildnumber]10.0.90-ci+azdo.14610779
Essentials -> /home/vsts/work/1/s/artifacts/bin/Essentials/Debug/net10.0/Microsoft.Maui.Essentials.dll
##vso[build.updatebuildnumber]10.0.90-ci+azdo.14610779
Core -> /home/vsts/work/1/s/artifacts/bin/Core/Debug/net10.0/Microsoft.Maui.dll
##vso[build.updatebuildnumber]10.0.90-ci+azdo.14610779
Maps -> /home/vsts/work/1/s/artifacts/bin/Maps/Debug/net10.0/Microsoft.Maui.Maps.dll
Controls.BindingSourceGen -> /home/vsts/work/1/s/artifacts/bin/Controls.BindingSourceGen/Debug/netstandard2.0/Microsoft.Maui.Controls.BindingSourceGen.dll
##vso[build.updatebuildnumber]10.0.90-ci+azdo.14610779
Controls.Core -> /home/vsts/work/1/s/artifacts/bin/Controls.Core/Debug/net10.0/Microsoft.Maui.Controls.dll
##vso[build.updatebuildnumber]10.0.90-ci+azdo.14610779
Controls.Xaml -> /home/vsts/work/1/s/artifacts/bin/Controls.Xaml/Debug/net10.0/Microsoft.Maui.Controls.Xaml.dll
##vso[build.updatebuildnumber]10.0.90-ci+azdo.14610779
Controls.Maps -> /home/vsts/work/1/s/artifacts/bin/Controls.Maps/Debug/net10.0/Microsoft.Maui.Controls.Maps.dll
TestUtils -> /home/vsts/work/1/s/artifacts/bin/TestUtils/Debug/netstandard2.0/Microsoft.Maui.TestUtils.dll
Controls.Core.UnitTests -> /home/vsts/work/1/s/artifacts/bin/Controls.Core.UnitTests/Debug/net10.0/Microsoft.Maui.Controls.Core.UnitTests.dll
Test run for /home/vsts/work/1/s/artifacts/bin/Controls.Core.UnitTests/Debug/net10.0/Microsoft.Maui.Controls.Core.UnitTests.dll (.NETCoreApp,Version=v10.0)
VSTest version 18.0.1 (x64)
Starting test execution, please wait...
A total of 1 test files matched the specified pattern.
[xUnit.net 00:00:00.00] xUnit.net VSTest Adapter v2.8.2+699d445a1a (64-bit .NET 10.0.0)
[xUnit.net 00:00:00.32] Discovering: Microsoft.Maui.Controls.Core.UnitTests
[xUnit.net 00:00:02.70] Discovered: Microsoft.Maui.Controls.Core.UnitTests
[xUnit.net 00:00:02.73] Starting: Microsoft.Maui.Controls.Core.UnitTests
Passed CanExecuteReturnsFalseIfParameterIsWrongValueType [14 ms]
Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.SearchBar), useWeakEventHandler: False) [168 ms]
Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.MenuItem), useWeakEventHandler: True) [183 ms]
Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.ImageButton), useWeakEventHandler: False) [83 ms]
Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.Button), useWeakEventHandler: False) [182 ms]
Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.BackButtonBehavior), useWeakEventHandler: False) [152 ms]
Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.ImageButton), useWeakEventHandler: True) [76 ms]
Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.BackButtonBehavior), useWeakEventHandler: True) [79 ms]
Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.RefreshView), useWeakEventHandler: False) [83 ms]
Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.TextCell), useWeakEventHandler: False) [96 ms]
Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.SearchHandler), useWeakEventHandler: True) [98 ms]
Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.MenuItem), useWeakEventHandler: False) [83 ms]
Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.RefreshView), useWeakEventHandler: True) [99 ms]
Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.TextCell), useWeakEventHandler: True) [212 ms]
Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.Button), useWeakEventHandler: True) [143 ms]
Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.SearchBar), useWeakEventHandler: True) [80 ms]
Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.SearchHandler), useWeakEventHandler: False) [84 ms]
Passed ExecuteDoesNotRunIfParameterIsWrongReferenceType [1 ms]
Passed ExecuteRunsIfReferenceTypeAndSetToNull [< 1 ms]
Passed CanExecuteIgnoresParameterIfValueTypeAndSetToNull [2 ms]
Passed CanExecute(expected: True) [7 ms]
Passed CanExecute(expected: False) [< 1 ms]
Passed GenericExecuteWithCanExecute [1 ms]
Passed GenericThrowsWithNullExecute [1 ms]
Passed Execute [< 1 ms]
Passed GenericCanExecute(expected: True) [< 1 ms]
Passed GenericCanExecute(expected: False) [< 1 ms]
Passed ThrowsWithNullConstructor [< 1 ms]
Passed ExecuteDoesNotRunIfParameterIsWrongValueType [< 1 ms]
Passed GenericThrowsWithNullExecuteAndCanExecuteValid [< 1 ms]
Passed ThrowsWithNullExecuteValidCanExecute [< 1 ms]
Passed CanExecuteUsesParameterIfReferenceTypeAndSetToNull [2 ms]
Passed ChangeCanExecute [< 1 ms]
Passed GenericExecute [< 1 ms]
Passed ThrowsWithNullCanExecute [< 1 ms]
Passed ThrowsWithNullParameterizedConstructor [< 1 ms]
[xUnit.net 00:00:04.83] Finished: Microsoft.Maui.Controls.Core.UnitTests
Passed CanExecuteUsesParameterIfNullableAndSetToNull [1 ms]
Passed ExecuteDoesNotRunIfValueTypeAndSetToNull [< 1 ms]
Passed Constructor [< 1 ms]
Passed ThrowsWithNullParameterizedCanExecute [< 1 ms]
Passed ExecuteRunsIfNullableAndSetToNull [3 ms]
Passed ExecuteParameterized [3 ms]
Passed GenericThrowsWithValidExecuteAndCanExecuteNull [< 1 ms]
Passed ExecuteWithCanExecute [< 1 ms]
Passed CanExecuteReturnsFalseIfParameterIsWrongReferenceType [< 1 ms]
Test Run Successful.
Total tests: 45
Passed: 45
Total time: 5.6239 Seconds
📁 Fix files reverted (1 files)
src/Controls/src/Core/Shell/BackButtonBehavior.cs
📱 UI Tests — Shell
Detected UI test categories: Shell
✅ Deep UI tests — 309 passed, 0 failed across 1 category on platform-pool agent (replaces in-process counts above).
🧪 UI Test Execution Results (deep, platform pool)
| Category | Tests | Snapshot diffs |
|---|---|---|
Shell |
309/309 ✓ | — |
📎 Download drop-deep-uitests artifact (TRX + snapshot diffs) |
📋 Pre-Flight — Context & Validation
Issue: #36345 - [leak-scan] Shell BackButtonBehavior.Command leaks via strong ICommand.CanExecuteChanged (no weak proxy, no detach teardown)
PR: #36370 - [leak-fix] Fix BackButtonBehavior.Command memory leak (Fixes #36345)
Platforms Affected: all managed platforms; testing requested for android, but the regression is covered by cross-platform Controls.Core unit tests.
Files Changed: 1 implementation, 1 test
Key Findings
BackButtonBehavior.Commandpreviously subscribed directly toICommand.CanExecuteChanged, so a long-lived command with a strong event retained the behavior after the page/behavior became otherwise unreachable.- The PR replaces the custom subscription code with shared
ICommandElement/CommandElementweak-subscription plumbing and extendsCommandsSubscribedToCanExecuteCollectto coverBackButtonBehavior. - Public GitHub context was available through the unauthenticated API/curl;
ghwas unavailable because no auth token is configured. - Prior comments include a MauiBot analysis saying the weak-event approach is consistent with other leak fixes and has low missed-unsubscription risk.
Code Review Summary
Verdict: NEEDS_CHANGES
Confidence: low
Errors: 1 | Warnings: 0 | Suggestions: 0
Key code review findings:
- [error]
src/Controls/src/Core/Shell/BackButtonBehavior.cs:16now routesCommandParameterchanges throughCommandElement.OnCommandParameterChanged, which can recalculateCanExecuteastruewhenCommandis null and potentially re-enable a disabled back button. The removed implementation only recalculated whenCommand != null.
Fix Candidates
| # | Source | Approach | Test Result | Files Changed | Notes |
|---|---|---|---|---|---|
| PR | PR #36370 | Reuse shared ICommandElement / CommandElement weak subscription for BackButtonBehavior.Command. |
PASSED (Gate) | src/Controls/src/Core/Shell/BackButtonBehavior.cs, src/Controls/tests/Core.UnitTests/CommandTests.cs |
Original PR; gate was already completed before this run. |
🔬 Code Review — Deep Analysis
Code Review — PR #36370
Independent Assessment
What this changes: BackButtonBehavior now reuses shared ICommandElement / CommandElement weak command subscription plumbing, and the command leak regression test now includes BackButtonBehavior.
Inferred motivation: Fix a memory leak where a long-lived ICommand.CanExecuteChanged event strongly retained BackButtonBehavior.
Reconciliation with PR Narrative
Author claims: The PR fixes BackButtonBehavior.Command retention using weak subscription while preserving IsEnabled / CanExecute behavior.
Agreement/disagreement: The leak motivation matches the code, but the narrative describes a direct WeakCommandSubscription field while the actual PR uses shared CommandElement behavior. That shared behavior changes the no-command CommandParameter path.
Prior Review Reconciliation
No prior ❌ Error findings found. Public PR review bodies, inline review comments, and issue comments were checked via the public GitHub API because gh is unauthenticated.
Blast Radius Assessment
- Runs for all instances: Yes — every
BackButtonBehaviornow routes command and command-parameter changes throughCommandElement. - Startup impact: No direct startup path, but Shell toolbar state can be affected during binding/context application.
- Static/shared state: No new static state.
CI Status
- Required-check result: undetermined —
gh pr checks --requiredfailed with auth required. - Classification: undetermined. Public Checks API fallback showed 29 completed successful check runs, but required-check status could not be verified through
gh. - Action taken: capped confidence low.
Findings
❌ Error — CommandParameter can re-enable a disabled back button when no command is set
src/Controls/src/Core/Shell/BackButtonBehavior.cs:16 now calls CommandElement.OnCommandParameterChanged for every CommandParameter change. Unlike the removed implementation, this path does not guard on Command != null; it calls ICommandElement.CanExecuteChanged, and CommandElement.GetCanExecute(this) returns true when Command is null.
That writes IsEnabledCore = true, which uses _userDefinedIsEnabled (BackButtonBehavior.cs:106-107). _userDefinedIsEnabled is only updated by the CLR IsEnabled setter (BackButtonBehavior.cs:77-80), while XAML/bindings commonly set the bindable property directly through SetValue / binding application. So a valid Shell scenario such as a XAML/bound BackButtonBehavior with IsEnabled=false, no Command, and a later-resolving CommandParameter binding can be re-enabled unintentionally.
Platform consumers use this property to decide whether the back button can act, e.g. Android checks GetPropertyIfSet(BackButtonBehavior.IsEnabledProperty, true) before navigating (ShellToolbarTracker.cs:162-170), and iOS updates the native back button from BackButtonBehavior.IsEnabled (ShellPageRendererTracker.cs:127-130).
⚠️ Warning
None.
💡 Suggestion
None.
Failure-Mode Probing
- Disabled back button with no command and late
CommandParameterbinding: regresses; parameter change recomputes can-execute astrueand may overwrite disabled state. - Command replacement/disposal: shared
CommandElementdisposes the old weak subscription on changing/changed paths, so the intended leak fix is sound. - Null command:
CommandElement.GetCanExecutesafely returnstrue, but that is exactly what makes the no-command parameter-change path unsafe here.
Verdict: NEEDS_CHANGES
Confidence: low (CI required status could not be verified, and this is Shell command/UI plumbing.)
Summary: The weak-subscription direction is reasonable, but the current shared CommandElement migration changes CommandParameter behavior when no command exists. This can re-enable a back button that app code disabled via XAML/binding, so the PR should preserve the old Command != null guard or otherwise avoid writing IsEnabled in that path.
🛠️ Fix — Analysis & Comparison
Fix Candidates
| # | Source | Approach | Test Result | Files Changed | Notes |
|---|---|---|---|---|---|
| 1 | try-fix-1 | Direct private WeakCommandSubscription in BackButtonBehavior, preserving local command/parameter semantics. |
PASS | 1 file | Passes regression filter and avoids the pre-flight concern in the PR's shared ICommandElement migration. |
| PR | PR #36370 | Migrate BackButtonBehavior to shared ICommandElement / CommandElement weak-command plumbing. |
PASSED (Gate) | 2 files | Original PR gate passed, but pre-flight review found a potential CommandParameter/null-command enablement regression. |
Cross-Pollination
| Model | Round | New Ideas? | Details |
|---|---|---|---|
| gpt-5.5 + maui-expert-reviewer | 1 | Yes | Try a direct WeakCommandSubscription field instead of adopting ICommandElement, so the leak is fixed without changing CommandParameter behavior when Command is null. |
Exhausted: No — stopped because candidate #1 passed all targeted regression tests and is demonstrably better than the PR fix on behavioral preservation.
Selected Fix: Candidate #1 — it fixes the same leak, passes the regression filter, and avoids the PR's potential no-command CommandParameter re-enable regression.
📝 Recommended PR Title & Description
Assessment: ✏️ Recommend updating — the current description is technically strong for the winning fix, but the title uses a workflow tag instead of the component-focused title format and the body includes automation metadata that should not become merge documentation.
Recommended title
Shell: Fix BackButtonBehavior.Command memory leak
Recommended description
Fixes #36345
Refs: dotnet/maui#36345
## The leak
`BackButtonBehavior` subscribed to `ICommand.CanExecuteChanged` with a strong delegate:
```csharp
newCommand.CanExecuteChanged += CanExecuteChanged;
Because an ICommand is commonly stored on a long-lived view model or otherwise shared/retained, that strong subscription keeps the BackButtonBehavior — and everything it transitively roots — alive for as long as the command lives. The only unsubscribe happened when the Command property itself changed, so a behavior whose command outlives it is never released.
Retention path from issue #36345:
ICommand (long-lived) -> CanExecuteChanged event -> BackButtonBehavior.CanExecuteChanged delegate -> BackButtonBehavior
The fix
Replace the strong event subscription with the existing WeakCommandSubscription helper while preserving BackButtonBehavior's existing local command semantics:
- Dispose the previous weak subscription whenever
Commandchanges. - Create a new
WeakCommandSubscriptionfor the new command. - Preserve the existing
CommandParameterbehavior: only recalculateCanExecutewhenCommand != null. - Preserve the existing no-command behavior:
IsEnabledCorereturns totruewhenCommandis cleared.
No public API change: the implementation adds only private/internal command-subscription plumbing.
Regression test
Extends CommandsSubscribedToCanExecuteCollect in src/Controls/tests/Core.UnitTests/CommandTests.cs with BackButtonBehavior rows for both weak-event and strong-event command variants. The strong-event variant (useWeakEventHandler: false) reproduces the leak.
Verified in the saved gate run for Controls.Core.UnitTests:
| State | BackButtonBehavior, false |
Result |
|---|---|---|
| Without fix | Assert.False() Failure — Expected: False, Actual: True (behavior still alive) |
FAIL |
| With fix | behavior collected | PASS |
Full CommandTests class after the fix: 45 passed, 0 failed.
Scope
- Managed, cross-platform Shell behavior only:
src/Controls/src/Core/Shell/BackButtonBehavior.cs. - Regression coverage:
src/Controls/tests/Core.UnitTests/CommandTests.cs. - Android was the requested test platform, but the fix is managed and covered by cross-platform unit tests.
- No test was muted, skipped, weakened, or marked with
[ActiveIssue]/Skip=.
</details>
---
<details>
<summary><strong>🏁 Report — Final Recommendation</strong></summary>
<br/>
# Comparative Report — PR #36370
## Candidate ranking
| Rank | Candidate | Regression result | Review result | Assessment |
| --- | --- | --- | --- | --- |
| 1 | `try-fix-1` | PASS — saved run: `CommandsSubscribedToCanExecuteCollect` 16/16 passed | No blocking expert findings in saved `try-fix-1` review | Best candidate. It fixes the leak with a private `WeakCommandSubscription` while preserving the original `BackButtonBehavior` `CommandParameter` guard and local semantics. |
| 2 | `pr-plus-reviewer` | Not re-run in sandbox: detached worktree lacked restored assets (`NETSDK1004`) | Addresses the expert reviewer's blocker | Viable PR-based repair. It keeps shared `ICommandElement` plumbing but restores the old null-command parameter behavior. Ranked below `try-fix-1` because it is broader and lacks an empirical sandbox test result. |
| 3 | `pr` | PASSED gate | Expert reviewer found a major correctness regression | The leak fix works, but the shared `CommandElement.OnCommandParameterChanged` migration can re-enable a no-command disabled back button when `CommandParameter` changes. |
## Candidate details
### `pr`
The raw PR migrates `BackButtonBehavior` to `ICommandElement` and uses `CommandElement.OnCommandChanging` / `CommandElement.OnCommandChanged`, which correctly routes command event subscription through `WeakCommandSubscription`. The PR regression test addition is appropriate and the saved gate result passed.
The problem is the parameter-change path: the PR changes `CommandParameterProperty` to `CommandElement.OnCommandParameterChanged`. That helper always invokes `CanExecuteChanged`, and `CommandElement.GetCanExecute` returns true when `Command` is null. The old implementation only recalculated command-enabled state when `Command != null`, so the raw PR changes observable behavior outside the leak fix.
### `pr-plus-reviewer`
This candidate applies the expert feedback to the PR by retaining shared weak subscription for `Command` changes but replacing the parameter-change callback with a local guarded callback. It removes the identified no-command re-enable regression and is likely functionally correct, but it still changes `BackButtonBehavior` to implement the shared command interface where the direct candidate does not need to.
### `try-fix-1`
This candidate replaces only the strong event subscription with a private `WeakCommandSubscription`, disposes the previous subscription on command replacement, and keeps the existing `OnCommandChanged` / `OnCommandParameterChanged` semantics intact. It passed the same targeted leak regression filter and had no blocking expert findings in the saved try-fix review.
## Winner
`try-fix-1` wins. It is the only candidate that both passed the targeted regression run and avoids the expert-reviewed behavioral regression while making the smallest implementation change necessary to fix the leak.
</details>
</details>
<!-- SESSION:7748750 END -->
---
<details>
<summary><strong>🧭 Next Steps</strong> — alternative fix proposed (<code>try-fix-1</code>)</summary>
<br/>
**Automated review — alternative fix proposed**
The expert-reviewer evaluation compared the PR fix against automatically generated candidates and selected <code>try-fix-1</code> as the strongest fix.
**Why:** try-fix-1 fixes the BackButtonBehavior.Command leak with a private WeakCommandSubscription while preserving the original CommandParameter behavior. It passed the targeted regression tests and avoids the raw PR regression where CommandParameter changes can re-enable a no-command disabled back button.
Please consider applying the candidate diff below (or use it as guidance). Once you push an update, this workflow will re-trigger and re-evaluate.
<details><summary>Candidate diff (<code>try-fix-1</code>)</summary>
````diff
diff --git a/src/Controls/src/Core/Shell/BackButtonBehavior.cs b/src/Controls/src/Core/Shell/BackButtonBehavior.cs
index 5e9b062fc7..8a9d481710 100644
--- a/src/Controls/src/Core/Shell/BackButtonBehavior.cs
+++ b/src/Controls/src/Core/Shell/BackButtonBehavior.cs
@@ -66,6 +66,7 @@ namespace Microsoft.Maui.Controls
bool _userDefinedIsEnabled = true;
// Tracks the enabled state derived from the command's CanExecute result.
bool _commandEnabled = true;
+ WeakCommandSubscription _commandSubscription;
/// <summary>
/// Gets or sets a value indicating whether the back button is enabled. This is a bindable property.
@@ -127,15 +128,13 @@ namespace Microsoft.Maui.Controls
void OnCommandChanged(ICommand oldCommand, ICommand newCommand)
{
- if (oldCommand != null)
- {
- oldCommand.CanExecuteChanged -= CanExecuteChanged;
- }
+ _commandSubscription?.Dispose();
+ _commandSubscription = null;
if (newCommand != null)
{
- newCommand.CanExecuteChanged += CanExecuteChanged;
- IsEnabledCore = Command.CanExecute(CommandParameter);
+ _commandSubscription = new WeakCommandSubscription(this, newCommand, CanExecuteChanged);
+ IsEnabledCore = newCommand.CanExecute(CommandParameter);
}
else
{
diff --git a/src/Controls/tests/Core.UnitTests/CommandTests.cs b/src/Controls/tests/Core.UnitTests/CommandTests.cs
index 3f4237785c..1f454837d3 100644
--- a/src/Controls/tests/Core.UnitTests/CommandTests.cs
+++ b/src/Controls/tests/Core.UnitTests/CommandTests.cs
@@ -271,6 +271,8 @@ namespace Microsoft.Maui.Controls.Core.UnitTests
[InlineData(typeof(SearchBar), false)]
[InlineData(typeof(SearchHandler), true)]
[InlineData(typeof(SearchHandler), false)]
+ [InlineData(typeof(BackButtonBehavior), true)]
+ [InlineData(typeof(BackButtonBehavior), false)]
public async Task CommandsSubscribedToCanExecuteCollect(Type controlType, bool useWeakEventHandler)
{
// Create a view model with a Command
@@ -310,6 +312,9 @@ namespace Microsoft.Maui.Controls.Core.UnitTests
sh.Command = command;
sh.ClearPlaceholderCommand = command;
break;
+ case BackButtonBehavior bbb:
+ bbb.Command = command;
+ break;
}
// Create a weak reference to the button
…36370) > [!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! > [!IMPORTANT] > This pull request was generated automatically by the **Memory Leak Fixer** agentic workflow in dotnet/maui. It contains a regression test empirically proven to fail without the fix and pass with it. Please review carefully — it is AI-generated. Fixes #36345 Refs: #36345 Target branch: main Attempt: 1/3 ## The leak `BackButtonBehavior` subscribed to `ICommand.CanExecuteChanged` with a **strong** delegate: ```csharp newCommand.CanExecuteChanged += CanExecuteChanged; ``` Because an `ICommand` is commonly stored on a long-lived view model (or otherwise shared/retained), that strong subscription keeps the `BackButtonBehavior` — and everything it transitively roots — alive for as long as the command lives. The only unsubscribe happened when the `Command` property itself changed, so a behavior whose command outlives it is never released. Retention path (from issue #36345): `ICommand (long-lived) -> CanExecuteChanged event -> BackButtonBehavior.CanExecuteChanged delegate -> BackButtonBehavior` ## The fix Route the subscription through the existing `WeakCommandSubscription` helper (already used by `CommandElement` for `Button`, `ImageButton`, `RefreshView`, etc.). It uses a `DependentHandle` so the command references the behavior only weakly, and the previous subscription is disposed whenever the command changes. `src/Controls/src/Core/Shell/BackButtonBehavior.cs`: ```csharp WeakCommandSubscription _commandSubscription; void OnCommandChanged(ICommand oldCommand, ICommand newCommand) { _commandSubscription?.Dispose(); _commandSubscription = null; if (newCommand != null) { _commandSubscription = new WeakCommandSubscription(this, newCommand, CanExecuteChanged); IsEnabledCore = Command.CanExecute(CommandParameter); } else { IsEnabledCore = true; } } ``` No public API change (private field, internal helper). All `IsEnabled`/`CanExecute` behavior is preserved. ## Regression test Extends the existing `CommandsSubscribedToCanExecuteCollect` theory in `src/Controls/tests/Core.UnitTests/CommandTests.cs` with `BackButtonBehavior` rows for both the weak-event and strong-event command variants. The strong-event variant (`useWeakEventHandler: false`) reproduces the leak. Verified in this run (net TFM, `Controls.Core.UnitTests`): | State | `BackButtonBehavior, false` | Result | | --- | --- | --- | | Without fix (red) | `Assert.False() Failure — Expected: False, Actual: True` (behavior still alive) | ❌ FAIL | | With fix (green) | behavior collected | ✅ PASS | Red run (unpatched source): ``` Failed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.BackButtonBehavior), useWeakEventHandler: False) [1 s] Assert.False() Failure Expected: False Actual: True ... Total tests: 16 Passed: 15 Failed: 1 ``` Green run (with fix): ``` Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.BackButtonBehavior), useWeakEventHandler: False) [82 ms] ... Total tests: 16 Passed: 16 ``` Full `CommandTests` class after the fix: **45 passed, 0 failed** (no regressions). ## Scope - Managed, cross-platform only: `src/Controls/src/Core/Shell/BackButtonBehavior.cs`. - No test was muted, skipped, or weakened; no `[ActiveIssue]` / `Skip=` / timeout changes. - Mirrors the same weak-subscription hardening already applied to sibling command controls. --- 🤖 Generated by the **Memory Leak Fixer** agentic workflow (dotnet/maui). This PR is AI-generated — please review before merging. > Generated by [Memory Leak Fixer](https://github.com/dotnet/maui/actions/runs/28694768688) · 2.2K AIC · ⌖ 176.3 AIC · ⊞ 60.6K · [◷](https://github.com/search?q=repo%3Adotnet%2Fmaui+%22gh-aw-workflow-id%3A+leak-fixer%22&type=pullrequests) <!-- gh-aw-agentic-workflow: Memory Leak Fixer, engine: copilot, version: 1.0.60, model: claude-opus-4.8, id: 28694768688, workflow_id: leak-fixer, run: https://github.com/dotnet/maui/actions/runs/28694768688 --> <!-- gh-aw-workflow-id: leak-fixer --> <!-- gh-aw-workflow-call-id: dotnet/maui/leak-fixer --> --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
…36370) > [!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! > [!IMPORTANT] > This pull request was generated automatically by the **Memory Leak Fixer** agentic workflow in dotnet/maui. It contains a regression test empirically proven to fail without the fix and pass with it. Please review carefully — it is AI-generated. Fixes #36345 Refs: #36345 Target branch: main Attempt: 1/3 ## The leak `BackButtonBehavior` subscribed to `ICommand.CanExecuteChanged` with a **strong** delegate: ```csharp newCommand.CanExecuteChanged += CanExecuteChanged; ``` Because an `ICommand` is commonly stored on a long-lived view model (or otherwise shared/retained), that strong subscription keeps the `BackButtonBehavior` — and everything it transitively roots — alive for as long as the command lives. The only unsubscribe happened when the `Command` property itself changed, so a behavior whose command outlives it is never released. Retention path (from issue #36345): `ICommand (long-lived) -> CanExecuteChanged event -> BackButtonBehavior.CanExecuteChanged delegate -> BackButtonBehavior` ## The fix Route the subscription through the existing `WeakCommandSubscription` helper (already used by `CommandElement` for `Button`, `ImageButton`, `RefreshView`, etc.). It uses a `DependentHandle` so the command references the behavior only weakly, and the previous subscription is disposed whenever the command changes. `src/Controls/src/Core/Shell/BackButtonBehavior.cs`: ```csharp WeakCommandSubscription _commandSubscription; void OnCommandChanged(ICommand oldCommand, ICommand newCommand) { _commandSubscription?.Dispose(); _commandSubscription = null; if (newCommand != null) { _commandSubscription = new WeakCommandSubscription(this, newCommand, CanExecuteChanged); IsEnabledCore = Command.CanExecute(CommandParameter); } else { IsEnabledCore = true; } } ``` No public API change (private field, internal helper). All `IsEnabled`/`CanExecute` behavior is preserved. ## Regression test Extends the existing `CommandsSubscribedToCanExecuteCollect` theory in `src/Controls/tests/Core.UnitTests/CommandTests.cs` with `BackButtonBehavior` rows for both the weak-event and strong-event command variants. The strong-event variant (`useWeakEventHandler: false`) reproduces the leak. Verified in this run (net TFM, `Controls.Core.UnitTests`): | State | `BackButtonBehavior, false` | Result | | --- | --- | --- | | Without fix (red) | `Assert.False() Failure — Expected: False, Actual: True` (behavior still alive) | ❌ FAIL | | With fix (green) | behavior collected | ✅ PASS | Red run (unpatched source): ``` Failed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.BackButtonBehavior), useWeakEventHandler: False) [1 s] Assert.False() Failure Expected: False Actual: True ... Total tests: 16 Passed: 15 Failed: 1 ``` Green run (with fix): ``` Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.BackButtonBehavior), useWeakEventHandler: False) [82 ms] ... Total tests: 16 Passed: 16 ``` Full `CommandTests` class after the fix: **45 passed, 0 failed** (no regressions). ## Scope - Managed, cross-platform only: `src/Controls/src/Core/Shell/BackButtonBehavior.cs`. - No test was muted, skipped, or weakened; no `[ActiveIssue]` / `Skip=` / timeout changes. - Mirrors the same weak-subscription hardening already applied to sibling command controls. --- 🤖 Generated by the **Memory Leak Fixer** agentic workflow (dotnet/maui). This PR is AI-generated — please review before merging. > Generated by [Memory Leak Fixer](https://github.com/dotnet/maui/actions/runs/28694768688) · 2.2K AIC · ⌖ 176.3 AIC · ⊞ 60.6K · [◷](https://github.com/search?q=repo%3Adotnet%2Fmaui+%22gh-aw-workflow-id%3A+leak-fixer%22&type=pullrequests) <!-- gh-aw-agentic-workflow: Memory Leak Fixer, engine: copilot, version: 1.0.60, model: claude-opus-4.8, id: 28694768688, workflow_id: leak-fixer, run: https://github.com/dotnet/maui/actions/runs/28694768688 --> <!-- gh-aw-workflow-id: leak-fixer --> <!-- gh-aw-workflow-call-id: dotnet/maui/leak-fixer --> --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
…36370) > [!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! > [!IMPORTANT] > This pull request was generated automatically by the **Memory Leak Fixer** agentic workflow in dotnet/maui. It contains a regression test empirically proven to fail without the fix and pass with it. Please review carefully — it is AI-generated. Fixes #36345 Refs: #36345 Target branch: main Attempt: 1/3 ## The leak `BackButtonBehavior` subscribed to `ICommand.CanExecuteChanged` with a **strong** delegate: ```csharp newCommand.CanExecuteChanged += CanExecuteChanged; ``` Because an `ICommand` is commonly stored on a long-lived view model (or otherwise shared/retained), that strong subscription keeps the `BackButtonBehavior` — and everything it transitively roots — alive for as long as the command lives. The only unsubscribe happened when the `Command` property itself changed, so a behavior whose command outlives it is never released. Retention path (from issue #36345): `ICommand (long-lived) -> CanExecuteChanged event -> BackButtonBehavior.CanExecuteChanged delegate -> BackButtonBehavior` ## The fix Route the subscription through the existing `WeakCommandSubscription` helper (already used by `CommandElement` for `Button`, `ImageButton`, `RefreshView`, etc.). It uses a `DependentHandle` so the command references the behavior only weakly, and the previous subscription is disposed whenever the command changes. `src/Controls/src/Core/Shell/BackButtonBehavior.cs`: ```csharp WeakCommandSubscription _commandSubscription; void OnCommandChanged(ICommand oldCommand, ICommand newCommand) { _commandSubscription?.Dispose(); _commandSubscription = null; if (newCommand != null) { _commandSubscription = new WeakCommandSubscription(this, newCommand, CanExecuteChanged); IsEnabledCore = Command.CanExecute(CommandParameter); } else { IsEnabledCore = true; } } ``` No public API change (private field, internal helper). All `IsEnabled`/`CanExecute` behavior is preserved. ## Regression test Extends the existing `CommandsSubscribedToCanExecuteCollect` theory in `src/Controls/tests/Core.UnitTests/CommandTests.cs` with `BackButtonBehavior` rows for both the weak-event and strong-event command variants. The strong-event variant (`useWeakEventHandler: false`) reproduces the leak. Verified in this run (net TFM, `Controls.Core.UnitTests`): | State | `BackButtonBehavior, false` | Result | | --- | --- | --- | | Without fix (red) | `Assert.False() Failure — Expected: False, Actual: True` (behavior still alive) | ❌ FAIL | | With fix (green) | behavior collected | ✅ PASS | Red run (unpatched source): ``` Failed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.BackButtonBehavior), useWeakEventHandler: False) [1 s] Assert.False() Failure Expected: False Actual: True ... Total tests: 16 Passed: 15 Failed: 1 ``` Green run (with fix): ``` Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.BackButtonBehavior), useWeakEventHandler: False) [82 ms] ... Total tests: 16 Passed: 16 ``` Full `CommandTests` class after the fix: **45 passed, 0 failed** (no regressions). ## Scope - Managed, cross-platform only: `src/Controls/src/Core/Shell/BackButtonBehavior.cs`. - No test was muted, skipped, or weakened; no `[ActiveIssue]` / `Skip=` / timeout changes. - Mirrors the same weak-subscription hardening already applied to sibling command controls. --- 🤖 Generated by the **Memory Leak Fixer** agentic workflow (dotnet/maui). This PR is AI-generated — please review before merging. > Generated by [Memory Leak Fixer](https://github.com/dotnet/maui/actions/runs/28694768688) · 2.2K AIC · ⌖ 176.3 AIC · ⊞ 60.6K · [◷](https://github.com/search?q=repo%3Adotnet%2Fmaui+%22gh-aw-workflow-id%3A+leak-fixer%22&type=pullrequests) <!-- gh-aw-agentic-workflow: Memory Leak Fixer, engine: copilot, version: 1.0.60, model: claude-opus-4.8, id: 28694768688, workflow_id: leak-fixer, run: https://github.com/dotnet/maui/actions/runs/28694768688 --> <!-- gh-aw-workflow-id: leak-fixer --> <!-- gh-aw-workflow-call-id: dotnet/maui/leak-fixer --> --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
…36370) > [!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! > [!IMPORTANT] > This pull request was generated automatically by the **Memory Leak Fixer** agentic workflow in dotnet/maui. It contains a regression test empirically proven to fail without the fix and pass with it. Please review carefully — it is AI-generated. Fixes #36345 Refs: #36345 Target branch: main Attempt: 1/3 ## The leak `BackButtonBehavior` subscribed to `ICommand.CanExecuteChanged` with a **strong** delegate: ```csharp newCommand.CanExecuteChanged += CanExecuteChanged; ``` Because an `ICommand` is commonly stored on a long-lived view model (or otherwise shared/retained), that strong subscription keeps the `BackButtonBehavior` — and everything it transitively roots — alive for as long as the command lives. The only unsubscribe happened when the `Command` property itself changed, so a behavior whose command outlives it is never released. Retention path (from issue #36345): `ICommand (long-lived) -> CanExecuteChanged event -> BackButtonBehavior.CanExecuteChanged delegate -> BackButtonBehavior` ## The fix Route the subscription through the existing `WeakCommandSubscription` helper (already used by `CommandElement` for `Button`, `ImageButton`, `RefreshView`, etc.). It uses a `DependentHandle` so the command references the behavior only weakly, and the previous subscription is disposed whenever the command changes. `src/Controls/src/Core/Shell/BackButtonBehavior.cs`: ```csharp WeakCommandSubscription _commandSubscription; void OnCommandChanged(ICommand oldCommand, ICommand newCommand) { _commandSubscription?.Dispose(); _commandSubscription = null; if (newCommand != null) { _commandSubscription = new WeakCommandSubscription(this, newCommand, CanExecuteChanged); IsEnabledCore = Command.CanExecute(CommandParameter); } else { IsEnabledCore = true; } } ``` No public API change (private field, internal helper). All `IsEnabled`/`CanExecute` behavior is preserved. ## Regression test Extends the existing `CommandsSubscribedToCanExecuteCollect` theory in `src/Controls/tests/Core.UnitTests/CommandTests.cs` with `BackButtonBehavior` rows for both the weak-event and strong-event command variants. The strong-event variant (`useWeakEventHandler: false`) reproduces the leak. Verified in this run (net TFM, `Controls.Core.UnitTests`): | State | `BackButtonBehavior, false` | Result | | --- | --- | --- | | Without fix (red) | `Assert.False() Failure — Expected: False, Actual: True` (behavior still alive) | ❌ FAIL | | With fix (green) | behavior collected | ✅ PASS | Red run (unpatched source): ``` Failed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.BackButtonBehavior), useWeakEventHandler: False) [1 s] Assert.False() Failure Expected: False Actual: True ... Total tests: 16 Passed: 15 Failed: 1 ``` Green run (with fix): ``` Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.BackButtonBehavior), useWeakEventHandler: False) [82 ms] ... Total tests: 16 Passed: 16 ``` Full `CommandTests` class after the fix: **45 passed, 0 failed** (no regressions). ## Scope - Managed, cross-platform only: `src/Controls/src/Core/Shell/BackButtonBehavior.cs`. - No test was muted, skipped, or weakened; no `[ActiveIssue]` / `Skip=` / timeout changes. - Mirrors the same weak-subscription hardening already applied to sibling command controls. --- 🤖 Generated by the **Memory Leak Fixer** agentic workflow (dotnet/maui). This PR is AI-generated — please review before merging. > Generated by [Memory Leak Fixer](https://github.com/dotnet/maui/actions/runs/28694768688) · 2.2K AIC · ⌖ 176.3 AIC · ⊞ 60.6K · [◷](https://github.com/search?q=repo%3Adotnet%2Fmaui+%22gh-aw-workflow-id%3A+leak-fixer%22&type=pullrequests) <!-- gh-aw-agentic-workflow: Memory Leak Fixer, engine: copilot, version: 1.0.60, model: claude-opus-4.8, id: 28694768688, workflow_id: leak-fixer, run: https://github.com/dotnet/maui/actions/runs/28694768688 --> <!-- gh-aw-workflow-id: leak-fixer --> <!-- gh-aw-workflow-call-id: dotnet/maui/leak-fixer --> --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
…36370) > [!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! > [!IMPORTANT] > This pull request was generated automatically by the **Memory Leak Fixer** agentic workflow in dotnet/maui. It contains a regression test empirically proven to fail without the fix and pass with it. Please review carefully — it is AI-generated. Fixes #36345 Refs: #36345 Target branch: main Attempt: 1/3 ## The leak `BackButtonBehavior` subscribed to `ICommand.CanExecuteChanged` with a **strong** delegate: ```csharp newCommand.CanExecuteChanged += CanExecuteChanged; ``` Because an `ICommand` is commonly stored on a long-lived view model (or otherwise shared/retained), that strong subscription keeps the `BackButtonBehavior` — and everything it transitively roots — alive for as long as the command lives. The only unsubscribe happened when the `Command` property itself changed, so a behavior whose command outlives it is never released. Retention path (from issue #36345): `ICommand (long-lived) -> CanExecuteChanged event -> BackButtonBehavior.CanExecuteChanged delegate -> BackButtonBehavior` ## The fix Route the subscription through the existing `WeakCommandSubscription` helper (already used by `CommandElement` for `Button`, `ImageButton`, `RefreshView`, etc.). It uses a `DependentHandle` so the command references the behavior only weakly, and the previous subscription is disposed whenever the command changes. `src/Controls/src/Core/Shell/BackButtonBehavior.cs`: ```csharp WeakCommandSubscription _commandSubscription; void OnCommandChanged(ICommand oldCommand, ICommand newCommand) { _commandSubscription?.Dispose(); _commandSubscription = null; if (newCommand != null) { _commandSubscription = new WeakCommandSubscription(this, newCommand, CanExecuteChanged); IsEnabledCore = Command.CanExecute(CommandParameter); } else { IsEnabledCore = true; } } ``` No public API change (private field, internal helper). All `IsEnabled`/`CanExecute` behavior is preserved. ## Regression test Extends the existing `CommandsSubscribedToCanExecuteCollect` theory in `src/Controls/tests/Core.UnitTests/CommandTests.cs` with `BackButtonBehavior` rows for both the weak-event and strong-event command variants. The strong-event variant (`useWeakEventHandler: false`) reproduces the leak. Verified in this run (net TFM, `Controls.Core.UnitTests`): | State | `BackButtonBehavior, false` | Result | | --- | --- | --- | | Without fix (red) | `Assert.False() Failure — Expected: False, Actual: True` (behavior still alive) | ❌ FAIL | | With fix (green) | behavior collected | ✅ PASS | Red run (unpatched source): ``` Failed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.BackButtonBehavior), useWeakEventHandler: False) [1 s] Assert.False() Failure Expected: False Actual: True ... Total tests: 16 Passed: 15 Failed: 1 ``` Green run (with fix): ``` Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.BackButtonBehavior), useWeakEventHandler: False) [82 ms] ... Total tests: 16 Passed: 16 ``` Full `CommandTests` class after the fix: **45 passed, 0 failed** (no regressions). ## Scope - Managed, cross-platform only: `src/Controls/src/Core/Shell/BackButtonBehavior.cs`. - No test was muted, skipped, or weakened; no `[ActiveIssue]` / `Skip=` / timeout changes. - Mirrors the same weak-subscription hardening already applied to sibling command controls. --- 🤖 Generated by the **Memory Leak Fixer** agentic workflow (dotnet/maui). This PR is AI-generated — please review before merging. > Generated by [Memory Leak Fixer](https://github.com/dotnet/maui/actions/runs/28694768688) · 2.2K AIC · ⌖ 176.3 AIC · ⊞ 60.6K · [◷](https://github.com/search?q=repo%3Adotnet%2Fmaui+%22gh-aw-workflow-id%3A+leak-fixer%22&type=pullrequests) <!-- gh-aw-agentic-workflow: Memory Leak Fixer, engine: copilot, version: 1.0.60, model: claude-opus-4.8, id: 28694768688, workflow_id: leak-fixer, run: https://github.com/dotnet/maui/actions/runs/28694768688 --> <!-- gh-aw-workflow-id: leak-fixer --> <!-- gh-aw-workflow-call-id: dotnet/maui/leak-fixer --> --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
- leak-fixer.md: cache the open/closed/merged [leak-fix] PR searches ONCE per run (new Step 2.5) instead of re-running all three GitHub searches for every auto-selected candidate. Step 3 now applies its per-candidate jq filters (gates a-d) against the cached JSON files. (r3685311261) - daily-leak-hunter.md + leak-fixer.md gate (d): a merged "[leak-fix]" PR only proves the fix landed on ITS base branch, not necessarily `main` (real counterexample: #36370, merged into `inflight/current`). Both "fixed-on-main" provenance lookups now verify each merge commit is an ancestor of `main` via the GitHub compare API (`ahead_by == 0`), the same ancestry check already used by the release-readiness skill, before trusting it as main provenance. This preserves the intended dedup behavior (no false "already fixed" suppression/close) while fixing the false-positive. (r3732227859) - leak-fixer.md: make the dry_run no-write guarantee job-enforced via `safe-outputs.staged`, matching the pattern already used by ci-status-main.md/ci-status-net11.md, instead of relying solely on agent prompt compliance. The generated safe_outputs job now stages (never executes) close-issue/create-pull-request/ push-to-pull-request-branch/add-comment whenever dry_run is true. (r3732227918) Both workflows recompiled with `gh aw compile --strict` (0 warnings); .lock.yml files regenerated and included. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d00747b7-96f3-4e7a-8dfb-e3a48db04b2d
…36370) > [!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! > [!IMPORTANT] > This pull request was generated automatically by the **Memory Leak Fixer** agentic workflow in dotnet/maui. It contains a regression test empirically proven to fail without the fix and pass with it. Please review carefully — it is AI-generated. Fixes #36345 Refs: #36345 Target branch: main Attempt: 1/3 ## The leak `BackButtonBehavior` subscribed to `ICommand.CanExecuteChanged` with a **strong** delegate: ```csharp newCommand.CanExecuteChanged += CanExecuteChanged; ``` Because an `ICommand` is commonly stored on a long-lived view model (or otherwise shared/retained), that strong subscription keeps the `BackButtonBehavior` — and everything it transitively roots — alive for as long as the command lives. The only unsubscribe happened when the `Command` property itself changed, so a behavior whose command outlives it is never released. Retention path (from issue #36345): `ICommand (long-lived) -> CanExecuteChanged event -> BackButtonBehavior.CanExecuteChanged delegate -> BackButtonBehavior` ## The fix Route the subscription through the existing `WeakCommandSubscription` helper (already used by `CommandElement` for `Button`, `ImageButton`, `RefreshView`, etc.). It uses a `DependentHandle` so the command references the behavior only weakly, and the previous subscription is disposed whenever the command changes. `src/Controls/src/Core/Shell/BackButtonBehavior.cs`: ```csharp WeakCommandSubscription _commandSubscription; void OnCommandChanged(ICommand oldCommand, ICommand newCommand) { _commandSubscription?.Dispose(); _commandSubscription = null; if (newCommand != null) { _commandSubscription = new WeakCommandSubscription(this, newCommand, CanExecuteChanged); IsEnabledCore = Command.CanExecute(CommandParameter); } else { IsEnabledCore = true; } } ``` No public API change (private field, internal helper). All `IsEnabled`/`CanExecute` behavior is preserved. ## Regression test Extends the existing `CommandsSubscribedToCanExecuteCollect` theory in `src/Controls/tests/Core.UnitTests/CommandTests.cs` with `BackButtonBehavior` rows for both the weak-event and strong-event command variants. The strong-event variant (`useWeakEventHandler: false`) reproduces the leak. Verified in this run (net TFM, `Controls.Core.UnitTests`): | State | `BackButtonBehavior, false` | Result | | --- | --- | --- | | Without fix (red) | `Assert.False() Failure — Expected: False, Actual: True` (behavior still alive) | ❌ FAIL | | With fix (green) | behavior collected | ✅ PASS | Red run (unpatched source): ``` Failed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.BackButtonBehavior), useWeakEventHandler: False) [1 s] Assert.False() Failure Expected: False Actual: True ... Total tests: 16 Passed: 15 Failed: 1 ``` Green run (with fix): ``` Passed CommandsSubscribedToCanExecuteCollect(controlType: typeof(Microsoft.Maui.Controls.BackButtonBehavior), useWeakEventHandler: False) [82 ms] ... Total tests: 16 Passed: 16 ``` Full `CommandTests` class after the fix: **45 passed, 0 failed** (no regressions). ## Scope - Managed, cross-platform only: `src/Controls/src/Core/Shell/BackButtonBehavior.cs`. - No test was muted, skipped, or weakened; no `[ActiveIssue]` / `Skip=` / timeout changes. - Mirrors the same weak-subscription hardening already applied to sibling command controls. --- 🤖 Generated by the **Memory Leak Fixer** agentic workflow (dotnet/maui). This PR is AI-generated — please review before merging. > Generated by [Memory Leak Fixer](https://github.com/dotnet/maui/actions/runs/28694768688) · 2.2K AIC · ⌖ 176.3 AIC · ⊞ 60.6K · [◷](https://github.com/search?q=repo%3Adotnet%2Fmaui+%22gh-aw-workflow-id%3A+leak-fixer%22&type=pullrequests) <!-- gh-aw-agentic-workflow: Memory Leak Fixer, engine: copilot, version: 1.0.60, model: claude-opus-4.8, id: 28694768688, workflow_id: leak-fixer, run: https://github.com/dotnet/maui/actions/runs/28694768688 --> <!-- gh-aw-workflow-id: leak-fixer --> <!-- gh-aw-workflow-call-id: dotnet/maui/leak-fixer --> --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
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!
Important
This pull request was generated automatically by the Memory Leak Fixer agentic workflow in dotnet/maui. It contains a regression test empirically proven to fail without the fix and pass with it. Please review carefully — it is AI-generated.
Fixes #36345
Refs: #36345
Target branch: main
Attempt: 1/3
The leak
BackButtonBehaviorsubscribed toICommand.CanExecuteChangedwith a strong delegate:Because an
ICommandis commonly stored on a long-lived view model (or otherwise shared/retained), that strong subscription keeps theBackButtonBehavior— and everything it transitively roots — alive for as long as the command lives. The only unsubscribe happened when theCommandproperty itself changed, so a behavior whose command outlives it is never released.Retention path (from issue #36345):
ICommand (long-lived) -> CanExecuteChanged event -> BackButtonBehavior.CanExecuteChanged delegate -> BackButtonBehaviorThe fix
Route the subscription through the existing
WeakCommandSubscriptionhelper (already used byCommandElementforButton,ImageButton,RefreshView, etc.). It uses aDependentHandleso the command references the behavior only weakly, and the previous subscription is disposed whenever the command changes.src/Controls/src/Core/Shell/BackButtonBehavior.cs:No public API change (private field, internal helper). All
IsEnabled/CanExecutebehavior is preserved.Regression test
Extends the existing
CommandsSubscribedToCanExecuteCollecttheory insrc/Controls/tests/Core.UnitTests/CommandTests.cswithBackButtonBehaviorrows for both the weak-event and strong-event command variants. The strong-event variant (useWeakEventHandler: false) reproduces the leak.Verified in this run (net TFM,
Controls.Core.UnitTests):BackButtonBehavior, falseAssert.False() Failure — Expected: False, Actual: True(behavior still alive)Red run (unpatched source):
Green run (with fix):
Full
CommandTestsclass after the fix: 45 passed, 0 failed (no regressions).Scope
src/Controls/src/Core/Shell/BackButtonBehavior.cs.[ActiveIssue]/Skip=/ timeout changes.🤖 Generated by the Memory Leak Fixer agentic workflow (dotnet/maui). This PR is AI-generated — please review before merging.