Skip to content

Add missing unset arms for modifiers that never released (#986) - #1018

Merged
Alexandre Zollinger Chohfi (azchohfi) merged 19 commits into
mainfrom
azchohfi-modifier-unset-arms
Aug 4, 2026
Merged

Alexandre Zollinger Chohfi (azchohfi) merged 19 commits into
mainfrom
azchohfi-modifier-unset-arms

Conversation

@azchohfi

@azchohfi Alexandre Zollinger Chohfi (azchohfi) commented Jul 31, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #986.

Problem

Reconciler.ApplyModifiers writes a modifier's value only when it is present in the new bag. Several common modifiers had no else arm at all, so dropping one from a fluent chain left the previous render's write pinned on the control forever:

phase == 0 ? Button("Go", Go).IsTabStop(false)
           : Button("Go", Go)          // still IsTabStop=false

ApplyAccessibilityModifiers was worse. It opened with if (a is null) return;, and the caller invokes it precisely when a11y is not null || oldA11y is not null — so dropping the whole accessibility sub-record reached the method and returned immediately, releasing nothing. Ten of its eleven properties additionally had no per-property unset arm even when the bag survived.

This is the mirror image of #952: there the reset ran but used the wrong shape; here it never ran.

What changed

src/Reactor/Core/Reconciler.cs

Five Tier-1 unset arms in ApplyModifiers — ElementSoundMode, HeadingLevel, IsTabStop, TabIndex, XYFocusKeyboardNavigation. All use ClearValue(<DP>Property), never a default-value assignment: a local value outranks every Style setter in WinUI's precedence order, so an assignment would pin the default rather than hand the property back (#952). The Control-gated arms rebind their own pattern variable so a non-Control falling out of the set arm cannot hit the reset.

ApplyAccessibilityModifiers rewritten — the early return is now if (a is null && oldA is null) return;, and 11 new ClearValue arms cover HelpText, FullDescription, LandmarkType, AccessibilityView, IsRequiredForForm, LiveSetting, PositionInSet, SizeOfSet, Level, ItemStatus, and TabFocusNavigation. LabeledByRef / DescribedByRefs / FlowsToRefs / FlowsFromRefs already unwind through ApplyModifierReferenceEdges and are unchanged.

Deferred-LabeledBy staleness guard. When the target AutomationId is not yet in the tree, the LabeledBy path parks a Loaded handler. If the modifier was dropped before that handler ran, the reset arm's ClearValue was immediately undone and a label the caller no longer asks for got re-pinned. The in-flight request is now published as ReactorState.PendingLabeledBy before parking, the handler no-ops unless it still matches, and the field is reset alongside PendingEchoMatch in ClearCurrentEventHandlers, DetachReactorState, and the pool-return path.

Tests

tests/Reactor.Tests/AnalyzerTests/ModifierUnsetClearValueTests.cs — the existing scan proved every arm that exists has the right shape; nothing proved an arm exists. Three additions:

  • Every_Diff_Guarded_Modifier_Has_An_Unset_Arm collects every set arm in both methods and requires a matching unset arm, with a documented exception dictionary that also fails on a stale entry, so landing an arm forces its exemption to be deleted.
  • Every_Type_Gated_Write_Has_A_Matching_Type_Gated_Clear closes a blind spot in the above. That test asks a per-property question, so it is satisfied the moment a property has any reset at all — but several arms are if (fe is WinUI.X) … else if (fe is WinUI.Y) … type-dispatch chains that get widened one control type at a time (Apply the Padding modifier to TextBlock (#950) #970 added TextBlock to Padding; Widen panel Padding and CornerRadius modifier gates #1003 adds Grid/RelativePanel to Padding and Grid/StackPanel/RelativePanel to CornerRadius). Widening only the write half leaves a control type that can have the property set and never released — the same bug one type down, invisible to a property-level scan. This is also the standing merge hazard on this file: the two halves live in different hunks, so a rebase can auto-merge the widened write while the widened clear conflicts, and resolving that conflict in favour of either side alone reinstates the bug while the arm a reviewer reads first still looks correct.
  • Deferred_LabeledBy_Rechecks_Pending_Request structurally pins the staleness guard — the harness cannot hold Loaded open across a re-render, so the behavioural fixture takes the synchronous path on a warm machine and cannot cover it.

Non-vacuity floors are per-method (ApplyModifiers → 32, ApplyAccessibilityModifiers → 10, type-gated pairs → 10) rather than one global count.

tests/Reactor.AppTests.Host/SelfTest/Fixtures/ModifierEventFixtures.cs — the only oracle that distinguishes "cleared" from "assigned the default" is ReadLocalValue(dp) == DependencyProperty.UnsetValue, and headless xUnit cannot construct a WinUI object, so behaviour is pinned here. Five release checks added to ModifierClearResets (all five modifiers were already set in its phase-0 bag and never asserted on — exactly why the bug was invisible), plus a new AccessibilityModifierClearResets fixture that sets the full bag, drops individual properties, then drops the bag wholesale. Phase-0 "applied" assertions are split per-property so a broken set arm cannot hide inside a conjunction.

Docs

docs/_pipeline/templates/modifier-system.md.dt stated the reset rule as universal. It still is not (see below), so a caveat names the exception. Recompiled via mur docs compile --topic modifier-system.

Verification

  • 12/12 mutation checks CAUGHT. Each new arm was individually removed and the matching selftest check confirmed to flip to not ok; the IsTabStop and TabIndex set arms were also mutated to close vacuity on the phase-0 assertions. For the type-parity test, deleting a single clear branch while leaving its write branch in place reddens it and nothing else, naming the property and the orphaned type — verified both on this branch (Padding on StackPanel) and on the [Bug] Several common modifiers have no unset arm at all — dropping IsTabStop/TabIndex/Scale/Rotation/… leaves the last value pinned forever #986 + Widen panel Padding and CornerRadius modifier gates #1003 merge result (CornerRadius on Grid, the exact mutation that passed silently before).
  • Merge-checked against Widen panel Padding and CornerRadius modifier gates #1003 (azchohfi-widen-panel-modifier-gates), which edits the same method: auto-merges cleanly, and the full structural suite passes on the merge result.
  • dotnet build Reactor.slnx — succeeds, 0 errors.
  • dotnet test tests/Reactor.Tests --filter "…ModifierUnsetClearValueTests|…PoolResetSetConsistencyTests|…ModifierTableIntegrityTests" — 75/75 pass.
  • Selftests --filter "ModifierEvent" — 47/47 modifier-clear checks pass; --filter "ChartA11y" — 44/44 (confirms the new arms do not disturb the Charts: double-announcement risk with custom LabelView / TickLabelView #162 imperative subtree-hiding writes, which have no prior modifier and so never hit a set→unset transition).
  • Full selftest suite on an idle machine — 1402 checks, only the 2 pre-existing Issue487_SV2ParkedAtBottom / Issue487_SV2ClampObserved failures, which also fail on a clean merge-base tree.

Deliberately out of scope

`ApplyModifiers` writes a modifier only when it is present in the new bag.
Five common modifiers had no `else` arm at all, so dropping one from a chain
left the previous render's write pinned on the control forever:

  phase == 0 ? Button("Go", Go).IsTabStop(false)
             : Button("Go", Go)     // still not a tab stop

`ApplyAccessibilityModifiers` was worse. It opened with `if (a is null) return;`
while the caller invokes it precisely when `a11y is not null || oldA11y is not
null` — so dropping the *whole* accessibility sub-record reached the method and
returned immediately, releasing nothing. Ten of its eleven properties also had
no per-property unset arm even when the bag survived.

This is the mirror image of #952: there the reset ran but used the wrong shape;
here it never ran.

Changes
- `ApplyModifiers`: unset arms for `ElementSoundMode`, `HeadingLevel`,
  `IsTabStop`, `TabIndex`, `XYFocusKeyboardNavigation`. The two Control-gated
  arms rebind their own pattern variable (the existing `enCtrl`/`enCtrl2`
  shape) — reaching the `else` only proves the whole set condition was false,
  which a non-Control satisfies while still having the modifier set.
- `ApplyAccessibilityModifiers`: drop the early return, read every property
  through `a?.X`, and add `ClearValue` arms for the ten properties that lacked
  one. `LabeledBy` already had one; the `*Refs` edges unwind through
  `ApplyModifierReferenceEdges`.

Every reset uses `ClearValue(<DP>Property)`, never a default assignment: a
local value outranks every `Style` setter in WinUI's precedence order (#952).

Tests
- `ModifierUnsetClearValueTests` gains the positive scan the existing shape
  tests admitted they lacked — every diff-guarded set arm in both reconciler
  methods must have a matching unset arm. 49 modifiers are scanned today
  against a non-vacuity floor of 30, with a documented exception dictionary
  and a stale-exception assertion so entries cannot rot.
- Selftests pin the behaviour, since only `ReadLocalValue(dp) ==
  DependencyProperty.UnsetValue` distinguishes "released" from "assigned the
  default", and headless xUnit cannot construct a WinUI object.
  `ModifierClearResets` gains five release checks; a new
  `AccessibilityModifierClearResets` fixture covers apply / partial drop /
  whole-bag drop.
- Each new arm was mutation-checked: removing the five Tier-1 `ClearValue`
  calls flips exactly the five new checks; restoring the early return flips
  only the whole-bag-drop phase; removing the eleven a11y arms flips the
  per-property phases.

The transform family (`Scale`/`Rotation`/`Translation`/`CenterPoint`) is
deliberately excluded and tracked in #1001: those are facade DPs whose live
value sits on the composition visual, so `ClearValue` alone cannot undo an
animated write. They are recorded in the new exception dictionary rather than
silently tolerated.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 0533f073-1d93-4f3a-9e34-85f02b4ddaee
Follow-up to the multi-model pr-review pass on the issue #986 unset-arm work.

Two high-severity findings:

1. The deferred LabeledBy path parks a `Loaded` handler when the target
   AutomationId is not yet in the tree. If the modifier is dropped before that
   handler runs, the reset arm's ClearValue is immediately undone by the stale
   handler, re-pinning a label the caller no longer asks for. Publish the
   in-flight request as ReactorState.PendingLabeledBy before parking, and have
   the handler no-op unless it still matches. Reset it alongside PendingEchoMatch
   in ClearCurrentEventHandlers, DetachReactorState, and the pool-return path.

2. The ModifierClear_Tier1Applied phase-0 assertions were a single 10-clause
   conjunction, so a broken *set* arm could be masked. Split into five
   per-property checks that each assert a local value exists AND the intended
   non-default effective value; release checks now compare against the phase-0
   value rather than a guessed WinUI default.

Structural gate: per-method non-vacuity floors replace the single global arm
count, and a new Roslyn test pins the handler's pending-request re-check (the
harness cannot hold `Loaded` open across a re-render, so the behavioural fixture
takes the synchronous path on a warm machine).

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 0533f073-1d93-4f3a-9e34-85f02b4ddaee

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Fixes a long-standing reconciler correctness gap where several modifiers (and most Tier 2/3 accessibility modifiers) were written when present but never released when dropped, leaving prior render values pinned as local DP values. It also hardens deferred LabeledBy resolution so a parked Loaded handler can’t re-apply a label after the modifier has been removed or retargeted.

Changes:

  • Added missing per-modifier unset arms in Reconciler.ApplyModifiers (using ClearValue(<DP>Property)), and rewrote ApplyAccessibilityModifiers to handle whole-bag drops plus per-property clears.
  • Introduced a staleness guard for deferred LabeledBy resolution via ReactorState.PendingLabeledBy, cleared across teardown/pool paths.
  • Added structural unit tests to ensure diff-guarded set arms have matching unset arms, plus new/extended selftests to prove local values are actually released; updated docs to note the transform-modifier exception.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated no comments.

Show a summary per file
File Description
src/Reactor/Core/Reconciler.cs Adds missing modifier/a11y unset paths and a deferred-LabeledBy staleness guard via PendingLabeledBy.
tests/Reactor.Tests/AnalyzerTests/ModifierUnsetClearValueTests.cs Strengthens structural scanning to require unset-arm existence (with scoped exceptions) and pins the deferred-LabeledBy guard structurally.
tests/Reactor.AppTests.Host/SelfTest/Fixtures/ModifierEventFixtures.cs Extends modifier-clear fixture with non-vacuous “applied then cleared” checks, and adds an accessibility clear/reset fixture covering per-property and whole-bag drops.
tests/Reactor.AppTests.Host/SelfTest/SelfTestFixtureRegistry.cs Registers the new accessibility selftest fixture name in both discovery list and constructor switch.
docs/_pipeline/templates/modifier-system.md.dt Documents the current transform-modifier reset caveat (composition-backed facade properties).
docs/guide/modifier-system.md Compiled output reflecting the new caveat in the user guide.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@github-actions

github-actions Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

📦 Build metrics

Artifact sizes for 20aef88 vs the base branch (4095674).

Packages (compressed .nupkg)

Artifact base PR Δ
Microsoft.UI.Reactor.nupkg 1.60 MB 1.60 MB +845 B (+0.05%) ⚠️
Microsoft.UI.Reactor.Advanced.nupkg 478.5 KB 478.5 KB -3 B (0.00%) ≈
Microsoft.UI.Reactor.Devtools.nupkg 278.2 KB 278.2 KB -3 B (0.00%) ≈

Assemblies in Microsoft.UI.Reactor

Artifact base PR Δ
Reactor.Analyzers.dll 355.0 KB 355.0 KB +0 B (0.00%) ≈
Reactor.dll 2.38 MB 2.38 MB +1.00 KB (+0.04%) ≈
Reactor.Localization.Generator.dll 16.0 KB 16.0 KB +0 B (0.00%) ≈
Reactor.Wrappers.Abstractions.dll 10.5 KB 10.5 KB +0 B (0.00%) ≈
Reactor.Wrappers.Generator.dll 99.5 KB 99.5 KB +0 B (0.00%) ≈

Assemblies in Microsoft.UI.Reactor.Advanced

Artifact base PR Δ
Reactor.Advanced.dll 1014.5 KB 1014.5 KB +0 B (0.00%) ≈

Assemblies in Microsoft.UI.Reactor.Devtools

Artifact base PR Δ
Microsoft.UI.Reactor.Devtools.dll 777.5 KB 777.5 KB +0 B (0.00%) ≈

✅ smaller / ⚠️ larger / ≈ within noise. Sizes come from a Release dotnet pack on the CI runner: packages are the compressed .nupkg download size, assemblies the uncompressed DLL inside it.
workflow run.

Comment thread src/Reactor/Core/Reconciler.cs Fixed
@github-actions

github-actions Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

🧪 Merged coverage

Coverage for 20aef88 vs the base branch (4095674) — unit + selftest merged.

Metric base PR Δ
Line 85.76% 85.77% +0.01 pp ≈
Branch 77.10% (899/1166) 77.19% (900/1166) +0.09 pp ≈

No coverage change beyond the noise floor. ✅

✅ higher / ⚠️ lower / ≈ within noise. Δ is in percentage points; coverage is unit + selftest merged (Debug x64) on the CI runner. Cobertura reports attached to the workflow run as artifacts.

Every_Diff_Guarded_Modifier_Has_An_Unset_Arm asks a per-property question, so
it is satisfied the moment a property has any reset at all. Several arms are
type-dispatch chains (`if (fe is WinUI.X) ... else if (fe is WinUI.Y) ...`)
that get widened one control type at a time -- #970 added TextBlock to Padding,
#1003 adds Grid/RelativePanel to Padding and Grid/StackPanel/RelativePanel to
CornerRadius. Widening only the write half leaves a control type that can have
the property set and never released: the #986 bug one type down, invisible to a
property-level scan because the property's reset still exists for its original
types. That is also the standing merge hazard on this file, since the two halves
sit in different hunks and can auto-merge apart.

Verified by mutation, on this branch and on the #986+#1003 merge result:
deleting a single clear branch while leaving its write branch in place reddens
Every_Type_Gated_Write_Has_A_Matching_Type_Gated_Clear and nothing else, naming
the property and the orphaned type. The same mutation passed silently before.

Review comments:

- github-code-quality flagged `a` as dereferenced after a null check in
  ApplyAccessibilityModifiers. The compiler's flow analysis proves the accesses
  safe (`a?.X.HasValue == true` implies non-null, and the project builds with
  nullable warnings as errors), but CodeQL cannot, and the explicit form reads
  better. Twelve set arms now use `a is not null && a.X... ` directly. The unset
  arms are unchanged: `a?.X.HasValue != true` never dereferences. Behaviour is
  identical, re-confirmed by re-running the ItemStatus unset-arm mutation, which
  still flips all three of its checks.

- Removed the write-only `scanned` list from
  Every_Diff_Guarded_Modifier_Has_An_Unset_Arm. The stale-exception check reads
  `missing`, so `scanned` was dead.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 0533f073-1d93-4f3a-9e34-85f02b4ddaee
Copilot AI review requested due to automatic review settings July 31, 2026 23:29

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 6 out of 6 changed files in this pull request and generated no new comments.

Suppressed comments (2)

docs/guide/modifier-system.md:123

  • The transform-modifier caveat is phrased as if these always bypass the XAML property system and as if ClearValue can never release a local value; in reality AnimationHelper.SetOrAnimateVector3 sets the facade DP directly when no animation curve is ambient, and only switches to compositor animations under .Animate() / WithAnimation. Also, the suggested identity resets omit CenterPoint, which is part of the exception list.
> **Caveat:** The four transform modifiers are the current exception. `.Scale()`,
> `.Rotation()`, `.Translation()` and `.CenterPoint()` write through the
> element's composition visual rather than through the XAML property
> system, so `ClearValue` has nothing to release and dropping one leaves
> the last value on the element. Until that is fixed, reset them by writing

docs/_pipeline/templates/modifier-system.md.dt:96

  • Same caveat issue as in the compiled doc: the explanation should be scoped to the animated/compositor path (ambient .Animate() / WithAnimation curve), and the identity-reset examples should include CenterPoint since it's listed as an affected modifier.
<!-- ai:caveat -->
The four transform modifiers are the current exception. `.Scale()`,
`.Rotation()`, `.Translation()` and `.CenterPoint()` write through the
element's composition visual rather than through the XAML property
system, so `ClearValue` has nothing to release and dropping one leaves

Five `github-code-quality` findings on PR #1018.

LINQ shape (3 findings) - the three scanner loops in
ModifierUnsetClearValueTests filtered with `continue` guards instead of a
predicate:

* `Every_Type_Gated_Write_Has_A_Matching_Type_Gated_Clear` - replaced
  `TryReadTypeGate(if, out string, out string) : bool` with
  `ReadTypeGate(if) : (string TypeName, string Variable)?` so the gate can be
  projected and filtered rather than tested with an `out`-param guard.
* `ReadUnsetModifierNames` / `ReadDiffGuardedModifiers` - folded the guards
  into `.Where(...)` predicates.

Phase-0 coupling (2 findings) - `initial.IsTabStop == false` and
`button.IsTabStop != false` were flagged as boolean-literal comparisons. The
literal is the *phase-0 bag value*, not a predicate: the release check asserts
the effective value moved away from what the bag wrote, deliberately not
towards a guessed WinUI default (guessing it once already produced a false
failure in this suite). Collapsing to `!initial.IsTabStop` would have broken
the five-row parallel table and hidden that coupling. Introduced
`const bool Phase0IsTabStop` and wired it through the bag *and* both checks,
so the coupling is now enforced by the compiler rather than only described in a
comment.

Mutation-verified after the refactor - both scanners still redden:

* drop the `StackPanel` Padding clear -> type-parity test fails with
  `[Padding on StackPanel]`
* drop the whole `IsTabStop` unset arm -> existence test fails with
  `[ApplyModifiers.IsTabStop]`

Unit 7/7, selftest `--filter ModifierEvent` 150 ok / 0 not ok.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 0533f073-1d93-4f3a-9e34-85f02b4ddaee
Copilot AI review requested due to automatic review settings July 31, 2026 23:56

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 6 out of 6 changed files in this pull request and generated no new comments.

Suppressed comments (1)

src/Reactor/Core/Reconciler.cs:4351

  • In the deferred LabeledBy Loaded handler, PendingLabeledBy is cleared before checking whether FindByAutomationId actually resolves. If deferred is still null (or if multiple parked handlers run in the same Loaded event), this can prematurely cancel the pending request and prevent a later handler from completing the resolution.
                    fe.Loaded -= OnLoaded;
                    if (!TryGetReactorState(fe, out var pending) || pending.PendingLabeledBy != labelId)
                        return;
                    pending.PendingLabeledBy = null;
                    var deferred = FindByAutomationId(fe, labelId);
                    if (deferred is not null)
                        Microsoft.UI.Xaml.Automation.AutomationProperties.SetLabeledBy(fe, deferred);

Round-3 Copilot review raised a *suppressed* finding (no inline thread) on the
deferred LabeledBy Loaded handler: clearing `PendingLabeledBy` before checking
whether `FindByAutomationId` resolves could `prematurely cancel the pending
request`, including when `multiple parked handlers run in the same Loaded
event`.

The finding is incorrect as stated. The handler unsubscribes itself as its first
statement, so it fires at most once - there is no later handler for the same
request to prevent, and once it has run the token no longer describes anything
outstanding whether or not the target resolved. Leaving it set on failure would
make the token assert a parked handler that does not exist.

The multi-handler case is real but already safe: the set arm's
`a.LabeledBy != oldA?.LabeledBy` diff guard means a second park always carries
a *different* labelId, so the stale handler's `PendingLabeledBy != labelId`
check returns before it can touch the live request's token.

But that safety rests entirely on statement *ordering*, and nothing pinned it.
Hoist the retirement above the staleness guard and the stale handler cancels the
live one, which then no-ops and leaves the label unresolved - the reviewer's
scenario, reachable by a plausible edit. So the concern is now guarded.

The first oracle for this was vacuous. Keying on the first `return` in the
handler body passes under the hoist mutation, because the handler opens with an
unrelated `TryGetReactorState` bail-out that still sorts before the clear.
Replaced with a syntax-span comparison between the if-statement whose condition
names `labelId` and the `PendingLabeledBy = null` assignment.

Mutation-verified: hoisting the retirement above the staleness guard fails the
test; the string-index version passed the same mutation.

Unit 7/7, `dotnet build Reactor.slnx` exit 0.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 0533f073-1d93-4f3a-9e34-85f02b4ddaee
Copilot AI review requested due to automatic review settings August 1, 2026 00:10
@azchohfi

Copy link
Copy Markdown
Collaborator Author

Re: the suppressed comment on src/Reactor/Core/Reconciler.cs:4351

Responding here because this finding was emitted inside the review body's <details>Suppressed comments (1)</details> block, so there is no inline thread to reply on.

The finding as stated is incorrect, but it pointed at a real unguarded invariant, so I've pinned it. Addressed in 68cedec.

"prevent a later handler from completing the resolution" — the handler unsubscribes itself as its first statement (fe.Loaded -= OnLoaded;), so it fires at most once. There is no later handler for this request to prevent. Whether or not we clear the token, this request will never be retried. And once the handler has run, the token — which means "a parked handler is outstanding for this labelId" — is false regardless of whether the target resolved. Leaving it set on the deferred is null path would make it assert a parked handler that doesn't exist, which is the state the unset arm at :4356 clears precisely to cancel.

"multiple parked handlers run in the same Loaded event" — this can happen, but it's already safe, and the reason is worth stating: the set arm is diff-guarded on a.LabeledBy != oldA?.LabeledBy, so a second park necessarily carries a different labelId. On Loaded the handlers run in subscription order, so the stale one runs first, hits pending.PendingLabeledBy != labelId, and returns before reaching the clear. It cannot cancel the live request's token.

What was genuinely worth fixing: that safety rests entirely on statement ordering, and nothing pinned it. Move the retirement above the staleness guard and the stale handler cancels the live one, which then sees a null token, no-ops, and leaves the label unresolved forever — exactly the failure you describe, just reachable by a future edit rather than present today. Deferred_LabeledBy_Rechecks_Pending_Request now asserts the ordering.

One note on the fix, because the first attempt at it was wrong. My initial oracle compared string indexes of "return" and "PendingLabeledBy = null". It passed under the hoist mutation — the handler opens with an unrelated TryGetReactorState bail-out whose return still sorts before the clear, so the assertion was vacuous for the exact bug it was written to catch. Replaced with a syntax-span comparison between the IfStatementSyntax whose condition names labelId and the PendingLabeledBy = null AssignmentExpressionSyntax:

Assert.True(stalenessGuard!.Span.End < retire!.SpanStart, ...);

Mutation-verified both ways: the span version fails on the hoist, the string-index version passed it.

dotnet build Reactor.slnx exit 0, unit 7/7.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 6 out of 6 changed files in this pull request and generated no new comments.

Suppressed comments (3)

src/Reactor/Core/Reconciler.cs:4332

  • Avoid allocating a new ReactorState in the synchronous LabeledBy resolution path. GetOrCreateReactorState(fe) will allocate and attach ReactorState even when there was never a deferred request, but the only thing needed here is to clear an existing PendingLabeledBy from a prior deferral.
                // Resolved synchronously — retire any deferred request from an
                // earlier render so its parked handler can't overwrite this one.
                GetOrCreateReactorState(fe).PendingLabeledBy = null;
                Microsoft.UI.Xaml.Automation.AutomationProperties.SetLabeledBy(fe, target);

docs/_pipeline/templates/modifier-system.md.dt:95

  • This caveat lists four transform modifiers but only provides explicit identity-value examples for three of them. Including an example for CenterPoint would make the guidance complete and prevent readers from assuming omitting .CenterPoint(...) is safe while the other three are not.
The four transform modifiers are the current exception. `.Scale()`,
`.Rotation()`, `.Translation()` and `.CenterPoint()` write through the
element's composition visual rather than through the XAML property
system, so `ClearValue` has nothing to release and dropping one leaves
the last value on the element. Until that is fixed, reset them by writing
the identity value explicitly — `.Scale(1f)`, `.Rotation(0f)`,
`.Translation(0f, 0f, 0f)` — rather than by omitting the call.

docs/guide/modifier-system.md:123

  • This caveat lists four transform modifiers but only gives explicit identity-value reset examples for three; consider adding a CenterPoint identity example so the guidance is complete.
> **Caveat:** The four transform modifiers are the current exception. `.Scale()`,
> `.Rotation()`, `.Translation()` and `.CenterPoint()` write through the
> element's composition visual rather than through the XAML property
> system, so `ClearValue` has nothing to release and dropping one leaves
> the last value on the element. Until that is fixed, reset them by writing
> the identity value explicitly — `.Scale(1f)`, `.Rotation(0f)`,
> `.Translation(0f, 0f, 0f)` — rather than by omitting the call.

…nt CenterPoint identity

Three *suppressed* findings from the round-4 Copilot review (again emitted in the
review body with no inline thread). All three are correct.

**Reconciler.cs:4332** - the synchronous LabeledBy resolution path called
`GetOrCreateReactorState(fe).PendingLabeledBy = null`, which allocates and
attaches a ReactorState even when there was never a deferral. Synchronous
resolution is the *common* path - deferral only happens when the element is not
yet in the visual tree - so this cost one attached state per element that ever
resolves a LabeledBy. With no state there is no parked handler and nothing to
retire, so `TryGetReactorState` is both cheaper and semantically identical.
This now matches the shape already used by the unset arm below it.

**modifier-system template + generated guide** - the transform caveat named four
modifiers but spelled identity resets for only three, which invites the reader to
assume `.CenterPoint()` is safe to omit while the other three are not. Added
`.CenterPoint(Vector3.Zero)`, and noted that unlike `.Translation()` it has
no component-wise overload - the reason the example was easy to leave out.

Edited the `.md.dt` template and regenerated via `mur docs compile --topic
modifier-system`; the generated diff is the four intended lines with no snippet
churn.

Selftests after the Reconciler change: ModifierEvent 150 ok, ChartA11y 181 ok,
Accessibility 28 ok, 0 not-ok across all three. Unit 7/7.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 0533f073-1d93-4f3a-9e34-85f02b4ddaee
Copilot AI review requested due to automatic review settings August 1, 2026 00:25
@azchohfi

Copy link
Copy Markdown
Collaborator Author

Re: the three suppressed comments on the round-4 review

Again replying here — all three were emitted inside <details>Suppressed comments (3)</details> with no inline threads. All three are correct and all three are fixed in aa27d69.

1. Reconciler.cs:4332 — GetOrCreateReactorState on the synchronous path. Agreed, and this one matters more than it looks. Synchronous resolution is the common path — deferral only happens when the element isn't in the visual tree yet — so this was allocating and attaching a ReactorState for every element that ever resolves a LabeledBy, purely to null out a field that in the overwhelming majority of cases was already null. With no state there is no parked handler and nothing to retire, so the TryGet form is semantically identical:

if (TryGetReactorState(fe, out var resolvedState))
    resolvedState.PendingLabeledBy = null;

This also makes it consistent with the unset arm 25 lines below, which already used TryGetReactorState for exactly the same job. Good catch.

2 & 3. The CenterPoint identity example. Also correct — the caveat named four modifiers and spelled resets for three, which is precisely the shape that invites "the fourth must be fine". Added .CenterPoint(Vector3.Zero).

One thing worth adding beyond the suggestion: .CenterPoint() takes only a Vector3 and has no component-wise overload, unlike .Translation(0f, 0f, 0f). That asymmetry is almost certainly why the example was easy to omit in the first place, so the caveat now says so explicitly rather than leaving the next reader to discover it at the compiler.

Fixed in the .md.dt template and regenerated with mur docs compile --topic modifier-system — the generated diff is the four intended lines with no unrelated snippet churn.

Validation after the Reconciler.cs change: ModifierEvent 150 ok, ChartA11y 181 ok, Accessibility 28 ok — 0 not-ok across all three. Unit 7/7.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 6 out of 6 changed files in this pull request and generated no new comments.

Suppressed comments (2)

tests/Reactor.AppTests.Host/SelfTest/Fixtures/ModifierEventFixtures.cs:1425

  • WaitFor(() => ReferenceEquals(AP.GetLabeledBy(applied), labelSource())) can return true when both sides are null (e.g., labelSource not yet discoverable and LabeledBy not yet resolved), causing an immediate return and a potential false failure/flakiness. Make the predicate require a non-null source inside the same lambda so it can't short-circuit on null/null.
                var resolved = await Harness.WaitFor(() =>
                    ReferenceEquals(AP.GetLabeledBy(applied), labelSource()));
                H.Check("A11yClear_Phase0_LabeledByResolved",
                    resolved && labelSource() is not null);

tests/Reactor.AppTests.Host/SelfTest/Fixtures/ModifierEventFixtures.cs:714

  • ModifierClear_IsTabStopCleared asserts button.IsTabStop != Phase0IsTabStop in addition to ReadLocalValue(...) == UnsetValue. If a Button’s themed/default effective value happens to equal the phase-0 value (e.g., false), this will fail even though the local value was correctly cleared. The phase-0 ModifierClear_Tier1Applied_IsTabStop check already proves the set arm landed, so the clear check can rely on the local-value oracle alone.
                H.Check("ModifierClear_IsTabStopCleared",
                    button.ReadLocalValue(UIElement.IsTabStopProperty) == DependencyProperty.UnsetValue
                    && button.IsTabStop != Phase0IsTabStop);

…ts non-vacuity guard

Two more *suppressed* findings (round 5, again no inline threads). Both correct.

**The WaitFor short-circuit is a real flake.** The predicate was
`ReferenceEquals(AP.GetLabeledBy(applied), labelSource())`, and my own comment
directly above it asserted this was `false at t=0 and converging, which is the
one shape WaitFor is sound for`. That was wrong: `ReferenceEquals(null, null)`
is **true**, so with the label source not yet discoverable and LabeledBy not yet
resolved the wait returned immediately at zero elapsed time - having never
waited - and the following check then failed spuriously on a still-null source.
The predicate now requires the source inside the same lambda, which is what makes
it genuinely eventual. This is the exact trap AGENTS.md documents for WaitFor;
the comment claiming soundness made it harder to spot, not easier.

**The release checks conflated two different failures.** Each read
`ReadLocalValue(...) == UnsetValue && <effective> != <phase-0 value>`. The
first clause is the product oracle; the second is a non-vacuity guard against a
phase-0 value that happens to equal the control's default. Folded together, a
fixture-design problem presented as a reconciler regression. Split into five
`ModifierClear_*Cleared` checks (local-value oracle alone, as suggested) and
five `ModifierClear_*Phase0WasDistinct` checks. The guard is kept rather than
dropped - without it a property whose default already equals the phase-0 value
would satisfy the release oracle trivially - but a `*Cleared` failure now means
a product bug unambiguously.

Applied to all five properties, not just the flagged `IsTabStop`: the shape
occurred five times and the concern is structural.

Mutation-verified: dropping the `IsTabStop` unset arm reddens
`ModifierClear_IsTabStopCleared`, so the split did not weaken the oracle.

Selftest `--filter ModifierEvent` 155 ok / 0 not-ok (150 before, +5 new
checks), including all 14 `A11yClear_*`. ChartA11y 181 ok.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 0533f073-1d93-4f3a-9e34-85f02b4ddaee
Copilot AI review requested due to automatic review settings August 1, 2026 00:39

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 6 out of 6 changed files in this pull request and generated no new comments.

Every_Type_Gated_Write_Has_A_Matching_Type_Gated_Clear carried a
non-vacuity floor of `pairs >= 10` and a comment claiming 14 pairs.
The oracle actually reads 28 pairs over 11 properties, so the floor
tolerated losing 18 of them.

That slack covered the exact arms the test exists for: dropping the
Padding (6) and CornerRadius (5) chains outright still reports 17 and
passes, and those are the two properties #970, #986 and #1003 each
widened. A resolution that lost both chains was certified green.

Raise the floor to 24 -- the loss of either chain now trips it, with
four arms of slack for a legitimate narrowing, matching the ratio the
per-method MinArms floors already use.

Boundary-verified against the oracle's own count rather than a
re-derivation: removing 4 CornerRadius arms leaves 24 and passes,
removing 5 leaves 23 and fails. A line-scoped text scan reports 22
here because it misses writes nested inside a gate's block, so the
comment now says to read the number out of the assertion message.

Comment and constant only; no product code and no Reconciler.cs change.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 0533f073-1d93-4f3a-9e34-85f02b4ddaee
Copilot AI review requested due to automatic review settings August 1, 2026 22:06

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 6 out of 6 changed files in this pull request and generated no new comments.

Every_Type_Gated_Write_Has_A_Matching_Type_Gated_Clear had a floor over the
write side only. A failure confined to ReadClearedProperties therefore left
pairs at 28 (floor green) while emptying clears, so every property took
the continue and offenders came out empty -- both arms of the test
reporting that nothing was wrong. ReadClearedProperties has exactly one call
site, so nothing else in the suite covered it.

Measured, not argued: breaking that reader alone and rebuilding produced
Failed: 0, Passed: 7. With the clear-side floor it produces
"Only 0 type-gated modifier clear(s) ... while the write side still reads 28".

The population is read through this test's own parser rather than a text scan
-- 28 clears over the same 11 properties, mirroring the writes exactly -- and
the floor is calibrated identically to its sibling, so losing either of the
two longest chains (Padding 6, CornerRadius 5) trips it.

Test-only. No product code; Reconciler.cs deliberately untouched.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 0533f073-1d93-4f3a-9e34-85f02b4ddaee
Copilot AI review requested due to automatic review settings August 2, 2026 01:00

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 6 out of 6 changed files in this pull request and generated no new comments.

The comment on the `clears.TryGetValue` continue claimed "several properties
legitimately clear through an ungated fe.ClearValue(...)". Measured through the
test's own parser, zero properties do: all 11 written properties are present in
`clears`, so the skip count is 0.

Two mutations settle what the branch is actually for:

  delete an unset arm, keep the write  -> Every_Diff_Guarded_Modifier_Has_An_
                                          Unset_Arm fails naming the property
  keep the arm, move the clear to an
  ungated fe.ClearValue(...)           -> 7/7 green, correctly: the property is
                                          still released, it is just no longer a
                                          type-dispatch chain to compare against

So the missing-arm case is covered by the sibling test, and the branch exists
only for the ungated-but-correct shape. Left as a continue rather than tightened
into an assertion: asserting the skip count is zero would fail on that correct
shape, and the obvious remediation would be to re-gate a clear that never needed
gating - churn in Reconciler.cs to fix nothing.

Comment only; no assertion or logic change (0 non-comment lines in the diff).

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 0533f073-1d93-4f3a-9e34-85f02b4ddaee
Copilot AI review requested due to automatic review settings August 2, 2026 01:14

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 6 out of 6 changed files in this pull request and generated no new comments.

Suppressed comments (1)

tests/Reactor.Tests/AnalyzerTests/ModifierUnsetClearValueTests.cs:112

  • The test name Every_ApplyModifiers_Unset_Arm_Clears_The_Dependency_Property is now misleading: ReadUnsetArms() scans both ApplyModifiers and ApplyAccessibilityModifiers, not just ApplyModifiers. Renaming it to reflect the broader scope will make future failures easier to interpret.
    [Fact]
    public void Every_ApplyModifiers_Unset_Arm_Clears_The_Dependency_Property()
    {

Every_Type_Gated_Write_Has_A_Matching_Type_Gated_Clear skipped any property
absent from its `clears` map. That map is gate-bound, so a property whose whole
unset arm was deleted vanished from it and was never compared -- the test
certified the exact defect it exists to catch.

The per-property sibling does not cover the gap. Its exclusion list names the
three modifiers that compute a local before testing it (Margin, Padding,
BorderThickness), whose conditions never mention `m.X`. Measured: deleting
BorderThickness's whole unset arm while keeping both type-gated writes left all
seven tests in this file green -- sibling excludes it, write floor untouched at
28, clear floor falls only 28 -> 26 against a floor of 24.

Read ungated clears too and classify three ways instead of skipping: a
type-gated chain is compared as before, an ungated `fe.ClearValue(...)` is
accepted, and neither is an offender. Asserting nothing was skipped would have
been wrong -- the ungated shape is semantically correct and would false-fail,
and its obvious remediation is to re-gate a clear that never needed gating, in
the most contended file in the repo.

Mutation-verified both directions on the same property, with the aim measured
out of band through the oracle's own parser:
  arm deleted, write kept   gated 2->0, ungated 0  -> RED,   names [BorderThickness]
  clear made ungated        gated 2->0, ungated 1  -> GREEN, no false positive
Reconciler.cs restored byte-identical after each arm; suite 13130/0/64.

Refs #986

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 0533f073-1d93-4f3a-9e34-85f02b4ddaee
Copilot AI review requested due to automatic review settings August 2, 2026 01:30

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 6 out of 6 changed files in this pull request and generated no new comments.

Suppressed comments (1)

tests/Reactor.Tests/AnalyzerTests/ModifierUnsetClearValueTests.cs:123

  • The non-vacuity guard in Every_ApplyModifiers_Unset_Arm_Clears_The_Dependency_Property only checks arms.Count >= 20. Since ReadUnsetArms() now scans both ApplyModifiers and ApplyAccessibilityModifiers, this can still pass if the scanner silently stops recognizing one method (e.g., all a11y unset arms drop out) while the other method keeps the total above 20 — leaving this test blind to default-value assignments in the missing method.
        // A parser that finds nothing would make every assertion below vacuous. The two
        // methods have ~45 unset arms today; 20 is a floor that survives ordinary churn but
        // not a shape change that silently stops matching.
        Assert.True(
            arms.Count >= 20,
            $"Only {arms.Count} modifier-unset arm(s) were read out of the reconciler. " +
            "The unset-transition shape ('!m.X.HasValue && oldM?.X.HasValue == true' or " +
            "'m.X is null && oldM?.X is not null') has probably changed, which would make this " +
            "whole test pass without checking anything.");

ReadUnsetArms() scans ApplyModifiers AND ApplyAccessibilityModifiers, but three
identifiers still carried an ApplyModifiers-only name. A coverage auditor reading
them would conclude the accessibility half is unscanned.

  Every_ApplyModifiers_Unset_Arm_Clears_The_Dependency_Property
    -> Every_Unset_Arm_Clears_The_Dependency_Property
  Every_ApplyModifiers_Unset_Arm_Actually_Resets_Something
    -> Every_Unset_Arm_Actually_Resets_Something
  ApplyModifiersAssignmentExceptions
    -> UnsetArmAssignmentExceptions

The dictionary was not merely broad but backwards: its sole entry,
PendingLabeledBy, occurs five times in ApplyAccessibilityModifiers and zero
times in ApplyModifiers. The mutation that removes that entry reports the
offender as `ApplyAccessibilityModifiers.LabeledBy`, i.e. the excluded method.

Tests only; no product code. 7/7 pass and the removed-entry mutation reddens
exactly one, so the renamed dictionary is still consulted.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 0533f073-1d93-4f3a-9e34-85f02b4ddaee
Copilot AI review requested due to automatic review settings August 2, 2026 01:42

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 6 out of 6 changed files in this pull request and generated no new comments.

The unset-arm scan covers both ApplyModifiers and ApplyAccessibilityModifiers,
but its only non-vacuity guard was a single combined `arms.Count >= 20` on one
caller. ApplyModifiers alone contributes 36 arms, so that floor cleared on its
own: if the matcher stopped recognizing ApplyAccessibilityModifiers, all 12 of
its arms could vanish and the test stayed green.

Every_Unset_Arm_Actually_Resets_Something consumes the same helper and had no
floor at all -- strictly worse than the reported case, and not reported.

The floor now lives inside ReadUnsetArms and is per method, so both current
callers and any future one inherit it, and the failure message names the
method and its count. The existing per-method MinArms floors did not cover
this: ReadUnsetArms discarded MinArms, and that floor governs the set-arm
scan in a different test over a different population.

Measured unset-arm counts 36 (ApplyModifiers) and 12
(ApplyAccessibilityModifiers); floors 31 and 10, matching the ratios the
existing floors in this file already use (32/37, 10/12, 24/28).

Mutation receipt -- made the accessibility bag identifiers unmatchable:
both consumers failed with "Only 0 modifier-unset arm(s) were read out of
ApplyAccessibilityModifiers (expected at least 10)"; the removed combined
floor would have read 36 >= 20 and passed. Restored byte-equal, 7/7.

Tests only; no product code, and Reconciler.cs is deliberately untouched.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 0533f073-1d93-4f3a-9e34-85f02b4ddaee
Copilot AI review requested due to automatic review settings August 2, 2026 01:54

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 6 out of 6 changed files in this pull request and generated no new comments.

@azchohfi
Alexandre Zollinger Chohfi (azchohfi) merged commit a861bed into main Aug 4, 2026
22 checks passed
@azchohfi
Alexandre Zollinger Chohfi (azchohfi) deleted the azchohfi-modifier-unset-arms branch August 4, 2026 05:37
Alexandre Zollinger Chohfi (azchohfi) pushed a commit that referenced this pull request Aug 4, 2026
…ol-control-panel-resets

Three files conflicted.

CHANGELOG.md and ModifierEventFixtures.cs are unions: both sides appended
bullets under the same `### Fixed` heading, and both added `using` aliases.
Nothing dropped from either side.

ModifierUnsetClearValueTests.cs is structural. #1018 renamed three members and
generalised `ReadUnsetArms` from a single-method 2-tuple to a multi-method
3-tuple driven by `ScannedMethods`; my side added seven members for the pool
half. The two addition sets are disjoint -- zero name collisions -- and none of
mine calls `ReadUnsetArms`, so theirs supersedes mine outright rather than
needing a pick.

`ReadCleanElementCommonBlock` takes #1018's Roslyn form. It is not a
preference: the auto-merged region above the conflict had already replaced my
regex method-location with their syntax walk, leaving my hunk referencing a
`braceStart` that no longer exists. Their `SwitchStatementSyntax` lookup
also removes outright the residual my comment documented at length -- a block
comment whose inner line began with the dispatch keyword could satisfy
`^\s*switch` and silently truncate the region. A syntax node cannot match a
comment, so the hazard is gone rather than described. The comment is replaced
with a shorter note recording why, and the four presence-shaped detectors it
warned against deleting are still named in the remarks above.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: d1564805-7a78-452e-9c6e-ad1c81947d4d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Several common modifiers have no unset arm at all — dropping IsTabStop/TabIndex/Scale/Rotation/… leaves the last value pinned forever

2 participants