Skip to content

Fix [leak-scan] VisualStateGroupList.Clear — removed groups keep triggers attached - #38439

Merged
kubaflo merged 5 commits into
dotnet:inflight/currentfrom
KarthikRajaKalaimani:fix-38245
Sep 23, 2026
Merged

kubaflo merged 5 commits into
dotnet:inflight/currentfrom
KarthikRajaKalaimani:fix-38245

Conversation

@KarthikRajaKalaimani

@KarthikRajaKalaimani KarthikRajaKalaimani commented Sep 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

Clearing an attached VisualStateGroupList removes groups without detaching the state triggers nested inside them. A trigger subscribed to a shared managed publisher in OnAttached() therefore stays subscribed and retained after its group is removed.

Root Cause

An attached StateTriggerBase runs OnAttached(), where custom triggers may subscribe to long-lived publishers such as static events. They rely on SendDetached() invoking OnDetached() to unsubscribe.

Replacing the entire VisualStateGroups attached property already performed this teardown. However, mutating the existing VisualStateGroupList did not:

  • Clear
  • Remove
  • RemoveAt
  • Adding a group that replaces one with the same name
  • Replacing a group through the indexer

These paths only removed StatesChanged handlers and collection entries. Nested triggers remained attached, leaving retention paths such as:

static publisher → event delegate → state trigger → page-local data

Description of Change

Added a shared DetachGroup teardown method that:

  1. Unsubscribes the group's StatesChanged handler.
  2. Calls SendDetached() on every nested state trigger.
  3. Removes the group's reference to its associated visual element.

All removal and replacement paths in VisualStateGroupList now use this teardown.

The Remove implementation also identifies the actual stored group before removing it. This ensures the correct instance is detached even when another equality-equivalent object is supplied.

Regression coverage

Added tests to VisualStateManagerTests.cs verifying trigger detachment for:

  • Clear
  • Remove
  • RemoveAt
  • Duplicate-name replacement through Add
  • Index replacement

Issues Fixed

Fixes #38245

Tested the behavior in the following platforms.

  • Android
  • Windows
  • iOS
  • Mac
Before After
image image

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

Or

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

@dotnet-policy-service dotnet-policy-service Bot added the community ✨ Community Contribution label Sep 11, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Hey there @@KarthikRajaKalaimani! Thank you so much for your PR! Someone from the team will get assigned to your PR shortly and we'll get it reviewed.

@azure-pipelines

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

@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Sep 11, 2026
MauiBot

This comment was marked as outdated.

@MauiBot MauiBot added s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-gate-passed AI verified tests catch the bug (fail without fix, pass with fix) s/agent-fix-win AI found a better alternative fix than the PR s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review) and removed s/agent-review-in-progress AI review is currently running for this PR labels Sep 11, 2026
@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Sep 11, 2026

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Expert Review — 2 findings

See inline comments for details.

MauiBot

This comment was marked as outdated.

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

Copy link
Copy Markdown
Contributor Author

AI Review Summary

@KarthikRajaKalaimani — new AI review results are available based on commit 1c07d15.

Gate Passed Confidence Unknown Platform Android

🗂️ Review Sessions — click to expand

🚦 Gate — Test Before & After Fix

Gate Result: ✅ PASSED

Platform: ANDROID · Base: main · Merge base: 699f16e4

Test Without Fix (expect FAIL) With Fix (expect PASS)
🧪 VisualStateManagerTests VisualStateManagerTests ✅ FAIL — 101s ✅ PASS — 70s
🔴 Without fix — 🧪 VisualStateManagerTests: FAIL ✅ · 101s
Error-relevant lines (filtered from the build log):

     at Microsoft.Maui.Controls.Core.UnitTests.VisualStateManagerTests.ReplacingGroupByIndexDetachesStateTriggers() in /_/src/Controls/tests/Core.UnitTests/VisualStateManagerTests.cs:line 386
   at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)
   at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)
     at Microsoft.Maui.Controls.Core.UnitTests.VisualStateManagerTests.ClearDetachesStateTriggers() in /_/src/Controls/tests/Core.UnitTests/VisualStateManagerTests.cs:line 346
     at Microsoft.Maui.Controls.Core.UnitTests.VisualStateManagerTests.RemoveDetachesStateTriggers() in /_/src/Controls/tests/Core.UnitTests/VisualStateManagerTests.cs:line 356
     at Microsoft.Maui.Controls.Core.UnitTests.VisualStateManagerTests.AddingDuplicateNamedGroupDetachesReplacedStateTriggers() in /_/src/Controls/tests/Core.UnitTests/VisualStateManagerTests.cs:line 376
     at Microsoft.Maui.Controls.Core.UnitTests.VisualStateManagerTests.RemoveAtDetachesStateTriggers() in /_/src/Controls/tests/Core.UnitTests/VisualStateManagerTests.cs:line 366

🟢 With fix — 🧪 VisualStateManagerTests: PASS ✅ · 70s
(no coded error found; showing last 1200 chars)

riggers [< 1 ms]
  Passed RemoveDetachesStateTriggers [4 ms]
  Passed IsEnabledToggleWhileSelectedPreservesState [9 ms]
  Passed SelectHoverDeselectRestoresPointerOverState [< 1 ms]
  Passed StateNamesMustBeUniqueWithinGroupList [< 1 ms]
  Passed VisualStateGroupsFromSettersAreDistinct [2 ms]
  Passed ImplicitStyleDisabledVSMOverridesLocalValue [1 ms]
  Passed VisualElementGoesToCorrectStateWhenAvailable [< 1 ms]
  Passed SelectingWhileDisabledStaysDisabledUntilReEnabled [< 1 ms]
  Passed StateNamesInGroupMayNotBeEmpty [< 1 ms]
  Passed CanRemoveAStateAndAddANewStateWithTheSameName [1 ms]
  Passed VSMFromStyleAreUnApplied [1 ms]
[xUnit.net 00:00:03.21]   Finished:    Microsoft.Maui.Controls.Core.UnitTests
  Passed UnapplyingVSMShouldUnapplySetters [< 1 ms]
  Passed AddingDuplicateNamedGroupDetachesReplacedStateTriggers [1 ms]
  Passed RemoveAtDetachesStateTriggers [< 1 ms]
  Passed StateNamesInGroupMayNotBeNull [< 1 ms]
  Passed VerifyVisualStateChanges [1 ms]
  Passed AssigningSameIsItemSelectedValueIsNoOp [< 1 ms]
  Passed VisualElementGoesToCorrectStateWhenAvailableFromSetter [< 1 ms]
Test Run Successful.
Total tests: 34
     Passed: 33
    Skipped: 1
 Total time: 4.4985 Seconds

