You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Fix XAML hot-reload id desync on x:Name changes and reorders - #39168
While testing XAML hot-reload (dotnet-watch, Android emulator) I noticed intermittent corruption after reordering/editing siblings: after enough edits the app eventually threw an InvalidCastException at runtime.
Root cause: XamlNodeDiff.ComputeDiff conflated "can this property change be emitted as an incremental patch" with "can this node's identity be matched at all". Any codegen-sensitive property change (e.g. x:Name added/removed/changed) made DiffNode return false, which cascaded all the way up to the root and forced ComputeDiff to return null. XamlGenerator's structural-fallback branch then reset every id in the page to a fresh DFS numbering, without ever informing the live app's XamlComponentRegistry, which kept its old ids. A later ordinary (non-structural) patch could then target the wrong live object by id.
Fix
Decouples identity from patchability:
DiffNode now reports a codegen-sensitive property change via a new needsRebuild out-parameter instead of returning false, except at the true tree root (depth 0), where there's no parent to attach a local rebuild to and a full structural reload is still correct.
The immediate parent's child-list diff (DiffChildrenPositional / DiffChildrenWithMatching) turns a needsRebuild signal into a single contained rebuild entry: the node is recreated but registered under its same id (ChildChangeKind.Rebuilt with the old id, intentionally excluded from RemovedNodeIds so the subsequent Unregister pass can't race with and clobber the re-registration). Rebuilt is distinguished from Added so the code writer knows to emit a replace-in-place against the SAME id rather than treating it as a brand-new insertion. No other node in the tree is affected.
DiffChildrenPositional now lazily builds a ChildListChangeDiff only when at least one child actually needs a rebuild; pure property/descendant-only edits are unaffected.
Net effect: an x:Name change (or a reorder that happens to coincide with one) no longer resets every id on the page - it's now a small, localized rebuild of just the affected node, so the registry and the generator's own id bookkeeping stay in sync.
Testing
Added/updated unit tests in XamlNodeDiffTests.cs at the XamlNodeDiff.ComputeDiff level, including a direct repro of the original desync that now asserts the live registry id and the freshly patched id match.
Full suite (SourceGen.UnitTests): Passed! - Failed: 0, Passed: 550, Skipped: 37, Total: 587
Known follow-up (not in this PR)
True cross-parent reparenting (same x:Name moved to a different parent) is not yet recognized as an identity match; it still falls back to remove+add in each parent, which is safe (no desync) but not optimal. Can be tackled as a separate change.
The reason will be displayed to describe this comment to others. Learn more.
Same root cause/response as the later-surfaced duplicate of this finding (r4195949572): backing fields and the fields assigned in InitializeComponent are a compile-time artifact of the original generation, and standard EnC hot reload cannot add a new field to a live type at runtime — only a real rebuild (restart or a fresh instance picking up the regenerated InitializeComponent) can materialize a new field/namescope entry for a renamed element. This is an accepted limitation of the incremental-patch model (same class as the documented structural-reset tradeoff in XamlGenerator.cs), not something this PR's id-continuity fix is meant to resolve. See my reply on r4195949572 for the fuller rationale.
The reason will be displayed to describe this comment to others. Learn more.
Fixed: the local-rebuild eligibility gate in DiffNode now checks HasUnsupportedConstructionDirectiveInSubtree, which rejects local rebuild whenever the node (or any descendant) carries x:FactoryMethod/x:Arguments — forcing a full structural fallback for those cases instead of an invalid new Type() rebuild. See regression tests XNameChanged_WithUnchangedXFactoryMethod_CascadesToStructural_NotLocalRebuild, XNameChanged_WithUnchangedXArguments_CascadesToStructural_NotLocalRebuild, and `XNameChanged_WithDescendantXFactoryMethod_CascadesToStructural_NotLocalRebuild" in XamlNodeDiffTests.cs. Landed in 070b11d / 209529e.
The reason will be displayed to describe this comment to others. Learn more.
This is already covered at the pipeline/runtime level by XNameRenamed_SamePositionSameType_UnregistersOldNameAndResolvesNewOne in StructuralHotReloadTests.cs: it generates+applies the actual UpdateComponent patch through the full hot-reload harness and asserts page.FindByName("oldLabel") is null post-rename while FindByName("RenamedLabel") resolves to the new live instance (i.e. it exercises XamlComponentRegistry/namescope behavior directly, not just the generator-side id dictionaries). The ApplyEdit-based test you commented on is a lower-level unit test of the diff/id-assignment algorithm itself and is intentionally narrower in scope; the registry/name-lookup behavior is verified separately at the pipeline test above.
The reason will be displayed to describe this comment to others. Learn more.
Already fixed in 6867fd4 — the dashed banner lines at all 4 locations were replaced with plain ordinary comments. Current HEAD has no dashed fake-region banners left in this file.
Azure Pipelines will not run the associated pipelines, because the pull request was updated after the run command was issued. Review the pull request again and issue a new run command.
The s/agent-review-in-progress label stays on this PR while the run is active. The final recommendation and outcome labels are posted only after Gate, expert review, and Deep UI tests finish.
During hot-reload, XamlNodeDiff.ComputeDiff conflated "can this
property change be emitted as an incremental patch" with "can this
node's identity be matched at all". Any codegen-sensitive property
change (e.g. x:Name added/removed/changed) made DiffNode return
false, which cascaded all the way up to the root and forced
ComputeDiff to return null. XamlGenerator's structural-fallback
branch then reset every id in the page to a fresh DFS numbering,
without ever informing the live app's XamlComponentRegistry, which
kept its old ids. A later ordinary (non-structural) patch could then
target the wrong live object by id, eventually producing an
InvalidCastException at runtime.
This fixes it by decoupling identity from patchability:
- DiffNode now reports a codegen-sensitive property change as a new
`needsRebuild` out-parameter instead of returning false, except at
the true tree root (depth 0), where there is no parent to attach a
local rebuild to and a full structural reload is still correct.
- The immediate parent's child-list diff (DiffChildrenPositional /
DiffChildrenWithMatching) turns a `needsRebuild` signal into a
single contained rebuild entry: the node is recreated, but
registered under its SAME id (ChildChangeKind.Added with the old
id, intentionally excluded from RemovedNodeIds so the subsequent
Unregister pass can't race with and clobber the re-registration).
No other node in the tree is affected.
- DiffChildrenPositional now lazily builds a ChildListChangeDiff only
when at least one child actually needs a rebuild; pure
property/descendant-only edits are unaffected.
Net effect: an x:Name change (or a reorder that happens to coincide
with one) no longer nukes every id on the page - it's now a small,
localized rebuild of just the affected node, so the registry and the
generator's own id bookkeeping stay in sync.
Added/updated unit tests in XamlNodeDiffTests.cs at the
XamlNodeDiff.ComputeDiff level, including a direct repro of the
original desync (StructuralResetMidReorder_...) that now asserts the
live registry id and the freshly patched id match.
Known follow-up (not in this change): true cross-parent reparenting
(same x:Name moved to a different parent) is not yet recognized as
an identity match; it still falls back to remove+add in each parent,
which is safe (no desync) but not optimal.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 9d5c8c84-5dbd-4c4a-8282-99860900c4f7
The s/agent-review-in-progress label stays on this PR while the run is active. The final recommendation and outcome labels are posted only after Gate, expert review, and Deep UI tests finish.
- Narrow local-rebuild eligibility to x:Name/x:Key only (IsLocallyRebuildable),
gated on IsCodegenSensitive + not-inside-template + not-root. Other
codegen-sensitive directives (x:FactoryMethod, x:TypeArguments, etc.) still
cascade to a full structural reload, since the rebuild codegen always emits
a plain 'new {Type}()' and can't represent a factory call or generic
instantiation.
- Gate local rebuilds on insideTemplate: a renamed node inside a
DataTemplate/ControlTemplate still cascades, since EmitChildListChange only
resolves parents via XamlComponentRegistry, not realized template instances.
- Collect RemovedNames for locally-rebuilt subtrees (new
CollectRebuiltSubtreeNames helper, reusing XamlGeneratedFieldCollector.Visit)
in both DiffChildrenPositional and DiffChildrenWithMatching, so a rebuilt
node's old x:Name (and any named descendants) get unregistered from the live
NameScope instead of leaking a stale FindByName entry.
- Replace dashed fake-region comment banners introduced by this PR with
ordinary comments, per repo convention.
- Add unit tests: RemovedNames population for both rebuild paths (including a
reorder-triggered DiffChildrenWithMatching case and a deeply-nested
descendant-name case), x:FactoryMethod/x:TypeArguments cascading behavior,
and template-content x:Name cascading behavior.
- Add an end-to-end pipeline test (StructuralHotReloadTests) exercising an
actual x:Name rename through the generated UpdateComponent code: asserts the
old name stops resolving, the new name resolves to the rebuilt instance, and
documents the known/accepted stale-backing-field limitation (UpdateComponent
can't add/rename a compiled class field at runtime).
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 9d5c8c84-5dbd-4c4a-8282-99860900c4f7
- IsLocallyRebuildable no longer accepts x:Key: it identifies a
ResourceDictionary entry, which is rewritten via the dedicated
TryEmitResourceDictionaryItemChange/TryEmitResourceDictionaryChange path,
not the Layout-child/content-property path EmitChildListChange (the
local-rebuild emitter) understands. A key rename now correctly keeps
cascading to a full structural reload.
- DiffProperties no longer short-circuits on the first codegen-sensitive
directive change it finds. It now scans every changed directive on a node
and only reports it as locally rebuildable when ALL of them are eligible,
so a compound edit (e.g. x:Name changed alongside x:FactoryMethod) can no
longer have the eligible directive mask the ineligible one and silently
drop part of the change.
- Updated/replaced the corresponding unit tests (XKey_Changed_*,
rebuild-eligibility boundary comment) and added
XNameAndXFactoryMethodBothChanged_CascadesToStructural_NotLocalRebuild to
lock in the compound-edit behavior.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 9d5c8c84-5dbd-4c4a-8282-99860900c4f7
The s/agent-review-in-progress label stays on this PR while the run is active. The final recommendation and outcome labels are posted only after Gate, expert review, and Deep UI tests finish.
…ck tradeoff
- XamlNodeDiff.cs: HasUnsupportedConstructionDirective only checked the node
being rebuilt itself. EmitNewElementChildren recreates the ENTIRE recreated
subtree via plain new {Type}() calls, so a descendant carrying
x:FactoryMethod/x:Arguments is just as unsafe to silently drop as the
rebuilt node itself carrying one. Added HasUnsupportedConstructionDirectiveInSubtree,
checked recursively over Properties and CollectionItems, and used it in the
local-rebuild eligibility gate instead of the single-node check.
(addresses r4195949531)
- UpdateComponentCodeWriter.cs: added a clarifying comment at the
GeneratePatchBody call site: routing an unsupported-shape emission failure
through the structural-reset fallback does not introduce a NEW desync class
beyond what already exists for every other structural-reset trigger (see
the pre-existing "Structural change" comment in XamlGenerator.cs) - live
instances are documented as not patched across a structural change; only
freshly-constructed instances pick up the new tree. No functional change.
(addresses r4195949442 - replied on the thread with the same rationale)
- XamlNodeDiffTests.cs: added a regression test for the descendant-directive
case (x:Name rename on a container whose child carries x:FactoryMethod).
Full SourceGen.UnitTests suite: 550 passed, 0 failed, 37 skipped.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 9d5c8c84-5dbd-4c4a-8282-99860900c4f7
The PR description says local rebuilds are encoded as ChildChangeKind.Added, but the implementation now introduces and relies on Rebuilt specifically to distinguish replacement from insertion. Update the description so the documented mechanism matches the code.
This issue also appears on line 484 of the same file.
The s/agent-review-in-progress label stays on this PR while the run is active. The final recommendation and outcome labels are posted only after Gate, expert review, and Deep UI tests finish.
🩺 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(1029,32): error CS0117: 'ChildChangeKind' does not contain a definition for 'Rebuilt' [/home/vsts/work/1/s/src/Controls/...
Error-relevant lines (filtered from the build log):
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlNodeDiffTests.cs(1029,32): error CS0117: 'ChildChangeKind' does not contain a definition for 'Rebuilt' [/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(2733,33): error CS0117: 'ChildChangeKind' does not contain a definition for 'Rebuilt' [/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(2839,32): error CS0117: 'ChildChangeKind' does not contain a definition for 'Rebuilt' [/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(3031,32): error CS0117: 'ChildChangeKind' does not contain a definition for 'Rebuilt' [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
🟢 With fix — 🧪 MainPage: 🔍 NO MATCH · 19s
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.01] xUnit.net VSTest Adapter v2.8.2+699d445a1a (64-bit .NET 11.0.0-rtm.26480.113)
[xUnit.net 00:00:00.15] Discovering: Microsoft.Maui.Controls.SourceGen.UnitTests
[xUnit.net 00:00:00.40] Discovered: Microsoft.Maui.Controls.SourceGen.UnitTests
[xUnit.net 00:00:00.42] Starting: Microsoft.Maui.Controls.SourceGen.UnitTests
[xUnit.net 00:00:00.46] 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
Error-relevant lines (filtered from the build log):
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlNodeDiffTests.cs(1029,32): error CS0117: 'ChildChangeKind' does not contain a definition for 'Rebuilt' [/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(2733,33): error CS0117: 'ChildChangeKind' does not contain a definition for 'Rebuilt' [/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(2839,32): error CS0117: 'ChildChangeKind' does not contain a definition for 'Rebuilt' [/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(3031,32): error CS0117: 'ChildChangeKind' does not contain a definition for 'Rebuilt' [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
🟢 With fix — 🧪 UpdateComponentCodeWriterTests: PASS ✅ · 15s
Error-relevant lines (filtered from the build log):
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlNodeDiffTests.cs(1029,32): error CS0117: 'ChildChangeKind' does not contain a definition for 'Rebuilt' [/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(2733,33): error CS0117: 'ChildChangeKind' does not contain a definition for 'Rebuilt' [/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(2839,32): error CS0117: 'ChildChangeKind' does not contain a definition for 'Rebuilt' [/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(3031,32): error CS0117: 'ChildChangeKind' does not contain a definition for 'Rebuilt' [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
🛠️ MainPage without fix: build failed before tests could run
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlNodeDiffTests.cs(1029,32): error CS0117: 'ChildChangeKind' does not contain a definition for 'Rebuilt' [/home/vsts/work/1/s/src/Controls/...
🛠️ UpdateComponentCodeWriterTests without fix: build failed before tests could run
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlNodeDiffTests.cs(1029,32): error CS0117: 'ChildChangeKind' does not contain a definition for 'Rebuilt' [/home/vsts/work/1/s/src/Controls/...
🛠️ XamlNodeDiffTests without fix: build failed before tests could run
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlNodeDiffTests.cs(1029,32): error CS0117: 'ChildChangeKind' does not contain a definition for 'Rebuilt' [/home/vsts/work/1/s/src/Controls/...
The Copilot expert-review task ended before this phase was persisted, usually because the review-stage time budget expired or the CI agent encountered a transient authentication/runtime problem. Earlier completed sections remain valid, but this review is incomplete without this phase.
Next step: re-comment /review to retry on a fresh agent. If this repeats across runs, a maintainer should inspect the reviewer token and Task 3 logs.
🔬 Code Review — Deep Analysis
⚠️Code Review did not produce output on this run.
The Copilot expert-review task ended before this phase was persisted, usually because the review-stage time budget expired or the CI agent encountered a transient authentication/runtime problem. Earlier completed sections remain valid, but this review is incomplete without this phase.
Next step: re-comment /review to retry on a fresh agent. If this repeats across runs, a maintainer should inspect the reviewer token and Task 3 logs.
🛠️ Try-Fix — Analysis & Comparison
⚠️Try-Fix did not produce output on this run.
The Copilot expert-review task ended before this phase was persisted, usually because the review-stage time budget expired or the CI agent encountered a transient authentication/runtime problem. Earlier completed sections remain valid, but this review is incomplete without this phase.
Next step: re-comment /review to retry on a fresh agent. If this repeats across runs, a maintainer should inspect the reviewer token and Task 3 logs.
🏁 Report — Final Recommendation
⚠️Report / Final Recommendation did not produce output on this run.
The Copilot expert-review task ended before this phase was persisted, usually because the review-stage time budget expired or the CI agent encountered a transient authentication/runtime problem. Earlier completed sections remain valid, but this review is incomplete without this phase.
Next step: re-comment /review to retry on a fresh agent. If this repeats across runs, a maintainer should inspect the reviewer token and Task 3 logs.
📱 UI Tests — Button,Label,Layout
Detected UI test categories:Button,Label,Layout
⚠️Deep UI tests — The build failed to compile for 3 categories (Button, Label, Layout), so those deep UI tests could not run. The compiler reported: error MSB4184: The expression "[MSBuild]::VersionLessThan('', 11.0)" cannot be evaluated. Version string was not in a correct format. [/home/vsts/work/1/s/src/Controls/tests/TestCases.HostApp/Controls.TestCases.HostApp.csproj]. Check the build-output.log in the drop-deep-uitests artifact to see whether main or this PR introduced it, then re-run once the build is fixed.
🧭 Next Steps — review latest findings
No alternative fix was selected for this run. Review the session findings and CI results before merging.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
While testing XAML hot-reload (dotnet-watch, Android emulator) I noticed intermittent corruption after reordering/editing siblings: after enough edits the app eventually threw an InvalidCastException at runtime.
Root cause: XamlNodeDiff.ComputeDiff conflated "can this property change be emitted as an incremental patch" with "can this node's identity be matched at all". Any codegen-sensitive property change (e.g. x:Name added/removed/changed) made DiffNode return false, which cascaded all the way up to the root and forced ComputeDiff to return null. XamlGenerator's structural-fallback branch then reset every id in the page to a fresh DFS numbering, without ever informing the live app's XamlComponentRegistry, which kept its old ids. A later ordinary (non-structural) patch could then target the wrong live object by id.
Fix
Decouples identity from patchability:
needsRebuildout-parameter instead of returning false, except at the true tree root (depth 0), where there's no parent to attach a local rebuild to and a full structural reload is still correct.Rebuiltis distinguished fromAddedso the code writer knows to emit a replace-in-place against the SAME id rather than treating it as a brand-new insertion. No other node in the tree is affected.Net effect: an x:Name change (or a reorder that happens to coincide with one) no longer resets every id on the page - it's now a small, localized rebuild of just the affected node, so the registry and the generator's own id bookkeeping stay in sync.
Testing
Added/updated unit tests in XamlNodeDiffTests.cs at the XamlNodeDiff.ComputeDiff level, including a direct repro of the original desync that now asserts the live registry id and the freshly patched id match.
Full suite (SourceGen.UnitTests): Passed! - Failed: 0, Passed: 550, Skipped: 37, Total: 587
Known follow-up (not in this PR)
True cross-parent reparenting (same x:Name moved to a different parent) is not yet recognized as an identity match; it still falls back to remove+add in each parent, which is safe (no desync) but not optimal. Can be tackled as a separate change.