Repository navigation
[XAML] Reconcile x:Name after structural Hot Reload updates - #37897
Conversation
Reconcile root namescope registrations and existing generated x:Name fields when structural hot reload recreates a subtree. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: c30817d7-694e-4593-8efc-dc56ecfaeba1
|
🚀 Dogfood this PR with:
curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 37897Or
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 37897" |
|
Azure Pipelines: Successfully started running 1 pipeline(s). There may be pipelines that require an authorized user to comment /azp run to run. |
Keep StyleId initialization independent from generated-field availability during structural hot reload. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: c30817d7-694e-4593-8efc-dc56ecfaeba1
There was a problem hiding this comment.
Pull request overview
This pull request updates the source-generated XAML Hot Reload patch generation to reconcile newly created elements with the page’s root namescope and existing x:Name-backed fields after structural subtree replacement, and adds a regression test covering an ancestor layout type swap scenario.
Changes:
- Emit namescope reconciliation for newly created elements during structural Hot Reload patches (register/replace name registrations; set
transientNamescope; restoreStyleId; reassign an existing named field when applicable). - Thread prior-root context into patch generation so field reassignment can be limited to names that existed before the update.
- Add a SourceGen Hot Reload regression test validating that the visible element, generated field, and
FindByNameresolve to the same instance after a structural update.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
| src/Controls/tests/SourceGen.UnitTests/HotReload/AiAssisted/StructuralHotReloadTests.cs | Adds a regression test for structural Hot Reload ensuring x:Name field and namescope resolve to the visible replacement element after an ancestor layout type change. |
| src/Controls/src/SourceGen/UpdateComponentCodeWriter.cs | Extends patch generation to reconcile namescopes and (when safe) reassign existing x:Name-generated fields for newly created elements in structural patches. |
| src/Controls/src/SourceGen/InitializeComponentCodeWriter.cs | Passes the prior parsed XAML root into patch generation so existing x:Name field eligibility can be computed from the pre-update tree. |
Persist the originally generated field set across chained edits and unregister removed root-scope names before structural reconstruction. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: c30817d7-694e-4593-8efc-dc56ecfaeba1
This comment has been minimized.
This comment has been minimized.
MauiBot
left a comment
There was a problem hiding this comment.
Expert Review — 6 findings
See inline comments for details.
kubaflo
left a comment
There was a problem hiding this comment.
Could you please check the ai's suggestions?
Align generated-field discovery with code-behind boundaries, retain field types, and make namescope cleanup identity-safe. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: c30817d7-694e-4593-8efc-dc56ecfaeba1
This comment has been minimized.
This comment has been minimized.
MauiBot
left a comment
There was a problem hiding this comment.
Expert Review — 3 findings
See inline comments for details.
| { | ||
| bool isRoot = string.IsNullOrEmpty(change.ParentNodeId); | ||
|
|
||
| if (change.RemovedNames.Count > 0 |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
if (XamlComponentRegistry.TryGet(this, "{ParentNodeId}", out var __rp_N)) guard that is opened a few lines below, and outside the if (__lok_N) / contentPropertyName == null skip paths.
Concrete failure: when the parent node is not in the component registry (or a retained child probe fails, or the container is neither a Layout nor has a content property), the whole child-list change is intentionally skipped — the B5 comment right below says a missing parent "only skips this change rather than aborting the whole method". But the generated __removedNameScope_N.UnregisterName("Foo") calls have already run unconditionally. The elements are still in the live visual tree (nothing was removed), yet FindByName("Foo"), {x:Reference Foo} and VSM name lookups now fail for a control that is still on screen — a state that no full re-inflation can produce and that the next patch will not repair (the name is only re-registered when the element is re-created).
Note also that the existing XamlComponentRegistry.Unregister(this, "id") cleanup for the same removals is emitted inside the parent guard, so removal-side cleanup is now split across two different guard scopes. Emitting this block after the parent TryGet (and, for layouts, inside the if (__lok_N) block) keeps namescope state consistent with registry state and with whether the removal actually happened.
| codeWriter.WriteLine($"&& global::System.Object.ReferenceEquals({removedNameScopeVar}.FindByName(\"{escapedName}\"), {removedElementVar}))"); | ||
| codeWriter.Indent--; | ||
| using (PrePost.NewBlock(codeWriter)) | ||
| codeWriter.WriteLine($"{removedNameScopeVar}.UnregisterName(\"{escapedName}\");"); |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
💡 Suggestion — The removal path unregisters the name from the namescope but never resets the generated field, so the field and the namescope disagree after a remove-only edit.
Scenario (exactly the middle step of RemovedThenReaddedName_ReconcilesOriginalGeneratedField, which asserts FindByName is null but never asserts anything about the field): v1 has <Label x:Name="StructureCounterLabel"/>, v2 deletes it. After the patch, page.FindByName<Label>("StructureCounterLabel") is null (correct), but this.StructureCounterLabel still points at the detached Label. Code-behind such as StructureCounterLabel.Text = ... keeps silently mutating an orphan that is no longer in the tree (no visible effect, no exception), and the removed subtree stays rooted by the page field for as long as the page lives. A fresh inflation of v2 would leave that field null.
If the field is reset here it should be guarded by the same identity check already used for the namescope (ReferenceEquals(this.<field>, __removedNamedElement_N_M)) so a name that moved to a new element in the same patch is not clobbered, and assigned as null! to avoid CS8625 in nullable-enabled projects. At minimum, the divergence deserves a test that pins the intended field behavior across a remove-only edit.
| && property.LocalName == "VisualStateManager.VisualStateGroups"; | ||
|
|
||
| static bool IsVisualStateFieldExcluded(ElementNode element, INode? parent) | ||
| => parent is IListNode |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
💡 Suggestion — IsVisualStateFieldExcluded matches on element.XmlType.Name is "VisualStateGroup" or "VisualState" without checking the namespace, unlike every other boundary check added here (IsFieldBoundary uses XmlType.IsOfAnyType, which rejects non-MAUI namespaces, and the new GeneratedFields_UseNamespaceAwareBoundaries test asserts exactly that property for local:Style).
Consequence: a user type named VisualState/VisualStateGroup from a clr-namespace xmlns that appears as a list item (e.g. <local:StateList><local:VisualState x:Name="Foo"/></local:StateList>) is dropped from the seed, even though CodeBehindCodeWriter.GetNamedFields — whose XPath only excludes descendants of DataTemplate/ControlTemplate/Style/VisualStateManager.VisualStateGroups in the MAUI namespaces — does generate a field for it. The seed then under-reports a field that exists on the live type, so a later structural re-add of Foo silently skips this.Foo = ... and the field stays stale. Real VisualStateGroup/VisualState nodes are already excluded by the VisualStateManager.VisualStateGroups property boundary above, so adding the namespace check (or reusing IsOfAnyType) only removes the divergence.
MauiBot
left a comment
There was a problem hiding this comment.
AI Review Summary
@StephaneDelcroix — new AI review results are available based on commit
9d1a975.
🗂️ Review Sessions — click to expand
🚦 Gate — Test Before & After Fix
Gate Result: ⚠️ INCONCLUSIVE
Platform: ANDROID · Base: net11.0 · Merge base: e4b0c0a1
🩺 Base branch does not compile — the without-fix build failed. The gate's "does the test fail without the fix" check is unreliable here; this usually means main is broken or a merge-base file went missing. Investigate before trusting this gate.
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlNodeDiffTests.cs(301,73): error CS1061: 'ChildListChangeDiff' does not contain a definition for 'RemovedNames' and no accessible extensio...
| Test | Without Fix (expect FAIL) | With Fix (expect PASS) |
|---|---|---|
🧪 MainPage MainPage |
🛠️ BUILD ERROR | 🔍 NO MATCH |
🧪 UpdateComponentCodeWriterTests UpdateComponentCodeWriterTests |
🛠️ BUILD ERROR | ✅ PASS — 19s |
🧪 XamlIncrementalHotReloadPipelineTests XamlIncrementalHotReloadPipelineTests |
🛠️ BUILD ERROR | ✅ PASS — 21s |
🧪 XamlNodeDiffTests XamlNodeDiffTests |
🛠️ BUILD ERROR | ✅ PASS — 14s |
🔴 Without fix — 🧪 MainPage: 🛠️ BUILD ERROR · 69s
Error-relevant lines (filtered from the build log):
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlNodeDiffTests.cs(301,73): error CS1061: 'ChildListChangeDiff' does not contain a definition for 'RemovedNames' and no accessible extension method 'RemovedNames' accepting a first argument of type 'ChildListChangeDiff' could be found (are you missing a using directive or an assembly reference?) [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlNodeDiffTests.cs(316,16): error CS0103: The name 'XamlGeneratedFieldCollector' does not exist in the current context [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlNodeDiffTests.cs(331,16): error CS0103: The name 'XamlGeneratedFieldCollector' does not exist in the current context [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlNodeDiffTests.cs(348,16): error CS0103: The name 'XamlGeneratedFieldCollector' does not exist in the current context [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlIncrementalHotReloadPipelineTests.cs(1129,34): error CS0117: 'XamlHotReloadState' does not contain a definition for 'GetGeneratedFields' [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlIncrementalHotReloadPipelineTests.cs(1133,44): error CS0117: 'XamlHotReloadState' does not contain a definition for 'GetGeneratedFields' [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
🟢 With fix — 🧪 MainPage: 🔍 NO MATCH · 20s
Determining projects to restore...
All projects are up-to-date for restore.
Test run for /home/vsts/work/1/s/artifacts/bin/SourceGen.UnitTests/Debug/net11.0/Microsoft.Maui.Controls.SourceGen.UnitTests.dll (.NETCoreApp,Version=v11.0)
A total of 1 test files matched the specified pattern.
[xUnit.net 00:00:00.00] xUnit.net VSTest Adapter v2.8.2+699d445a1a (64-bit .NET 11.0.0-rc.1.26379.102)
[xUnit.net 00:00:00.29] Discovering: Microsoft.Maui.Controls.SourceGen.UnitTests
[xUnit.net 00:00:00.61] Discovered: Microsoft.Maui.Controls.SourceGen.UnitTests
[xUnit.net 00:00:00.63] Starting: Microsoft.Maui.Controls.SourceGen.UnitTests
[xUnit.net 00:00:00.67] Finished: Microsoft.Maui.Controls.SourceGen.UnitTests
No test matches the given testcase filter `MainPage` in /home/vsts/work/1/s/artifacts/bin/SourceGen.UnitTests/Debug/net11.0/Microsoft.Maui.Controls.SourceGen.UnitTests.dll
🔴 Without fix — 🧪 UpdateComponentCodeWriterTests: 🛠️ BUILD ERROR · 16s
Error-relevant lines (filtered from the build log):
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlNodeDiffTests.cs(301,73): error CS1061: 'ChildListChangeDiff' does not contain a definition for 'RemovedNames' and no accessible extension method 'RemovedNames' accepting a first argument of type 'ChildListChangeDiff' could be found (are you missing a using directive or an assembly reference?) [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlNodeDiffTests.cs(316,16): error CS0103: The name 'XamlGeneratedFieldCollector' does not exist in the current context [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlNodeDiffTests.cs(331,16): error CS0103: The name 'XamlGeneratedFieldCollector' does not exist in the current context [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlNodeDiffTests.cs(348,16): error CS0103: The name 'XamlGeneratedFieldCollector' does not exist in the current context [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlIncrementalHotReloadPipelineTests.cs(1129,34): error CS0117: 'XamlHotReloadState' does not contain a definition for 'GetGeneratedFields' [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlIncrementalHotReloadPipelineTests.cs(1133,44): error CS0117: 'XamlHotReloadState' does not contain a definition for 'GetGeneratedFields' [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
🟢 With fix — 🧪 UpdateComponentCodeWriterTests: PASS ✅ · 19s
(no coded error found; showing last 1200 chars)
urceGen.UnitTests.UpdateComponentCodeWriterTests.GeneratedMethod_HasEditorBrowsableNeverAttribute [2 ms]
Passed Microsoft.Maui.Controls.SourceGen.UnitTests.UpdateComponentCodeWriterTests.EmptyDiff_ReturnsNull [1 ms]
Passed Microsoft.Maui.Controls.SourceGen.UnitTests.UpdateComponentCodeWriterTests.SinglePropertyChange_NewValueInOutput [1 ms]
[xUnit.net 00:00:01.94] Finished: Microsoft.Maui.Controls.SourceGen.UnitTests
Passed Microsoft.Maui.Controls.SourceGen.UnitTests.UpdateComponentCodeWriterTests.SinglePropertyChange_RegistryLookupPresent [4 ms]
Passed Microsoft.Maui.Controls.SourceGen.UnitTests.UpdateComponentCodeWriterTests.SinglePropertyChange_ProducesNonEmptyPatchBody [6 ms]
Passed Microsoft.Maui.Controls.SourceGen.UnitTests.UpdateComponentCodeWriterTests.RemovedName_NonBindableObjectRoot_DoesNotEmitNameScopeLookup [15 ms]
Passed Microsoft.Maui.Controls.SourceGen.UnitTests.UpdateComponentCodeWriterTests.ReorderedChildren_GeneratesReorderCode [4 ms]
Passed Microsoft.Maui.Controls.SourceGen.UnitTests.UpdateComponentCodeWriterTests.SingleUpdateComponent_NoVersionedMethodName [2 ms]
Test Run Successful.
Total tests: 14
Passed: 14
Total time: 2.8739 Seconds
🔴 Without fix — 🧪 XamlIncrementalHotReloadPipelineTests: 🛠️ BUILD ERROR · 16s
Error-relevant lines (filtered from the build log):
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlNodeDiffTests.cs(301,73): error CS1061: 'ChildListChangeDiff' does not contain a definition for 'RemovedNames' and no accessible extension method 'RemovedNames' accepting a first argument of type 'ChildListChangeDiff' could be found (are you missing a using directive or an assembly reference?) [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlNodeDiffTests.cs(316,16): error CS0103: The name 'XamlGeneratedFieldCollector' does not exist in the current context [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlNodeDiffTests.cs(331,16): error CS0103: The name 'XamlGeneratedFieldCollector' does not exist in the current context [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlNodeDiffTests.cs(348,16): error CS0103: The name 'XamlGeneratedFieldCollector' does not exist in the current context [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlIncrementalHotReloadPipelineTests.cs(1129,34): error CS0117: 'XamlHotReloadState' does not contain a definition for 'GetGeneratedFields' [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlIncrementalHotReloadPipelineTests.cs(1133,44): error CS0117: 'XamlHotReloadState' does not contain a definition for 'GetGeneratedFields' [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
🟢 With fix — 🧪 XamlIncrementalHotReloadPipelineTests: PASS ✅ · 21s
(no coded error found; showing last 1200 chars)
sGeneratedFieldsAfterNullRoot [< 1 ms]
Passed Microsoft.Maui.Controls.SourceGen.UnitTests.XamlIncrementalHotReloadPipelineTests.EventHandler_InvalidIdentifier_UCSkips [26 ms]
[xUnit.net 00:00:08.77] Finished: Microsoft.Maui.Controls.SourceGen.UnitTests
Passed Microsoft.Maui.Controls.SourceGen.UnitTests.XamlIncrementalHotReloadPipelineTests.SecondRun_NestedLayoutAdded_EmitsUCWithGridAndChildren [40 ms]
Passed Microsoft.Maui.Controls.SourceGen.UnitTests.XamlIncrementalHotReloadPipelineTests.SecondRun_ChildReplaced_EmitsUCWithRemoveAndAdd [31 ms]
Passed Microsoft.Maui.Controls.SourceGen.UnitTests.XamlIncrementalHotReloadPipelineTests.ResourceRemoved_UCDoesNotEmitUnreachableCode [42 ms]
Passed Microsoft.Maui.Controls.SourceGen.UnitTests.XamlIncrementalHotReloadPipelineTests.VisualStateManagerChange_UCGeneratesPatch [45 ms]
Passed Microsoft.Maui.Controls.SourceGen.UnitTests.XamlIncrementalHotReloadPipelineTests.AttachedPropertyClear_UCResolvesDeclaringType [27 ms]
Passed Microsoft.Maui.Controls.SourceGen.UnitTests.XamlIncrementalHotReloadPipelineTests.TriggerAdded_UCGeneratesPatch [27 ms]
Test Run Successful.
Total tests: 64
Passed: 64
Total time: 9.7223 Seconds
🔴 Without fix — 🧪 XamlNodeDiffTests: 🛠️ BUILD ERROR · 14s
Error-relevant lines (filtered from the build log):
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlNodeDiffTests.cs(301,73): error CS1061: 'ChildListChangeDiff' does not contain a definition for 'RemovedNames' and no accessible extension method 'RemovedNames' accepting a first argument of type 'ChildListChangeDiff' could be found (are you missing a using directive or an assembly reference?) [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlNodeDiffTests.cs(316,16): error CS0103: The name 'XamlGeneratedFieldCollector' does not exist in the current context [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlNodeDiffTests.cs(331,16): error CS0103: The name 'XamlGeneratedFieldCollector' does not exist in the current context [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlNodeDiffTests.cs(348,16): error CS0103: The name 'XamlGeneratedFieldCollector' does not exist in the current context [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlIncrementalHotReloadPipelineTests.cs(1129,34): error CS0117: 'XamlHotReloadState' does not contain a definition for 'GetGeneratedFields' [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlIncrementalHotReloadPipelineTests.cs(1133,44): error CS0117: 'XamlHotReloadState' does not contain a definition for 'GetGeneratedFields' [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
🟢 With fix — 🧪 XamlNodeDiffTests: PASS ✅ · 14s
(no coded error found; showing last 1200 chars)
ourceGen.UnitTests.XamlNodeDiffTests.SameBinding_NoDiff [< 1 ms]
Passed Microsoft.Maui.Controls.SourceGen.UnitTests.XamlNodeDiffTests.MultipleChangedNodes_ReturnsAllNodeDiffs [< 1 ms]
[xUnit.net 00:00:00.90] Finished: Microsoft.Maui.Controls.SourceGen.UnitTests
Passed Microsoft.Maui.Controls.SourceGen.UnitTests.XamlNodeDiffTests.NodeId_Root_IsEmptyString [< 1 ms]
Passed Microsoft.Maui.Controls.SourceGen.UnitTests.XamlNodeDiffTests.SequentialEdits_GrowingLayout [5 ms]
Passed Microsoft.Maui.Controls.SourceGen.UnitTests.XamlNodeDiffTests.NewPropertyWithBinding_ProducesPropertyDiff [< 1 ms]
Passed Microsoft.Maui.Controls.SourceGen.UnitTests.XamlNodeDiffTests.BindingToStaticResource_ProducesComplexPropertyDiff [< 1 ms]
Passed Microsoft.Maui.Controls.SourceGen.UnitTests.XamlNodeDiffTests.SmartMatching_MixedTypes_OnlyDuplicatesUseSmartMatch [< 1 ms]
Passed Microsoft.Maui.Controls.SourceGen.UnitTests.XamlNodeDiffTests.AttachedPropertyChangedToBinding_ReturnsMarkupNodeDiff [< 1 ms]
Passed Microsoft.Maui.Controls.SourceGen.UnitTests.XamlNodeDiffTests.IdenticalTree_ReturnsEmptyDiff [< 1 ms]
Test Run Successful.
Total tests: 106
Passed: 106
Total time: 1.8817 Seconds
⚠️ Failure Details
- 🛠️ MainPage without fix: build failed before tests could run
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlNodeDiffTests.cs(301,73): error CS1061: 'ChildListChangeDiff' does not contain a definition for 'RemovedNames' and no accessible extensio...
- 🛠️ UpdateComponentCodeWriterTests without fix: build failed before tests could run
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlNodeDiffTests.cs(301,73): error CS1061: 'ChildListChangeDiff' does not contain a definition for 'RemovedNames' and no accessible extensio...
- 🛠️ XamlIncrementalHotReloadPipelineTests without fix: build failed before tests could run
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlNodeDiffTests.cs(301,73): error CS1061: 'ChildListChangeDiff' does not contain a definition for 'RemovedNames' and no accessible extensio...
- 🛠️ XamlNodeDiffTests without fix: build failed before tests could run
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlNodeDiffTests.cs(301,73): error CS1061: 'ChildListChangeDiff' does not contain a definition for 'RemovedNames' and no accessible extensio...
- 🔍 MainPage with fix: test filter matched 0 tests
- filter:
MainPage
- filter:
📁 Fix files reverted (5 files)
src/Controls/src/SourceGen/InitializeComponentCodeWriter.cssrc/Controls/src/SourceGen/UpdateComponentCodeWriter.cssrc/Controls/src/SourceGen/XamlGenerator.cssrc/Controls/src/SourceGen/XamlHotReloadState.cssrc/Controls/src/SourceGen/XamlNodeDiff.cs
📋 Pre-Flight — Context & Validation
PR #37897 Pre-Flight
Context
- PR:
[XAML] Reconcile x:Name after structural Hot Reload updates - Base:
net11.0 - Materialized review commit:
b6e16a650d2eff080bfa71bcb3ff46b6b01d9ad2 - Fixes: #37891,
[XAML Hot Reload] Structural update leaves x:Name field disconnected from the visible element - Requested test platform: Android. The changed behavior is in the cross-platform XAML source generator and is covered by
SourceGen.UnitTests; no Android device test is involved.
Problem
After source-generated incremental XAML Hot Reload structurally replaces an unnamed ancestor, the visible named descendant can be a new instance while the generated x:Name field and root namescope still reference the detached instance. Code-behind continues to run but updates the stale field, leaving the visible element unchanged. Generated fields are fixed when the type is first loaded because metadata updates cannot add or remove instance fields.
Existing PR Approach
The PR changes five production files and four test files:
InitializeComponentCodeWriter.csandXamlGenerator.cspass an original generated-field map into structural patch generation.XamlHotReloadState.cssnapshots the original root-scope generated fields and preserves that seed across later edits.XamlNodeDiff.cscollects removed names, respecting template/style/visual-state boundaries.UpdateComponentCodeWriter.csunregisters removed names identity-safely, attaches newly created elements to the root namescope, restoresStyleId, and reassigns only compatible fields that existed in the original XAML.- Tests cover structural replacement, remove/re-add, move ordering, incompatible replacement, field-boundary collection, and chained edits.
The current implementation is a broad, stateful reconciliation design. Alternative candidates must use a genuinely different root-cause mechanism and must not assign fields introduced only by Hot Reload, derive field availability from the immediately previous edit, use reflection, or rebuild retained elements.
Direct Diff Assessment
The production diff is internal implementation only and adds no public API. The sensitive behaviors are:
- A replacement element must become both the namescope result and the existing generated-field target before later code-behind access.
- Removal-only edits must stop
FindByNamefrom returning detached objects. - A name introduced after initial load must remain fieldless across later edits.
- Moving a same-named element between containers must not let a later removal unregister the newly registered instance.
- Template, style, and visual-state names must not be treated as root generated fields.
Test Boundary
Do not rerun the gate and do not run the full suite. Use one targeted command per implementation pass:
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj --no-restore -v minimal --filter "FullyQualifiedName~StructuralHotReloadTests.AncestorLayoutTypeReplacement_ReconcilesNamedFieldWithVisibleElement|FullyQualifiedName~StructuralHotReloadTests.RemovedThenReaddedName_ReconcilesOriginalGeneratedField|FullyQualifiedName~StructuralHotReloadTests.MovingNameFromLaterToEarlierContainer_KeepsNewRegistration|FullyQualifiedName~UpdateComponentCodeWriterTests|FullyQualifiedName~XamlIncrementalHotReloadPipelineTests|FullyQualifiedName~XamlNodeDiffTests"The first three filters are the primary behavioral reproductions. The three class filters are the mandatory regression tests already identified by the gate. The gate was inconclusive only because its without-fix state retained new tests that referenced reverted production symbols; the with-fix regression classes passed. Do not treat the gate as a failing fix and do not recreate gate/content.md.
Execution Constraints
Each try-fix invocation gets one implementation/test pass and at most one focused correction/retest. It must use EstablishBrokenBaseline.ps1 and its restore mode exactly as required by the try-fix skill, modify only the baseline state's RevertedFiles, perform the inline expert self-review, capture all attempt artifacts, and restore before returning. Existing unrelated dirty and untracked workflow files are pre-existing harness state and must remain untouched.
🔬 Code Review — Deep Analysis
Expert PR Evaluation
Verdict: NEEDS_CHANGES
Confidence: medium
The submitted fix correctly preserves the originally generated-field set across chained XAML Hot Reload edits, reconciles replacement instances without reflection, protects same-name moves with identity checks, and adds focused coverage for structural replacement, removal/re-addition, incompatible types, and namescope boundaries. The core replacement-time reconciliation approach is sound.
Actionable findings
⚠️ Structural changes skipped at runtime can still unregister live names. InUpdateComponentCodeWriter.EmitChildListChange, removed-name cleanup is emitted before the non-root parent registry guard and before the layout retained-child probe. If either guard causes the structural mutation to be skipped, the generated code has already removed names for elements that remain in the live tree. Namescope cleanup must execute only on the same successful path as the corresponding removal and registry cleanup.- 💡 Remove-only field behavior is not defined by a test. The namescope is cleared while the immutable generated field continues to reference the detached element. This may be intentional because the field survives metadata updates, but the PR should explicitly pin that contract rather than silently leaving field and namescope divergent.
- 💡 Visual-state exclusion is not namespace-aware.
XamlGeneratedFieldCollector.IsVisualStateFieldExcludedexcludes any list child namedVisualStateorVisualStateGroup, including user types from a CLR namespace. That diverges from the source generator's actual generated-field rules and can cause an existing custom-type field to be omitted from the immutable seed.
Evaluation
The first finding is a concrete consistency regression on an existing fail-soft path and blocks recommending the raw PR unchanged. The namespace mismatch is a safe, localized correctness improvement. Clearing immutable fields on removal requires an explicit contract decision, so it should not be changed speculatively; targeted coverage should document the intended behavior.
Gate: Inconclusive because the test project could not be built/run in the gate environment. This is treated as unverified, not as a regression-test failure.
🛠️ Try-Fix — Analysis & Comparison
PR #37897 — Final Try-Fix Aggregate
Candidate 1: ❌ BLOCKED — baseline dirty-worktree gate; zero source edits; not tested.
Candidate 2 (FINAL): ❌ BLOCKED — same independently reproduced gate; zero source edits; not tested.
Overall status: BLOCKED. Neither candidate was implemented or empirically evaluated. No further candidate will run.
Mechanism comparison
The committed PR accepts newly allocated replacement identity and repairs namescope/generated-field pointers during recursive construction, with identity-safe unregister guards. Candidate 1 designed a registry-driven post-patch epilogue that would pull final live instances and recompute those pointers. Candidate 2 designed generated-field identity transplantation: preserve the compatible object already anchored by the immutable original field through structural diff planning, so replacement-pointer repair is unnecessary. Candidate 2 avoids both prohibited mechanisms, but remains unimplemented because the baseline allow-list was never created.
Candidate 1 — complete narrative (preserved verbatim)
PR #37897 — Try-Fix Candidate 1
Result: ❌ BLOCKED (environment; zero code edits made)
Approach description (designed, not applied)
Post-Patch Namescope/Field Reconciliation Epilogue Driven by the Node-ID Registry.
Instead of wiring each newly constructed element to the root namescope and to its generated
x:Name field as it is created, emit a single reconciliation epilogue at the end of the
generated UpdateComponent() that recomputes the entire root-scope name binding from the
authoritative nodeId -> live instance map already held by XamlComponentRegistry.
Planned shape (all five files the PR touches, i.e. the same expected RevertedFiles set):
XamlHotReloadState.cs— seed and expose the original root-scope generated-field map
(name -> XmlType) captured from the first parsed root viaGetGeneratedFields, stable
across edits because metadata updates cannot add or remove instance fields.XamlNodeDiff.cs—XamlGeneratedFieldCollector(boundary-aware name walk:
DataTemplate/ControlTemplate/Stylecontribute their ownx:Namebut not their
descendants;VisualStateGroup/VisualStateitems under
VisualStateManager.VisualStateGroupsare excluded) plus
ChildListChangeDiff.RemovedNames/RemovedNameEntry.XamlGenerator.cs+InitializeComponentCodeWriter.cs— thread the new parsed root and
its effective node IDs and the original field map intoGeneratePatchBody.UpdateComponentCodeWriter.cs— emit, once per patch and only when the root inherits
BindableObject, an epilogue after every child-list/property change has been applied:- Compile time: build
name -> newNodeIdover the new tree with the same boundary walk;
compute vanished names = (original field map ∪RemovedNames) − names in the new tree. - Runtime:
var __ns = NameScope.GetNameScope(this); if (__ns != null) { … }; for each
surviving nameXamlComponentRegistry.TryGet(this, "<nodeId>", out var e), and when the
object currently registered under that name is not reference-equal toe,
UnregisterNamethenRegisterName; assignthis.<Field> = (T)eonly when the name
exists in the original field map and the new element's compile-time type is assignable
to the original field's declared type. For each vanished name, unregister guarded by a
reference-equality check against that element's last registry entry.
- Compile time: build
Prior approach avoided
The shipped PR fix (review commit b6e16a650d2eff080bfa71bcb3ff46b6b01d9ad2) hypothesises that
identity is lost in the creation path, so it repairs it there. It threads a new
existingNamedFields parameter down the entire recursive construction chain
(EmitChildListChange → EmitContentPropertyChange → EmitNewElement →
EmitNewElementChildren), adds EmitNewElementNameScope, which for every constructed
Element sets element.transientNamescope, does a per-element
FindByName/UnregisterName/RegisterName, assigns the compatible original field and
back-fills StyleId; and separately emits, before each child-list change is applied, a
per-change removal block that identity-safely unregisters RemovedNames.
Shared failure mechanism of that family of approaches: ordering coupling. Registration and
unregistration are interleaved with construction and removal, so operations for one name can be
sequenced after operations for another. The concrete manifestation is the move case — a name
moving from a later container to an earlier one can be registered by the creation path and then
unregistered by a subsequent removal block. The PR does not remove that hazard; it guards
against it with ReferenceEquals(__removedNameScope_N.FindByName(name), __removedNamedElement_N_M).
Every guard of that shape is evidence that the mechanism itself does not establish the invariant.
Mechanism-level difference
Different root-cause hypothesis: the namescope registration and the generated field are a
projection of the final tree, not a side effect of construction.
Cause-to-effect chain:
- Because reconciliation runs after all adds and removes have been applied — rather than
during them — no removal can execute after the registration of a same-name replacement.
The "a move unregisters the newly registered instance" hazard is eliminated structurally
instead of being detected and guarded, so the identity guard is no longer load-bearing. - Because each name's target is resolved from the node-ID registry (IC registers every element
it creates; UC registers every element it creates and unregisters every removed subtree),
the registry is a complete authoritative map at epilogue time. Retained elements are
therefore reconciled by lookup only — never rebuilt — and notransientNamescopepush at
construction is needed, because every new element is already parented into the live tree by
the time the epilogue runs, soNameScope.GetNameScope(this)on the root is the single
registration target. - Because field assignment is gated on the seeded original field map (not the previous edit's
tree), a name introduced only after initial load can never be assigned to a field, satisfying
the fieldless-after-load constraint; and because assignability is checked against the original
field's resolved symbol, an incompatible replacement emits nothis.X =. - No reflection anywhere: compile-time Roslyn symbol resolution plus
XamlComponentRegistry.
Net: the PR's mechanism is push-during-construction with ordering guards; the candidate's is
pull-once-after-mutation from a single authoritative identity map, which makes the invariant
hold by construction of the algorithm rather than by defensive checks.
Files changed
None. git diff -- src is empty. Zero production and zero test files were modified.
Complete captured candidate diff
(empty — no code edits were made; see Blocker analysis)fix.diff and reviewer-findings.diff in
CustomAgentLogsTmp/PRState/37897/PRAgent/try-fix/attempt-1/ are both empty for this reason.
Exact test results
No test pass was executed.
The mandated command was deliberately not run:
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj --no-restore -v minimal --filter "FullyQualifiedName~StructuralHotReloadTests.AncestorLayoutTypeReplacement_ReconcilesNamedFieldWithVisibleElement|FullyQualifiedName~StructuralHotReloadTests.RemovedThenReaddedName_ReconcilesOriginalGeneratedField|FullyQualifiedName~StructuralHotReloadTests.MovingNameFromLaterToEarlierContainer_KeepsNewRegistration|FullyQualifiedName~UpdateComponentCodeWriterTests|FullyQualifiedName~XamlIncrementalHotReloadPipelineTests|FullyQualifiedName~XamlNodeDiffTests"
Rationale: because the baseline could not be established, src/Controls/src/SourceGen still
contains the PR's own shipped fix in full. Running the filter would exercise the PR's
implementation and report green for a candidate that was never applied — a manufactured Pass,
which the skill's Pass/Fail rules explicitly prohibit. Recorded verbatim in
attempt-1/test-output.log.
Failure / blocker analysis
Step 2 (Establish Baseline) failed:
pwsh .github/scripts/EstablishBrokenBaseline.ps1
⇒ (no prior baseline state to auto-restore)
⇒ ERROR: DIRTY WORKING DIRECTORY - Cannot establish baseline
⇒ throw "EstablishBrokenBaseline.ps1 failed: Working directory is not clean.
Clean up before establishing baseline."
- The script's gate at
EstablishBrokenBaseline.ps1:372is an unconditional
git status --porcelain --untracked-files=noemptiness check. - 59 tracked files are dirty. All of them are pre-existing harness state under
.github/scripts/**,.github/skills/**,.github/workflows/**andeng/scripts/**
(e.g.Review-PR.ps1,Run-DeviceTests.ps1,eng/scripts/detect-ui-test-categories.ps1,
plus a deletedSet-ScreenResolution.Tests.ps1).git status --porcelain -- srcis empty. - The pre-flight and the invocation both require these files be left untouched, and
git checkout/restore/reset/clean/stashare prohibited by the skill's
script-only restoration principle and by the invocation's hard bounds. The script exposes
only-BaseBranch,-DryRun,-Restore— no scoping or override switch. - Consequently
.github/.baseline-state.jsonwas never created, so theRevertedFiles
modification allow-list does not exist. The skill's Step 2 rule ("If the state file is
absent … reportBlockedbefore editing") and the invocation's hard bound ("if absent …
mark Blocked without code edits") both apply. ReportedBlocked; no file edited.
Notable irony worth fixing upstream: every dirty path here already matches
$script:TestPathPatterns (which contains .github/*) and is therefore already excluded
from the script's own fix-file auto-detection. The cleanliness gate is strictly stricter than
the state the script actually requires.
Self-review count
0 findings (reviewer-findings.json = []).
Performed inline against .github/agents/maui-expert-reviewer.md per Step 6 — no sub-agent was
spawned and maui-expert-reviewer was not invoked. There is no diff to review (git diff is
empty), so the always-active dimensions (Logic and Correctness, Regression Prevention,
Complexity Reduction) have no changed hunks to walk and no routed dimensions match any file
path. reviewer-findings.diff was snapshotted as empty; Step 7.5 drift detection therefore
found no change and no refresh was required.
Restoration confirmation
pwsh .github/scripts/EstablishBrokenBaseline.ps1 -Restore was run and completed:
No baseline state found. Nothing to restore.
Restored : False
Message : No baseline state found
This is the skill-sanctioned expected result for the verified no-state path (Step 2 reported
Blocked before changing any file and no baseline state was ever created). Verified afterwards:
git status --porcelain --untracked-files=no -- src returns 0 lines — the source tree is
untouched. All 59 pre-existing dirty harness files and every pre-existing untracked path remain
exactly as found; nothing was deleted or cleaned. No git checkout/restore/reset/clean/
stash was used at any point.
Artifacts
CustomAgentLogsTmp/PRState/37897/PRAgent/try-fix/attempt-1/ — all 8 required files present:
baseline.log, approach.md, result.txt (Blocked), fix.diff (empty),
analysis.md, test-output.log, reviewer-findings.json ([]), reviewer-findings.diff (empty).
Candidate 2 — complete narrative
PR #37897 — Try-Fix Candidate 2 (FINAL)
Result: ❌ BLOCKED (environment; baseline rejected the pre-existing dirty harness state)
Implementation status: Designed only. Zero source edits were made, and the candidate was not tested.
Distinct approach: generated-field identity transplantation
Candidate 2 treats each field generated by the original XAML as an immutable runtime identity anchor. Its root-cause hypothesis is earlier than either prior proposal: when an unnamed ancestor changes type, the structural differ treats every descendant as disposable even when a compatible descendant is permanently represented by an original generated field. Allocating a second object for that name creates the split among visible tree, field, and namescope.
The planned mechanism was:
- Preserve the original boundary-aware
name -> XmlTypeseed inXamlHotReloadStateacross edits. - In
XamlNodeDiff, correlate a compatible original generated-field name below a removed subtree with the same name below an added subtree. Mark it as a transplant anchor rather than an ordinary remove/add pair. - Detach the anchored instance from its old parent, preserve/transfer its component identity, apply the normal node/property delta to that same instance, and attach it under the new ancestor. If a name was removed in one edit and reintroduced later, obtain the detached anchor directly from statically emitted
this.<generatedField>, not a registry scan. - Reattach the root namescope to the same identity when necessary. Exclude a transplanted node from removed-name and removed-registry cleanup. A move cannot unregister a newer same-name instance because no newer instance exists.
- Only names in the first-load field seed with assignment-compatible types are eligible. Post-load names are allocated normally and stay fieldless. Ordinary retained nodes remain on the existing retained path and are not rebuilt. Direct generated field access and Roslyn type checks require no reflection.
Property removals and descendant deltas on a reused detached anchor would require careful implementation. Because the baseline failed before edits were authorized, this remained a design and is not claimed correct.
Prior approaches explicitly avoided
Existing PR: push during recursive construction
The PR snapshots original generated names/types, threads that state through recursive patch construction, and invokes EmitNewElementNameScope for newly allocated elements. That method pushes the root namescope into transientNamescope, replaces the registration, assigns a compatible original field to the new instance, and restores StyleId. Per-child-list removal blocks identity-safely unregister removed names. The assumption is that replacement identity is valid and references should be repaired while it is built; ordering hazards are mitigated with ReferenceEquals guards.
Candidate 2 does not assign a generated field to a newly created replacement, does not thread reconciliation through recursive construction, and does not rely on interleaved unregister/register operations. For a compatible original field identity, it avoids constructing the conflicting replacement.
Candidate 1: registry-driven post-patch epilogue
Candidate 1 designed a single final reconciliation pass that would walk final names/node IDs, pull live instances from XamlComponentRegistry, rebuild the root namescope projection, and assign compatible fields. Its assumption is that namescope and fields are projections to recompute after the final tree exists.
Candidate 2 performs no final registry scan and has no registry-driven post-patch epilogue. The generated field itself supplies identity, and structural diff planning carries that identity through the edit.
Mechanism-level difference
The PR and candidate 1 both accept replacement identity and repair pointers to it—one pushes during construction, the other pulls after mutation. Candidate 2 rejects replacement identity for compatible original generated fields. It preserves the object the immutable field already identifies and transplants it through the structural boundary. Thus:
- no second compatible object is allocated for an original generated name;
- the field cannot become stale because it still references the object inserted into the visible tree;
- the namescope continues or is reattached to the same object;
- removal bookkeeping excludes that identity, so moves cannot unregister a newer same-name object;
- post-load names lack anchors and remain fieldless;
- retained nodes remain retained and are not reconstructed.
This changes identity selection in the differ, rather than renaming or repositioning reconciliation.
Baseline and blocker
The required independent baseline step ran exactly once:
pwsh .github/scripts/EstablishBrokenBaseline.ps1
It exited 1:
ERROR: DIRTY WORKING DIRECTORY - Cannot establish baseline
...
EstablishBrokenBaseline.ps1 failed: Working directory is not clean.
Clean up before establishing baseline.
The verbatim output is in try-fix/attempt-2/baseline.log. The script listed 59 tracked pre-existing harness changes, all under .github/** or eng/scripts/**. Verification showed:
STATE_ABSENT
TRACKED_DIRTY_COUNT=59
SRC_DIRTY_COUNT=0
Because .github/.baseline-state.json was absent, no RevertedFiles allow-list existed. The skill and invocation prohibit bypassing the gate, changing the script, or cleaning/stashing/restoring pre-existing files. Candidate 2 stopped before source edits.
Files changed and complete candidate diff
Source/test files changed: none. Required output artifacts were written only in the designated logging paths.
(empty — baseline failed before source edits were permitted)Both attempt-2/fix.diff and reviewer-findings.diff are empty.
Exact test result
Not run. The only allowed command was:
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj --no-restore -v minimal --filter "FullyQualifiedName~StructuralHotReloadTests.AncestorLayoutTypeReplacement_ReconcilesNamedFieldWithVisibleElement|FullyQualifiedName~StructuralHotReloadTests.RemovedThenReaddedName_ReconcilesOriginalGeneratedField|FullyQualifiedName~StructuralHotReloadTests.MovingNameFromLaterToEarlierContainer_KeepsNewRegistration|FullyQualifiedName~UpdateComponentCodeWriterTests|FullyQualifiedName~XamlIncrementalHotReloadPipelineTests|FullyQualifiedName~XamlNodeDiffTests"
Running it without an applied candidate would test the committed PR mechanism and could not yield an honest candidate Pass. attempt-2/test-output.log records this.
Inline expert self-review
0 findings. Performed inline without any reviewer, task, skill, or sub-agent. All eight overarching principles and the always-active Logic and Correctness, Regression Prevention, and Complexity Reduction dimensions were applied. No code diff meant no routed SourceGen hunk with a concrete finding. reviewer-findings.json is []; Step 7.5 confirmed the empty diff did not drift.
Restoration confirmation
The exact restore command ran:
pwsh .github/scripts/EstablishBrokenBaseline.ps1 -Restore
No baseline state found. Nothing to restore.
Restored : False
Message : No baseline state found
This is the expected verified no-state path: baseline created no state and candidate 2 made no source edit. Afterward, state remained absent, all 59 pre-existing harness changes remained untouched, and SRC_DIRTY_COUNT=0. No checkout/reset/restore/clean/stash or deletion was used.
Artifacts and final status
All eight mandatory files were verified in CustomAgentLogsTmp/PRState/37897/PRAgent/try-fix/attempt-2/: baseline.log, approach.md, result.txt (Blocked), fix.diff, analysis.md, test-output.log, reviewer-findings.json, and reviewer-findings.diff.
Done / Blocked. This was the final allowed candidate. It was neither implemented nor tested, and no further candidate will run.
🏁 Report — Final Recommendation
⚠️ Final Recommendation: REQUEST CHANGES
Winner: pr-plus-reviewer
The submitted PR has the right core model: it preserves the originally loaded generated-field set, repairs replacement identity in the root namescope, avoids reflection, respects nested namescope boundaries, and protects same-name move ordering with reference identity. Expert review nevertheless found a concrete fail-soft-path defect: removed names are unregistered before the runtime parent and retained-child guards establish that the structural mutation can execute. When a guard skips the mutation, the element remains visible but its root namescope entry has already been removed.
pr-plus-reviewer keeps the submitted design and applies one consolidated correction. It scopes namescope, generated-field, and component-registry cleanup to successful mutation; identity-safely clears original fields on remove-only updates; and makes visual-state field filtering namespace-aware. It also adds focused regressions for all three review findings. Its required targeted validation was attempted exactly once but was blocked before compilation by a missing sandbox project.assets.json; this is recorded as uncertainty, not as a failed regression test.
Candidate comparison
| Rank | Candidate | Implementation | Regression evidence | Assessment |
|---|---|---|---|---|
| 1 | pr-plus-reviewer |
Complete reviewer patch on the submitted fix | Best code-level result. It preserves the PR's proven architecture while resolving the expert review's concrete consistency bug and two adjacent state/field gaps with targeted tests. | |
| 2 | pr |
Complete submitted fix | Correct core reconciliation, but runtime skip paths can remove names and registry entries without applying the visual-tree mutation. The raw PR therefore should not merge unchanged. | |
| 3 | try-fix-1 |
Design only; no source edits | ❌ Blocked before implementation; no tests run | The post-patch registry reconciliation epilogue could remove ordering coupling, but it is broader than the PR fix and its assumptions about registry completeness were never implemented or tested. |
| 4 | try-fix-2 |
Design only; no source edits | ❌ Blocked before implementation; no tests run | Identity transplantation is the most invasive option and explicitly leaves property-removal and descendant-delta behavior unresolved. It has no executable evidence. |
No candidate produced a regression-test failure. The two try-fix-* entries are ranked below implemented candidates because they contain no patch and no empirical result; pr-plus-reviewer remains explicitly unverified because its only allowed validation could not start.
Why pr-plus-reviewer wins
It is the only candidate that both retains the submitted fix's narrow source-generated Hot Reload model and addresses the expert review findings in executable code. The raw PR cannot win while its cleanup side effects escape the same guards that intentionally skip structural mutations, and neither try-fix design is implemented. Because the winner includes changes not present in submitted PR HEAD, the recommendation is REQUEST CHANGES.
Remaining uncertainty
The reviewer patch passed git diff --check, but its targeted SourceGen tests did not compile or execute due to the missing assets file. The candidate should be restored and run with the exact focused filter before its changes are submitted; no claim of passing tests is made here.
📱 UI Tests — Button,Label,Layout
Detected UI test categories: Button,Label,Layout
✅ Deep UI tests — 360 passed, 0 failed, 7 skipped across 3 categories on platform-pool agent (replaces in-process counts above).
🧪 UI Test Execution Results (deep, platform pool)
| Category | Tests | Snapshot diffs |
|---|---|---|
Button |
71/73 (2 skipped) ✓ | 1 diff PNG |
Label |
97/99 (2 skipped) ✓ | — |
Layout |
192/195 (3 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 submitted reconciliation design while fixing cleanup that could run when a structural mutation was skipped, defining remove-only field state, and aligning visual-state field collection with namespaces. Its focused validation was environment-blocked rather than failed, while both try-fix alternatives remained unimplemented and untested.
Address the actionable findings in this review before merging.
<!-- 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! ## Description Fixes #37889. Source-generated incremental Hot Reload rebuilds a binding when only `StringFormat` changes. The update writer expands the binding in a synthetic generator context that has no live XAML namescope, so nested `{x:Reference ...}` resolution loses its source. The replacement binding keeps its path and format but receives a null source, clearing the target value. This change recognizes the actual `Microsoft.Maui.Controls.Xaml.ReferenceExtension` symbol while regenerating markup extensions and resolves it from the live target element's namescope. Resolution is performed before replacing the existing property value: if the element is detached, namescopes are disabled, or a renamed/new name has not yet been reconciled, the update is skipped and the existing binding is retained rather than cleared or throwing. Non-`Element` property owners use the root `Element` as the namescope anchor when available. The change intentionally does not duplicate the broad structural namescope registration work in #37897. Child-list changes already run before property changes, so once #37897 reconciles a structurally introduced name, this guarded lookup can consume it; without that reconciliation, it fails safely. ## Tests Added source-generator Hot Reload coverage that: - creates two live page instances and verifies a `StringFormat`-only edit retains each instance's referenced source; - detaches the updated element and removes its transient namescope, proving the update does not throw or replace the existing binding; - renames an `x:Name` without live namescope reconciliation, proving the unresolved reference does not clear the existing source; - defines a user markup extension named `ReferenceExtension`, proving it is not mistaken for MAUI's `x:Reference`. Baseline result for the original reproduction: failed with `Expected: \"mirror Instance caption V1\"; Actual: null`. Validation: ```text Targeted: Passed 20, Failed 0, Skipped 0 Full SourceGen suite: Passed 515, Failed 0, Skipped 0 ``` Commands: ```bash DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj --no-restore --filter "FullyQualifiedName~BindingAndMarkupHotReloadTests|FullyQualifiedName~UpdateComponentCodeWriterTests" DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj --no-restore ``` Formatting: ```bash dotnet format src/Controls/src/SourceGen/Controls.SourceGen.csproj --no-restore --include src/Controls/src/SourceGen/UpdateComponentCodeWriter.cs --exclude-diagnostics CA1822 dotnet format src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj --no-restore --include src/Controls/tests/SourceGen.UnitTests/HotReload/AiAssisted/BindingAndMarkupHotReloadTests.Bindings.cs src/Controls/tests/SourceGen.UnitTests/HotReload/AiAssisted/BindingAndMarkupHotReloadTests.cs --exclude-diagnostics CA1822 ``` ## Risk Low and limited to source-generated incremental Hot Reload markup-extension regeneration. Normal XAML inflation and runtime binding behavior are unchanged. Template realization remains outside this patch's scope; existing DataTemplate/ControlTemplate namescope isolation behavior is unchanged. --------- Copilot-Session: c30817d7-694e-4593-8efc-dc56ecfaeba1
Note
Are you waiting for the changes in this PR to be merged?
It would be very helpful if you could test the resulting artifacts from this PR and let us know in a comment if this change resolves your issue. Thank you!
Root Cause
Source-generated incremental XAML Hot Reload rebuilt structurally replaced subtrees and updated the component registry, but skipped the namescope and generated-field work performed by
InitializeComponent. The visible named descendant was replaced while itsx:Namefield and root namescope entry continued to reference the detached instance.Generated-field availability is fixed when the type is originally loaded: metadata updates cannot add or remove instance fields. Therefore chained edits must use the original XAML field set, not the immediately previous XAML.
Description of Change
StyleId, and reassign a field only when that name existed on the originally loaded type.FindByNamenever returns a detached object during removal-only edits.Retained elements keep their identity, handlers, bindings, and lifecycle. Namescope operations remain behind
_MAUIXAML_SG_NAMESCOPE_DISABLE.What NOT to Do
Test Evidence
HorizontalStackLayout→VerticalStackLayoutreplacement invokes code-behind through the generated field and distinguishes visible and detached label identities.FindByName.Structure count 0instead ofStructure count 2; fixed test passes.DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj --no-restore -v minimal— 514 passed.Structural and Lifecycle Risks
The change is limited to structural patch creation/removal. Root-scope field collection excludes DataTemplate, ControlTemplate, Style, and VisualStateGroup scopes. Runtime reconciliation is per page instance; no runtime global state is added.
Issues Fixed
Fixes #37891