📁 Fix files reverted (1 files)

  • src/Controls/src/Core/VisualStateManager.cs

📋 Pre-Flight — Context & Validation

PR #38439 Pre-Flight

Context

  • PR: [WIP] Fix [leak-scan] VisualStateGroupList.Clear — removed groups keep triggers attached
  • Issue: [leak-scan] VisualStateGroupList.Clear — removed groups keep triggers attached #38245
  • Base/head: main at 699f16e4c2 / PR head 1c07d15f60 (materialized locally as squashed commit 5a73743767)
  • Platform requested for this phase: Android
  • Gate: Passed previously; the five targeted tests fail without the production fix and pass with it. Gate verification must not be rerun or overwritten.

Problem

Removing a VisualStateGroup from an attached VisualStateGroupList does not call SendDetached() on nested StateTriggerBase instances. A custom trigger that subscribes to a long-lived publisher in OnAttached() therefore remains subscribed after removal and can retain page-local state indefinitely.

The affected mutation paths are:

  1. Clear
  2. Remove
  3. RemoveAt
  4. Duplicate-name replacement through Add
  5. Indexer replacement

Existing PR Approach

The PR adds VisualStateGroupList.DetachGroup, which unsubscribes StatesChanged, calls SendDetached() for every nested trigger, and clears VisualStateGroup.VisualElement. Every removal/replacement path calls that helper. Remove resolves the stored item by index before teardown, while the indexer validates null, skips self-replacement, wires the replacement, and revalidates the list.

Changed files:

  • src/Controls/src/Core/VisualStateManager.cs (implementation)
  • src/Controls/tests/Core.UnitTests/VisualStateManagerTests.cs (unit tests)

The alternatives must not reproduce the PR's explicit list-level helper invoked by each mutation path.

Targeted Validation

Use only this focused Controls unit-test command:

dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --filter "FullyQualifiedName=Microsoft.Maui.Controls.Core.UnitTests.VisualStateManagerTests.ClearDetachesStateTriggers|FullyQualifiedName=Microsoft.Maui.Controls.Core.UnitTests.VisualStateManagerTests.RemoveDetachesStateTriggers|FullyQualifiedName=Microsoft.Maui.Controls.Core.UnitTests.VisualStateManagerTests.RemoveAtDetachesStateTriggers|FullyQualifiedName=Microsoft.Maui.Controls.Core.UnitTests.VisualStateManagerTests.AddingDuplicateNamedGroupDetachesReplacedStateTriggers|FullyQualifiedName=Microsoft.Maui.Controls.Core.UnitTests.VisualStateManagerTests.ReplacingGroupByIndexDetachesStateTriggers"

No full suite is authorized. No additional mandatory regression-test command was included in the STEP 5a prompt. Each candidate may run the command once and, only after one focused correction, once more.

Constraints and Prior Attempts

  • The behavior is cross-platform although this phase is tagged Android; validation is platform-neutral.
  • Preserve normal IList<T> behavior, including returning false when Remove cannot find an item.
  • Detach the actual stored group, never an equality-equivalent argument that is not stored.
  • Do not detach a group that remains in the list or emit duplicate detach/attach notifications.
  • Keep public API unchanged.
  • Existing .github/ and eng/ worktree changes are trusted harness overlays and must remain untouched.
  • A prior review proposed detachment from the VisualStateGroup.VisualElement owner-to-null transition but was blocked before implementation.
  • A prior review proposed adding removal notifications to shared WatchAddList<T> but was blocked before implementation.
  • New attempts must avoid both prior untested mechanisms as well as the submitted PR mechanism.

🔬 Code Review — Deep Analysis

Expert PR Evaluation

Verdict: NEEDS_CHANGES

The submitted teardown mechanism correctly covers the five leak-producing removal and replacement paths exercised by the trusted gate, but the revised VisualStateGroupList.Remove violates its ICollection<T>.Remove contract. When the supplied group is not present, IndexOf returns -1 and the implementation calls RemoveAt(-1), throwing ArgumentOutOfRangeException instead of returning false.

Findings

  1. Major — Logic and correctness: Restore the non-member path in Remove so it returns false without detaching anything.
  2. Moderate — Regression prevention: Add focused coverage for removing a non-member; the submitted tests exercise only successful removal and therefore miss the contract regression.

The raw PR is not the recommended candidate as submitted. A consolidated candidate that preserves its trigger teardown while fixing and testing the non-member path should be compared against the blocked, unvalidated STEP 5a alternatives.

🛠️ Try-Fix — Analysis & Comparison

PR #38439 Try-Fix Aggregate

Candidate 1 — Baseline-Gated Safety Stop

  • Model: gpt-5.3-codex
  • Result: Blocked
  • Approach: No production mechanism was implemented. The attempt enforced the required baseline allow-list boundary and stopped before editing when EstablishBrokenBaseline.ps1 rejected the pre-existing dirty worktree.
  • Mechanisms avoided: The PR's per-operation DetachGroup helper, the prior VisualElement owner-to-null proposal, and the prior shared WatchAddList<T> removal-notification proposal.
  • Diff: None.
  • Tests: Not run because baseline establishment failed before an editable-file allow-list was created.
  • Failure analysis: The trusted .github/ and eng/ harness overlay appears as tracked worktree changes. The baseline script reported DIRTY WORKING DIRECTORY, created no .github/.baseline-state.json, and therefore prohibited a safe implementation. The exact script-only restore reported no baseline state; the target production file has no worktree diff.
  • Self-review: 0 findings.

Candidate details: ../try-fix-1/content.md

Candidate 2 — Final Observer Release

  • Model: gpt-5.6-sol
  • Result: Blocked
  • Approach: Use the final removal of a list's internal StatesChanged observer as the group-membership lifetime boundary. A backed event would detach nested triggers when its last owning-list observer is removed; subscription multiplicity would keep a group attached while another occurrence remains.
  • Mechanisms avoided: The PR's per-operation helper, the prior VisualElement owner-to-null proposal, the prior shared WatchAddList<T> notification proposal, and Candidate 1's workflow-only safety-stop framing.
  • Mechanism-level difference: Membership is represented by existing event subscriptions. Removing one occurrence releases one subscription; only the transition to zero observers performs trigger teardown. This centralizes lifecycle cleanup on observer ownership rather than on each collection mutation.
  • Diff: None; this remained a read-only design.
  • Tests: Not run because mandatory baseline establishment again failed before creating an editable-file allow-list.
  • Failure analysis: The baseline script rejected the trusted tracked .github/ and eng/ overlay as DIRTY WORKING DIRECTORY. With no .github/.baseline-state.json, editing the target was prohibited. The exact restore command reported the expected no-state result, and the target file has no worktree diff.
  • Self-review: 0 findings.

Candidate details: ../try-fix-2/content.md

Final Aggregate

Model Approach Result Diff Test Evidence

1 gpt-5.3-codex Baseline-gated safety stop; no implementation BLOCKED None Not run
2 gpt-5.6-sol Detach nested triggers when final owning-list observer is released BLOCKED None Not run
PR PR #38439 Explicit list-level teardown for every removal/replacement path PASS 1 implementation file, 1 test file Trusted gate: targeted tests fail without fix and pass with fix

Aggregate Outcome

Both permitted candidates completed. Neither could produce or validate a source diff because the mandatory baseline script rejected the pre-existing trusted harness overlay before creating its restoration allow-list. Candidate 2 records a mechanism-level alternative for STEP 5b comparison, but it has no empirical evidence and must rank below the gate-validated PR fix. No candidate code remains in the worktree, and gate/content.md was not touched.

📝 PR Finalize — Recommended Title & Description

Assessment: ✏️ Recommend updating — the current title retains a WIP marker and names only Clear, while the submitted PR covers every group removal and replacement path; the detailed description itself should be preserved.

Recommended title

[Controls] VisualStateGroupList: Detach state triggers when groups are removed or replaced

Recommended description

### Issue Details

Clearing an attached VisualStateGroupList removes groups without detaching the state triggers nested inside them. A trigger subscribed to a shared managed publisher in OnAttached() therefore stays subscribed and retained after its group is removed.

### Root Cause

An attached `StateTriggerBase` runs `OnAttached()`, where custom triggers may subscribe to long-lived publishers such as static events. They rely on `SendDetached()` invoking `OnDetached()` to unsubscribe.

Replacing the entire `VisualStateGroups` attached property already performed this teardown. However, mutating the existing `VisualStateGroupList` did not:

- `Clear`
- `Remove`
- `RemoveAt`
- Adding a group that replaces one with the same name
- Replacing a group through the indexer

These paths only removed `StatesChanged` handlers and collection entries. Nested triggers remained attached, leaving retention paths such as:

```text
static publisher → event delegate → state trigger → page-local data

Description of Change

Added a shared DetachGroup teardown method that:

  1. Unsubscribes the group's StatesChanged handler.
  2. Calls SendDetached() on every nested state trigger.
  3. Removes the group's reference to its associated visual element.

All removal and replacement paths in VisualStateGroupList now use this teardown.

The Remove implementation also identifies the actual stored group before removing it. This ensures the correct instance is detached even when another equality-equivalent object is supplied.

Regression coverage

Added tests to VisualStateManagerTests.cs verifying trigger detachment for:

  • Clear
  • Remove
  • RemoveAt
  • Duplicate-name replacement through Add
  • Index replacement

Issues Fixed

Fixes #38245

Tested the behavior in the following platforms.

  • Android
  • Windows
  • iOS
  • Mac
Before After
image image

**🏁 Report — Final Recommendation**

## ⚠️ Final Recommendation: REQUEST CHANGES
**Winner:** `pr-plus-reviewer`

The submitted PR fixes the reported trigger-retention paths and its trusted gate proves that all five new lifecycle tests fail without the fix and pass with it. The expert review nevertheless found a concrete regression in the submitted `VisualStateGroupList.Remove`: removing a non-member now calls `RemoveAt(-1)` and throws instead of returning `false` as required by `ICollection<T>.Remove`.

`pr-plus-reviewer` is the only candidate that preserves the gate-proven teardown behavior, resolves every expert finding, and has focused passing validation. It adds the missing `index < 0` return path and extends the already-selected `RemoveDetachesStateTriggers` test to prove that a non-member returns `false`, leaves the live trigger attached, and still detaches the actual stored group when subsequently removed.

## Candidate Comparison
Rank	Candidate	Implementation	Regression evidence	Expert-review status	Result
1	`pr-plus-reviewer`	Submitted teardown plus the consolidated `Remove(false)` correction and coverage	**PASS** — authorized filter passed 5/5 from the required sandbox	Resolves both findings	**Winner**
2	`pr`	Explicit `DetachGroup` teardown across `Clear`, `Remove`, `RemoveAt`, duplicate-name `Add`, and index replacement	Trusted Gate **PASS** — tests fail without the fix and pass with it	**Major unresolved regression:** non-member `Remove` throws; negative case untested	Request changes
3	`try-fix-2`	Read-only proposal to detach after the final `StatesChanged` observer is removed	**Not run**; no diff	No empirical implementation evidence	Blocked
4	`try-fix-1`	No production mechanism; baseline safety stop only	**Not run**; no diff	Nothing implementable to assess	Blocked
## Why the Alternatives Lose
* The raw `pr` ranks below `pr-plus-reviewer` despite its successful gate because passing leak-regression tests do not excuse the independently verified collection-contract regression.
* `try-fix-2` describes a distinct observer-lifetime design, but it was neither implemented nor tested. Its proposed coupling of trigger lifetime to event-subscriber count has no evidence that it preserves all existing event and ownership semantics.
* `try-fix-1` contains no candidate fix and therefore cannot satisfy the issue.

## Required PR Change
Apply `pr-plus-reviewer/reviewer.patch` to the submitted PR. The complete proposed PR diff is preserved in `pr-plus-reviewer/candidate.patch`; the focused run is preserved in `pr-plus-reviewer/targeted-validation.log`.

**📱 UI Tests — VisualStateManager**

**Detected UI test categories:** `VisualStateManager`

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

### 🧪 UI Test Execution Results (deep, platform pool)
Category	Tests	Snapshot diffs
`VisualStateManager`	97/101 (4 skipped) ✓	—
📎 [Download `drop-deep-uitests` artifact (TRX + snapshot diffs)](https://devdiv.visualstudio.com/DevDiv/_build/results?buildId=15292473&view=artifacts&pathAsName=false&type=publishedArtifacts)		
**🧭 Next Steps** — reviewer changes required

addressed Ai summary concerns.

@KarthikRajaKalaimani KarthikRajaKalaimani changed the title [WIP] Fix [leak-scan] VisualStateGroupList.Clear — removed groups keep triggers attached Fix [leak-scan] VisualStateGroupList.Clear — removed groups keep triggers attached Sep 16, 2026
@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Sep 21, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Note

🔍 /review started

AzDO build 15396792 is running for android.

The s/agent-review-in-progress label stays on this PR while the run is active. The final recommendation and outcome labels are posted only after Gate, expert review, and Deep UI tests finish.

@kubaflo

This comment has been minimized.

@github-actions

Copy link
Copy Markdown
Contributor

Tests Failure Analysis

@KarthikRajaKalaimani — test-failure analysis for commit 2036dff.

Scope CI failures Commit 2036dff


🧪 CI Analysis — click to expand
📊 maui-pr

🧪 maui-pr-devicetests

No results available.


🧪 maui-pr-uitests

No results available.


🧭 Follow-up — actions and refresh

Next action: Comment /azp run maui-pr-devicetests and /azp run maui-pr-uitests.

Maintainers: comment /review tests to refresh this report.

@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

@KarthikRajaKalaimani — new AI review results are available based on commit 2036dff.

Gate Passed Confidence Low Platform Android


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

Gate Result: ✅ PASSED

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

Test Without Fix (expect FAIL) With Fix (expect PASS)
🧪 VisualStateManagerTests VisualStateManagerTests ✅ FAIL — 116s ✅ PASS — 69s
🔴 Without fix — 🧪 VisualStateManagerTests: FAIL ✅ · 116s

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

     at Microsoft.Maui.Controls.Core.UnitTests.VisualStateManagerTests.ReplacingGroupByIndexDetachesStateTriggers() in /_/src/Controls/tests/Core.UnitTests/VisualStateManagerTests.cs:line 399
   at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)
   at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)
     at Microsoft.Maui.Controls.Core.UnitTests.VisualStateManagerTests.ClearDetachesStateTriggers() in /_/src/Controls/tests/Core.UnitTests/VisualStateManagerTests.cs:line 346
     at Microsoft.Maui.Controls.Core.UnitTests.VisualStateManagerTests.RemoveDetachesStateTriggers() in /_/src/Controls/tests/Core.UnitTests/VisualStateManagerTests.cs:line 356
     at Microsoft.Maui.Controls.Core.UnitTests.VisualStateManagerTests.AddingDuplicateNamedGroupDetachesReplacedStateTriggers() in /_/src/Controls/tests/Core.UnitTests/VisualStateManagerTests.cs:line 389
     at Microsoft.Maui.Controls.Core.UnitTests.VisualStateManagerTests.RemoveAtDetachesStateTriggers() in /_/src/Controls/tests/Core.UnitTests/VisualStateManagerTests.cs:line 379
🟢 With fix — 🧪 VisualStateManagerTests: PASS ✅ · 69s

(no coded error found; showing last 1200 chars)

 1 ms]
  Passed IsEnabledToggleWhileSelectedPreservesState [5 ms]
  Passed SelectHoverDeselectRestoresPointerOverState [< 1 ms]
  Passed StateNamesMustBeUniqueWithinGroupList [< 1 ms]
  Passed VisualStateGroupsFromSettersAreDistinct [< 1 ms]
  Passed RemoveNonMemberReturnsFalse [< 1 ms]
  Passed ImplicitStyleDisabledVSMOverridesLocalValue [1 ms]
  Passed VisualElementGoesToCorrectStateWhenAvailable [< 1 ms]
  Passed SelectingWhileDisabledStaysDisabledUntilReEnabled [< 1 ms]
  Passed StateNamesInGroupMayNotBeEmpty [< 1 ms]
  Passed CanRemoveAStateAndAddANewStateWithTheSameName [< 1 ms]
[xUnit.net 00:00:03.35]   Finished:    Microsoft.Maui.Controls.Core.UnitTests
  Passed VSMFromStyleAreUnApplied [1 ms]
  Passed UnapplyingVSMShouldUnapplySetters [< 1 ms]
  Passed AddingDuplicateNamedGroupDetachesReplacedStateTriggers [< 1 ms]
  Passed RemoveAtDetachesStateTriggers [< 1 ms]
  Passed StateNamesInGroupMayNotBeNull [< 1 ms]
  Passed VerifyVisualStateChanges [< 1 ms]
  Passed AssigningSameIsItemSelectedValueIsNoOp [< 1 ms]
  Passed VisualElementGoesToCorrectStateWhenAvailableFromSetter [< 1 ms]
Test Run Successful.
Total tests: 35
     Passed: 34
    Skipped: 1
 Total time: 4.6141 Seconds
📁 Fix files reverted (1 files)
  • src/Controls/src/Core/VisualStateManager.cs

📋 Pre-Flight — Context & Validation

PR #38439 Pre-Flight

Context

  • PR: Fix [leak-scan] VisualStateGroupList.Clear — removed groups keep triggers attached
  • Issue: #38245
  • Platform: Android (the defect is in shared Controls code and affects all platforms)
  • Base: main
  • Materialized review commit: 1f2fcef2bbcf0484c82e6f5460674113544c4fe8
  • Merge base: f8a2f062a8e1b4686a5a3de93bb69cabc02c8c4a

An attached StateTriggerBase can subscribe to a long-lived publisher from
OnAttached(). Removing its VisualStateGroup through an existing
VisualStateGroupList does not call SendDetached(), so OnDetached() cannot
unsubscribe and the publisher continues retaining the trigger and page-local
state.

Affected mutation paths are Clear, Remove, RemoveAt, duplicate-name
replacement in Add, and indexer replacement.

Existing PR Approach

The PR adds VisualStateGroupList.DetachGroup, which unsubscribes
StatesChanged, calls SendDetached() for each nested trigger, and clears the
group's VisualElement. It routes every removal/replacement path through that
helper. The PR also changes Remove to locate the stored instance and adds five
trigger-detachment tests plus a non-member removal test.

Changed files:

  • src/Controls/src/Core/VisualStateManager.cs
  • src/Controls/tests/Core.UnitTests/VisualStateManagerTests.cs

Alternative candidates must avoid repeating the PR's centralized
DetachGroup-called-from-each-list-mutation strategy and may modify only
src/Controls/src/Core/VisualStateManager.cs; the regression tests are
read-only.

Verification Surface

The prior gate already proved the tests fail without the fix and pass with it:
five added regression tests failed at baseline, while the fixed class suite
passed 34 tests with one skipped.

Run only:

dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --filter "FullyQualifiedName~VisualStateManagerTests" --logger "console;verbosity=normal"

This class-level primary test includes the five new regression cases and the
existing adjacent Visual State Manager tests. No additional mandatory
regression test command was specified. Do not rerun gate verification or run a
broader suite.

Constraints

  • Use EstablishBrokenBaseline.ps1 and its restore mode exactly as required by
    the try-fix skill.
  • Preserve gate/content.md.
  • One initial implementation/test pass and at most one focused
    correction/retest.
  • Perform the skill's expert self-review inline; do not launch another agent.
  • Persist all attempt artifacts before restoring the source file.

🔬 Code Review — Deep Analysis

Code Review — PR #38439

Independent Assessment

What this changes: The submitted fix routes VisualStateGroupList removal and replacement paths through DetachGroup, which unsubscribes StatesChanged, detaches nested state triggers, and clears the removed group's VisualElement. It also makes Remove resolve the actual stored group and validates/wires index replacements.

Inferred motivation: A removed trigger can remain subscribed to a long-lived publisher after its group leaves an attached list, retaining page-local state.

Expert Reviewer Result

The single maui-expert-reviewer invocation returned LGTM with medium confidence and no new actionable inline findings. It confirmed that SendDetached() is idempotent and that the submitted regression tests cover the reported trigger-retention paths. The required inline-findings.json was written as [].

Prior Review Reconciliation

Prior error finding Status Evidence
Removing a non-member called RemoveAt(-1) instead of returning false ✅ Fixed Current Remove returns false when IndexOf is negative, and RemoveNonMemberReturnsFalse covers the contract.
Missing negative-case coverage for Remove ✅ Fixed RemoveNonMemberReturnsFalse is present in the submitted HEAD.
Active visual-state setters survive group removal ❌ Unresolved DetachGroup detaches triggers and clears group.VisualElement without unapplying setters from group.CurrentState; whole-property replacement already performs equivalent setter cleanup.

Failure-Mode Probing

  • Clear/remove an active group: Trigger subscriptions are released, but the active state's setter contributions remain applied after the defining group is gone.
  • Duplicate-name/index replacement: The outgoing group is detached before the replacement is installed, so stale effective values can remain from the removed group.
  • Repeated detach: StateTriggerBase.SendDetached() is guarded by IsAttached, so repeated lifecycle cleanup does not duplicate OnDetached() calls.
  • Non-member removal: The current implementation returns false without detaching or mutating the stored group.

CI Status

The trusted Gate passed: the focused regressions fail without the submitted fix and pass with it. GitHub required-check status could not be collected because gh is unauthenticated; no claim is made that all PR CI is green.

External Output Contract

Not applicable.

Verdict: NEEDS_CHANGES

Confidence: low

Summary: The submitted fix closes the reported trigger-subscription leak, and the current expert reviewer found no new changed-line defect. However, the mandatory prior-review reconciliation leaves a concrete earlier error unresolved: collection-level teardown does not relinquish setters from an active removed group. A reviewer-enhanced candidate should address that adjacent lifecycle invariant before comparison.


🛠️ Try-Fix — Analysis & Comparison

Alternative Fix Candidates for PR #38439

Candidate 1 — VisualStateGroup ownership-transition teardown

Result: FAIL

This candidate moved trigger teardown away from explicit collection-mutation
traversal and into VisualStateGroup.VisualElement ownership changes. It
compiled after one focused correction, then failed all five new detachment
tests (29 passed, 5 failed, 1 skipped).

The mechanism is insufficient because a trigger can be directly attached while
its group owner remains null. Removing that group produces no ownership
transition, so the teardown gate is never entered. Candidate 2 must not depend
on a prior non-null VisualElement and must not repeat either this ownership
strategy or the PR's centralized mutation-path DetachGroup strategy.

Candidate report (including its complete diff):
CustomAgentLogsTmp/PRState/38439/PRAgent/try-fix-1/content.md

Attempt artifacts:
CustomAgentLogsTmp/PRState/38439/PRAgent/try-fix/attempt-1/

Candidate 2 — Backing-collection removal notifications

Result: PASS

This candidate extends WatchAddList<T> with an optional removal callback and
configures VisualStateGroupList to tear down the actual stored group in
response to structural removal. This differs from both prior mechanisms:
public mutation methods do not explicitly invoke teardown, and teardown does
not depend on a prior non-null VisualElement.

The single permitted test run passed all five new regression scenarios and the
adjacent class tests: 35 total, 34 passed, 0 failed, and 1 skipped. Inline
expert self-review found no issues.

The key mechanism is that WatchAddList<T> removes or replaces an entry first,
then reports the stored instance. OnGroupRemoved balances one
StatesChanged subscription and detaches nested triggers only after the final
reference to that exact group leaves the list. This preserves duplicate
reference behavior while covering directly attached, null-owned triggers.

Candidate report (including its complete diff):
CustomAgentLogsTmp/PRState/38439/PRAgent/try-fix-2/content.md

Attempt artifacts:
CustomAgentLogsTmp/PRState/38439/PRAgent/try-fix/attempt-2/

Aggregate Outcome

Candidate Mechanism Result Self-review
1 Detach on VisualStateGroup.VisualElement ownership loss FAIL — 5 regression failures after one correction 1 major finding
2 Detach from WatchAddList<T> structural-removal notification PASS — 34 passed, 1 skipped Clean

Candidate 2 is a viable alternative under the bounded validation performed in
STEP 5a. Candidate 1 is not viable because trigger attachment does not imply a
non-null group owner.


🏁 Report — Final Recommendation

⚠️ Final Recommendation: REQUEST CHANGES

Winner

pr-plus-reviewer

The submitted PR correctly fixes the reported trigger-retention paths and passes the trusted Gate, but mandatory prior-review reconciliation confirmed an unresolved adjacent teardown defect: removing an active VisualStateGroup leaves its setters applied after the group is gone. pr-plus-reviewer preserves the submitted leak fix, adds symmetric active-state cleanup and safe group reuse, and passed the one authorized targeted validation run. Because the winning changes are not in the submitted PR HEAD, the recommendation is REQUEST CHANGES.

Candidate comparison

Rank Candidate Mechanism Regression evidence Assessment
1 pr-plus-reviewer Raw PR plus shared current-state setter cleanup, CurrentState reset, and focused reuse coverage PASS — 35 passed, 1 skipped Only candidate that fixes the trigger leak and relinquishes the removed active state's effective values without breaking group reuse.
2 pr Explicit DetachGroup teardown across Clear, Remove, RemoveAt, duplicate-name Add, and index replacement PASS — trusted Gate, 34 passed and 1 skipped Correct for the reported leak and non-member Remove contract, but leaves active-state setter contributions behind.
3 try-fix-2 WatchAddList<T> structural-removal callbacks drive exact-instance trigger teardown PASS — 34 passed, 1 skipped Viable for the leak, but broadens a shared collection abstraction and still does not unapply setters from an active removed group.
4 try-fix-1 Trigger teardown on VisualStateGroup.VisualElement ownership loss FAIL — 5 target regressions failed; 29 passed, 1 skipped Directly attached triggers can have a null owner, so null-to-null removal never enters the teardown gate.

The regression-failing candidate is ranked below every candidate with passing regression evidence, as required.

Expert and prior-review reconciliation

The single expert-review invocation returned LGTM with medium confidence and wrote inline-findings.json as []. It found no new changed-line issue in the current submitted HEAD. Review of all three prior-comment surfaces found three earlier errors:

  • The non-member RemoveAt(-1) regression is fixed by the current index < 0 return.
  • Missing non-member coverage is fixed by RemoveNonMemberReturnsFalse.
  • Active visual-state setters surviving group removal is still applicable: submitted DetachGroup clears ownership without calling the same setter cleanup used by whole-property replacement.

Under the code-review consistency rules, that unresolved prior error overrides the current no-finding result.

Winning patch

pr-plus-reviewer factors whole-property cleanup into VisualStateManager.UnapplyStateSetters, invokes it from collection teardown before clearing VisualElement, and resets CurrentState so a removed group can be re-added and apply normally. ClearUnappliesAndReappliesCurrentStateSetters covers restoration of the old effective value and reapplication after reuse.

git diff --check 1f2fcef2bbcf0484c82e6f5460674113544c4fe8 passed before validation. The exact required class-level test command ran once from /home/vsts/work/_temp/pr-38439-pr-plus-reviewer and passed all runnable tests: 36 total, 35 passed, 1 skipped.

Evidence and uncertainty

  • Raw PR trusted Gate: PASS; not rerun.
  • pr-plus-reviewer: PASS; one authorized focused run.
  • try-fix-2: PASS under STEP 5a's bounded class-level run.
  • try-fix-1: FAIL with all five new detachment regressions failing.
  • Mechanical regression cross-reference: clean.
  • GitHub required checks could not be queried because gh is unauthenticated; this report does not claim all PR CI is green.

Apply pr-plus-reviewer/reviewer.patch to the submitted PR.


📱 UI Tests — VisualStateManager

Detected UI test categories: VisualStateManager

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

🧪 UI Test Execution Results (deep, platform pool)

Category Tests Snapshot diffs
VisualStateManager 97/101 (4 skipped) ✓ —
📎 Download drop-deep-uitests artifact (TRX + snapshot diffs)

🧭 Next Steps — reviewer changes required

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

Why: The reviewer-enhanced PR preserves the Gate-validated trigger-detachment fix and also removes active-state setter contributions before group ownership is cleared. Its single authorized VisualStateManager test run passed 35 tests with 1 skip, while the raw PR and try-fix-2 leave that teardown invariant unresolved.

Address the actionable findings in this review before merging.

@MauiBot MauiBot added s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-fix-win AI found a better alternative fix than the PR and removed s/agent-approved AI agent recommends approval - PR fix is correct and optimal s/agent-fix-pr-picked AI could not beat the PR fix - PR is the best among all candidates s/agent-review-in-progress AI review is currently running for this PR labels Sep 21, 2026
@kubaflo
kubaflo changed the base branch from main to inflight/current September 21, 2026 17:33

@kubaflo kubaflo left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Could you please resolve conflicts and check the ai's suggestions?

@kubaflo

kubaflo commented Sep 21, 2026

Copy link
Copy Markdown
Contributor

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines will not run the associated pipelines, because the pull request was updated after the run command was issued. Review the pull request again and issue a new run command.

kubaflo and others added 2 commits September 23, 2026 12:35
Preserve group trigger teardown alongside upstream state-trigger removal and indexer subscription handling.

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

kubaflo commented Sep 23, 2026

Copy link
Copy Markdown
Contributor

Resolved the conflict in VisualStateManager.cs and pushed the original fix-38245 branch to 37cca13. Merged the latest inflight/current (c525623ec5bb60db19a7c19f7843c3a61e92cf6c) using ordinary merge commits, without rewriting history. The resolution preserves group-trigger teardown, the upstream indexer subscription/validation fix, and the newer individual-trigger removal fix.

This PR is still needed. #37340 fixes group subscription handling, and #38444 detaches triggers removed from VisualState.StateTriggers. Neither detaches nested triggers when an entire group is removed from VisualStateGroupList.

Verified against that exact current target using the full fail-without/pass-with script:

  • Without this fix: five regressions fail (Clear, Remove, RemoveAt, duplicate-name replacement, and index replacement); 33 tests pass and one existing performance test is skipped.
  • With this fix: all 38 runnable VisualStateManagerTests pass, including the upstream subscription and individual-trigger removal tests; the same performance test is skipped.
  • Script result: VERIFICATION PASSED. Build tasks and formatting also completed successfully, and the worktree is clean.

GitHub now reports no merge conflicts. CI for the new head has not completed; this is not a CI-green or merge-approval claim.

@kubaflo
kubaflo merged commit 3164ce8 into dotnet:inflight/current Sep 23, 2026
2 of 12 checks passed
@github-actions github-actions Bot added this to the .NET 10 SR12 milestone Sep 23, 2026
kubaflo added a commit that referenced this pull request Sep 27, 2026
…ggers attached (#38439)

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

Clearing an attached VisualStateGroupList removes groups without
detaching the state triggers nested inside them. A trigger subscribed to
a shared managed publisher in OnAttached() therefore stays subscribed
and retained after its group is removed.

### Root Cause 

An attached `StateTriggerBase` runs `OnAttached()`, where custom
triggers may subscribe to long-lived publishers such as static events.
They rely on `SendDetached()` invoking `OnDetached()` to unsubscribe.
 
Replacing the entire `VisualStateGroups` attached property already
performed this teardown. However, mutating the existing
`VisualStateGroupList` did not:
 
- `Clear`
- `Remove`
- `RemoveAt`
- Adding a group that replaces one with the same name
- Replacing a group through the indexer
 
These paths only removed `StatesChanged` handlers and collection
entries. Nested triggers remained attached, leaving retention paths such
as:
 
```text
static publisher → event delegate → state trigger → page-local data
```

### Description of Change

Added a shared `DetachGroup` teardown method that:
 
1. Unsubscribes the group's `StatesChanged` handler.
2. Calls `SendDetached()` on every nested state trigger.
3. Removes the group's reference to its associated visual element.
 
All removal and replacement paths in `VisualStateGroupList` now use this
teardown.
 
The `Remove` implementation also identifies the actual stored group
before removing it. This ensures the correct instance is detached even
when another equality-equivalent object is supplied.
 
## Regression coverage
 
Added tests to `VisualStateManagerTests.cs` verifying trigger detachment
for:
 
- `Clear`
- `Remove`
- `RemoveAt`
- Duplicate-name replacement through `Add`
- Index replacement 
 
### Issues Fixed
 
Fixes #38245  
 
**Tested the behavior in the following platforms.**
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac
 
| Before  | After  |
|---------|--------|
| <img width="300" height="600" alt="image"
src="https://github.com/user-attachments/assets/3f5ede16-f0ee-4aac-b728-07835001f851"
/> | <img width="300" height="600" alt="image"
src="https://github.com/user-attachments/assets/dafc0ce1-e9b4-439d-949e-cbe29a29af49"
/> |

---------

Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
kubaflo added a commit that referenced this pull request Oct 3, 2026
…ggers attached (#38439)

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

Clearing an attached VisualStateGroupList removes groups without
detaching the state triggers nested inside them. A trigger subscribed to
a shared managed publisher in OnAttached() therefore stays subscribed
and retained after its group is removed.

### Root Cause 

An attached `StateTriggerBase` runs `OnAttached()`, where custom
triggers may subscribe to long-lived publishers such as static events.
They rely on `SendDetached()` invoking `OnDetached()` to unsubscribe.
 
Replacing the entire `VisualStateGroups` attached property already
performed this teardown. However, mutating the existing
`VisualStateGroupList` did not:
 
- `Clear`
- `Remove`
- `RemoveAt`
- Adding a group that replaces one with the same name
- Replacing a group through the indexer
 
These paths only removed `StatesChanged` handlers and collection
entries. Nested triggers remained attached, leaving retention paths such
as:
 
```text
static publisher → event delegate → state trigger → page-local data
```

### Description of Change

Added a shared `DetachGroup` teardown method that:
 
1. Unsubscribes the group's `StatesChanged` handler.
2. Calls `SendDetached()` on every nested state trigger.
3. Removes the group's reference to its associated visual element.
 
All removal and replacement paths in `VisualStateGroupList` now use this
teardown.
 
The `Remove` implementation also identifies the actual stored group
before removing it. This ensures the correct instance is detached even
when another equality-equivalent object is supplied.
 
## Regression coverage
 
Added tests to `VisualStateManagerTests.cs` verifying trigger detachment
for:
 
- `Clear`
- `Remove`
- `RemoveAt`
- Duplicate-name replacement through `Add`
- Index replacement 
 
### Issues Fixed
 
Fixes #38245  
 
**Tested the behavior in the following platforms.**
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac
 
| Before  | After  |
|---------|--------|
| <img width="300" height="600" alt="image"
src="https://github.com/user-attachments/assets/3f5ede16-f0ee-4aac-b728-07835001f851"
/> | <img width="300" height="600" alt="image"
src="https://github.com/user-attachments/assets/dafc0ce1-e9b4-439d-949e-cbe29a29af49"
/> |

---------

Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
kubaflo added a commit that referenced this pull request Oct 6, 2026
…ggers attached (#38439)

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

Clearing an attached VisualStateGroupList removes groups without
detaching the state triggers nested inside them. A trigger subscribed to
a shared managed publisher in OnAttached() therefore stays subscribed
and retained after its group is removed.

### Root Cause 

An attached `StateTriggerBase` runs `OnAttached()`, where custom
triggers may subscribe to long-lived publishers such as static events.
They rely on `SendDetached()` invoking `OnDetached()` to unsubscribe.
 
Replacing the entire `VisualStateGroups` attached property already
performed this teardown. However, mutating the existing
`VisualStateGroupList` did not:
 
- `Clear`
- `Remove`
- `RemoveAt`
- Adding a group that replaces one with the same name
- Replacing a group through the indexer
 
These paths only removed `StatesChanged` handlers and collection
entries. Nested triggers remained attached, leaving retention paths such
as:
 
```text
static publisher → event delegate → state trigger → page-local data
```

### Description of Change

Added a shared `DetachGroup` teardown method that:
 
1. Unsubscribes the group's `StatesChanged` handler.
2. Calls `SendDetached()` on every nested state trigger.
3. Removes the group's reference to its associated visual element.
 
All removal and replacement paths in `VisualStateGroupList` now use this
teardown.
 
The `Remove` implementation also identifies the actual stored group
before removing it. This ensures the correct instance is detached even
when another equality-equivalent object is supplied.
 
## Regression coverage
 
Added tests to `VisualStateManagerTests.cs` verifying trigger detachment
for:
 
- `Clear`
- `Remove`
- `RemoveAt`
- Duplicate-name replacement through `Add`
- Index replacement 
 
### Issues Fixed
 
Fixes #38245  
 
**Tested the behavior in the following platforms.**
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac
 
| Before  | After  |
|---------|--------|
| <img width="300" height="600" alt="image"
src="https://github.com/user-attachments/assets/3f5ede16-f0ee-4aac-b728-07835001f851"
/> | <img width="300" height="600" alt="image"
src="https://github.com/user-attachments/assets/dafc0ce1-e9b4-439d-949e-cbe29a29af49"
/> |

---------

Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
kubaflo added a commit that referenced this pull request Oct 13, 2026
…ggers attached (#38439)

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

Clearing an attached VisualStateGroupList removes groups without
detaching the state triggers nested inside them. A trigger subscribed to
a shared managed publisher in OnAttached() therefore stays subscribed
and retained after its group is removed.

### Root Cause 

An attached `StateTriggerBase` runs `OnAttached()`, where custom
triggers may subscribe to long-lived publishers such as static events.
They rely on `SendDetached()` invoking `OnDetached()` to unsubscribe.
 
Replacing the entire `VisualStateGroups` attached property already
performed this teardown. However, mutating the existing
`VisualStateGroupList` did not:
 
- `Clear`
- `Remove`
- `RemoveAt`
- Adding a group that replaces one with the same name
- Replacing a group through the indexer
 
These paths only removed `StatesChanged` handlers and collection
entries. Nested triggers remained attached, leaving retention paths such
as:
 
```text
static publisher → event delegate → state trigger → page-local data
```

### Description of Change

Added a shared `DetachGroup` teardown method that:
 
1. Unsubscribes the group's `StatesChanged` handler.
2. Calls `SendDetached()` on every nested state trigger.
3. Removes the group's reference to its associated visual element.
 
All removal and replacement paths in `VisualStateGroupList` now use this
teardown.
 
The `Remove` implementation also identifies the actual stored group
before removing it. This ensures the correct instance is detached even
when another equality-equivalent object is supplied.
 
## Regression coverage
 
Added tests to `VisualStateManagerTests.cs` verifying trigger detachment
for:
 
- `Clear`
- `Remove`
- `RemoveAt`
- Duplicate-name replacement through `Add`
- Index replacement 
 
### Issues Fixed
 
Fixes #38245  
 
**Tested the behavior in the following platforms.**
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac
 
| Before  | After  |
|---------|--------|
| <img width="300" height="600" alt="image"
src="https://github.com/user-attachments/assets/3f5ede16-f0ee-4aac-b728-07835001f851"
/> | <img width="300" height="600" alt="image"
src="https://github.com/user-attachments/assets/dafc0ce1-e9b4-439d-949e-cbe29a29af49"
/> |

---------

Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
kubaflo added a commit that referenced this pull request Oct 14, 2026
…ggers attached (#38439)

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

Clearing an attached VisualStateGroupList removes groups without
detaching the state triggers nested inside them. A trigger subscribed to
a shared managed publisher in OnAttached() therefore stays subscribed
and retained after its group is removed.

### Root Cause 

An attached `StateTriggerBase` runs `OnAttached()`, where custom
triggers may subscribe to long-lived publishers such as static events.
They rely on `SendDetached()` invoking `OnDetached()` to unsubscribe.
 
Replacing the entire `VisualStateGroups` attached property already
performed this teardown. However, mutating the existing
`VisualStateGroupList` did not:
 
- `Clear`
- `Remove`
- `RemoveAt`
- Adding a group that replaces one with the same name
- Replacing a group through the indexer
 
These paths only removed `StatesChanged` handlers and collection
entries. Nested triggers remained attached, leaving retention paths such
as:
 
```text
static publisher → event delegate → state trigger → page-local data
```

### Description of Change

Added a shared `DetachGroup` teardown method that:
 
1. Unsubscribes the group's `StatesChanged` handler.
2. Calls `SendDetached()` on every nested state trigger.
3. Removes the group's reference to its associated visual element.
 
All removal and replacement paths in `VisualStateGroupList` now use this
teardown.
 
The `Remove` implementation also identifies the actual stored group
before removing it. This ensures the correct instance is detached even
when another equality-equivalent object is supplied.
 
## Regression coverage
 
Added tests to `VisualStateManagerTests.cs` verifying trigger detachment
for:
 
- `Clear`
- `Remove`
- `RemoveAt`
- Duplicate-name replacement through `Add`
- Index replacement 
 
### Issues Fixed
 
Fixes #38245  
 
**Tested the behavior in the following platforms.**
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac
 
| Before  | After  |
|---------|--------|
| <img width="300" height="600" alt="image"
src="https://github.com/user-attachments/assets/3f5ede16-f0ee-4aac-b728-07835001f851"
/> | <img width="300" height="600" alt="image"
src="https://github.com/user-attachments/assets/dafc0ce1-e9b4-439d-949e-cbe29a29af49"
/> |

---------

Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
kubaflo added a commit that referenced this pull request Oct 18, 2026
…ggers attached (#38439)

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

Clearing an attached VisualStateGroupList removes groups without
detaching the state triggers nested inside them. A trigger subscribed to
a shared managed publisher in OnAttached() therefore stays subscribed
and retained after its group is removed.

### Root Cause 

An attached `StateTriggerBase` runs `OnAttached()`, where custom
triggers may subscribe to long-lived publishers such as static events.
They rely on `SendDetached()` invoking `OnDetached()` to unsubscribe.
 
Replacing the entire `VisualStateGroups` attached property already
performed this teardown. However, mutating the existing
`VisualStateGroupList` did not:
 
- `Clear`
- `Remove`
- `RemoveAt`
- Adding a group that replaces one with the same name
- Replacing a group through the indexer
 
These paths only removed `StatesChanged` handlers and collection
entries. Nested triggers remained attached, leaving retention paths such
as:
 
```text
static publisher → event delegate → state trigger → page-local data
```

### Description of Change

Added a shared `DetachGroup` teardown method that:
 
1. Unsubscribes the group's `StatesChanged` handler.
2. Calls `SendDetached()` on every nested state trigger.
3. Removes the group's reference to its associated visual element.
 
All removal and replacement paths in `VisualStateGroupList` now use this
teardown.
 
The `Remove` implementation also identifies the actual stored group
before removing it. This ensures the correct instance is detached even
when another equality-equivalent object is supplied.
 
## Regression coverage
 
Added tests to `VisualStateManagerTests.cs` verifying trigger detachment
for:
 
- `Clear`
- `Remove`
- `RemoveAt`
- Duplicate-name replacement through `Add`
- Index replacement 
 
### Issues Fixed
 
Fixes #38245  
 
**Tested the behavior in the following platforms.**
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac
 
| Before  | After  |
|---------|--------|
| <img width="300" height="600" alt="image"
src="https://github.com/user-attachments/assets/3f5ede16-f0ee-4aac-b728-07835001f851"
/> | <img width="300" height="600" alt="image"
src="https://github.com/user-attachments/assets/dafc0ce1-e9b4-439d-949e-cbe29a29af49"
/> |

---------

Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
kubaflo added a commit that referenced this pull request Oct 21, 2026
…ggers attached (#38439)

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

Clearing an attached VisualStateGroupList removes groups without
detaching the state triggers nested inside them. A trigger subscribed to
a shared managed publisher in OnAttached() therefore stays subscribed
and retained after its group is removed.

### Root Cause 

An attached `StateTriggerBase` runs `OnAttached()`, where custom
triggers may subscribe to long-lived publishers such as static events.
They rely on `SendDetached()` invoking `OnDetached()` to unsubscribe.
 
Replacing the entire `VisualStateGroups` attached property already
performed this teardown. However, mutating the existing
`VisualStateGroupList` did not:
 
- `Clear`
- `Remove`
- `RemoveAt`
- Adding a group that replaces one with the same name
- Replacing a group through the indexer
 
These paths only removed `StatesChanged` handlers and collection
entries. Nested triggers remained attached, leaving retention paths such
as:
 
```text
static publisher → event delegate → state trigger → page-local data
```

### Description of Change

Added a shared `DetachGroup` teardown method that:
 
1. Unsubscribes the group's `StatesChanged` handler.
2. Calls `SendDetached()` on every nested state trigger.
3. Removes the group's reference to its associated visual element.
 
All removal and replacement paths in `VisualStateGroupList` now use this
teardown.
 
The `Remove` implementation also identifies the actual stored group
before removing it. This ensures the correct instance is detached even
when another equality-equivalent object is supplied.
 
## Regression coverage
 
Added tests to `VisualStateManagerTests.cs` verifying trigger detachment
for:
 
- `Clear`
- `Remove`
- `RemoveAt`
- Duplicate-name replacement through `Add`
- Index replacement 
 
### Issues Fixed
 
Fixes #38245  
 
**Tested the behavior in the following platforms.**
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac
 
| Before  | After  |
|---------|--------|
| <img width="300" height="600" alt="image"
src="https://github.com/user-attachments/assets/3f5ede16-f0ee-4aac-b728-07835001f851"
/> | <img width="300" height="600" alt="image"
src="https://github.com/user-attachments/assets/dafc0ce1-e9b4-439d-949e-cbe29a29af49"
/> |

---------

Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@github-actions github-actions Bot locked and limited conversation to collaborators Oct 24, 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-gate-passed AI verified tests catch the bug (fail without fix, pass with fix) 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.

[leak-scan] VisualStateGroupList.Clear — removed groups keep triggers attached

3 participants