Skip to content

Make CodeBehind generator incremental to fix EnC rude edits on x:Name changes - #39281

Merged
kubaflo merged 10 commits into
net11.0from
fix-38993-cb-incremental-fields
Oct 20, 2026
Merged

kubaflo merged 10 commits into
net11.0from
fix-38993-cb-incremental-fields

Conversation

@StephaneDelcroix

@StephaneDelcroix StephaneDelcroix commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Note

Are you waiting for the changes in this PR to be merged?
It would be very helpful if you could test the resulting artifacts from this PR and let us know in a comment if this change resolves your issue. Thank you!

Description of Change

Renaming, removing, or retyping an x:Name during XAML Incremental Hot Reload caused the CodeBehind generator to regenerate its field list from the current XAML. Roslyn Edit-and-Continue treats a generated field being deleted or retyped as a rude edit (ENC0020/ENC0033), even though no hand-written C# changed.

This PR makes generated code-behind fields additive for the lifetime of a generator-driver session:

  • Previously generated fields are retained when an x:Name is removed or renamed.
  • A field keeps its original declaration type and access modifier when the name is reused with an incompatible type.
  • New fields are appended without changing existing field definitions.
  • Mutable field and XAML history is isolated per generator-driver through a weakly keyed HotReloadSessionToken, preventing overlapping compilations from sharing state.
  • Field compatibility is evaluated against the compilation containing generated code-behind, preserving inheritance relationships declared by generated partial types.
  • Declaration and assignment checks use Roslyn implicit conversions, including boxing, and retain the original XmlType for nested, generic, and special types.
  • Invalid identifiers and unresolved types are not persisted into field history. x:Name values are normalized consistently before declaration and assignment.

Live x:Name changes are applied in place when the existing element can be retained:

  • All affected old names are unregistered before any new names are registered, allowing sibling-name swaps.
  • New names are registered before dependent property and binding updates, supporting forward x:Reference.
  • Generated fields and StyleId are updated for added or renamed names.
  • Root names and non-BindableObject roots are handled without invalid namescope access.
  • Template-local name changes use structural fallback rather than mutating the page namescope.
  • Unregistration only removes a name when it still refers to the element being patched.

The field-history behavior remains gated by the existing EnableIncrementalHotReload setting.

Validation

  • DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj --no-restore
    • Passed: 612
    • Failed: 0
    • Skipped: 0

Coverage includes rename, removal, incompatible retyping, unresolved types, whitespace-normalized names, nested/generic types, boxing, fresh and overlapping generator sessions, root names, sibling swaps, forward references, template fallback, generated-source compilation, metadata deltas, namescope registration, bindings, StyleId, and retained live-element identity.

Issues Fixed

Fixes #38993

… changes

Renaming, removing, or retyping an x:Name'd element during live Hot
Reload caused the CodeBehind generator to regenerate its whole field
list from scratch, which Roslyn's EnC engine flags as a rude edit
(ENC0020/ENC0033 - deleting/renaming a field requires restarting the
application), even though no hand-written C# was touched.

CodeBehindCodeWriter now accumulates named fields across Hot Reload
generations (XamlHotReloadState.AccumulatedCodeBehindFields) instead
of recomputing them from the current XAML parse alone. Fields are
only ever added, never removed or retyped: a field whose x:Name was
removed or reused with an incompatible type becomes a 'ghost' field
that keeps its original type/access and is left at its default value,
while MemberNotNullAttribute emission and the generated FindByName<T>
assignments skip ghost fields. SetFieldsForXNamesVisitor was updated
to skip emitting an assignment to a ghost field when the element's
type no longer matches the originally generated field type.

Also fixes XamlHotReloadState.TryGetPrevious, which could report a
bogus 'previous generation' purely from the new field-bookkeeping
cache entry, suppressing UpdateComponent emission on the very first
generation. A new CacheEntry.HasGeneratedOutput flag distinguishes
real prior generations from bookkeeping-only entries.

The whole fix is gated behind ProjectItem.EnableIncrementalHotReload
(Debug-only), so Release/CI builds are unaffected.

Fixes #38993

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: c95b3039-fd19-4865-94d8-591f6237b063
Copilot AI balanced review requested due to automatic review settings October 9, 2026 12:33
@github-actions

github-actions Bot commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 39281

Or

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

@azure-pipelines

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

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.

🟡 Changes recommended

Compatible derived types are incorrectly treated as ghosts, and the tests do not validate generated assignments or actual EnC updates.

4 open findings
What changed in this PR

Makes generated XAML code-behind fields additive across Hot Reload generations to avoid EnC field deletion/retype diagnostics.

Changes:

  • Accumulates generated fields and tracks valid prior generations.
  • Preserves ghost fields while suppressing invalid assignments.
  • Adds rename, removal, and retype regression tests.
File Description
CodeBehindCodeWriter.cs Reconciles current and historical fields.
XamlHotReloadState.cs Stores accumulated fields and generation status.
SetFieldsForXNamesVisitor.cs Skips assignments for mismatched field types.
CodeBehindFieldStabilityTests.cs Tests field stability across XAML edits.

🧠 Review effort: Balanced

Comment on lines +52 to +56
Assert.Contains("Microsoft.Maui.Controls.Label count", output1, StringComparison.Ordinal);

// The field generated for the original name must still be declared after the rename:
// removing it is what makes Roslyn's EnC engine see a field deletion/rename.
Assert.Contains("count", output2, StringComparison.Ordinal);
@kubaflo

This comment has been minimized.

@kubaflo

kubaflo commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

/azp run

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Oct 9, 2026
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).

@github-actions

github-actions Bot commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

Note

🔍 /review started

AzDO build 15629523 is running for android.

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

…date tests

Address multi-model review findings on PR #39281:
- Replace strict string-equality type comparison with real Roslyn
  assignability checks (TryResolveSimpleTypeSymbol/IsAssignableToGhostField
  in GeneratorHelpers.cs), used by both CodeBehindCodeWriter's
  ReconcileNamedFieldsForHotReload and SetFieldsForXNamesVisitor. This fixes
  the case where an x:Name is reused with a derived type (e.g. Label ->
  MyLabel : Label) incorrectly being treated as an incompatible "ghost"
  field and losing its assignment.
- Add RunGeneratorWithChangesAndUpdateCompilation to SourceGeneratorDriver
  so hot-reload-style second-generation tests can assert the generated
  code actually compiles, not just string-match the generated source.
- Add two tests in CodeBehindFieldStabilityTests.cs that reuse an x:Name
  across generations with an assignable derived type (field stays
  assigned) and an incompatible type (assignment correctly skipped),
  verifying both that the field is (or isn't assigned in
  InitializeComponent output and that the resulting code compiles.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: c95b3039-fd19-4865-94d8-591f6237b063
EOF
)
MauiBot

This comment was marked as outdated.

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

This comment has been minimized.

@github-actions

github-actions Bot commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

Tests Failure Analysis

@StephaneDelcroix — test-failure analysis for commit 5358550.

Scope CI failures Commit 5358550


🧪 CI Analysis — click to expand
📊 maui-pr

No failures found.


🧪 maui-pr-devicetests
  • 🟡 Needs human investigation — CarouselView handler leak, MacCatalyst CoreCLR/macOS 15 arm64: retained reference; five bounded target runs lack equivalent diagnostics.
  • 🟡 Needs human investigation — Controls Tests crash, same runtime: dump/incomplete execution causes the failed Helix step; inspect crash stack.

🧪 maui-pr-uitests

🧭 Follow-up — actions and refresh

Next action: Inspect crash/app logs, compare unresolved failures at head/base, and restore truncated UI evidence.

Maintainers: comment /review tests to refresh this report.

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

Copilot-Session: c95b3039-fd19-4865-94d8-591f6237b063
Copilot AI balanced review requested due to automatic review settings October 19, 2026 08:45

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.

🟡 Changes recommended

Unresolved name-update ordering, duplicate registration, and conversion errors can skip bindings or abort Hot Reload patches.

3 open issues
1 previously missed issue

In code that hasn't changed since last review

Medium severity Avoid duplicate name registration for unchanged mappings

src/​Controls/​src/​SourceGen/​UpdateComponentCodeWriter.cs:248

RegisterName throws when the new name already exists, even when it points to the same element. Replaying a rename patch therefore aborts the remaining updates: the guarded old-name removal does nothing, then this registration throws. Queued runtime-handler invocations can execute the same latest UpdateComponent body. Skip registration when the mapping already matches the target, as EmitNewElementNameScope does, and test applying the rename patch twice.

5 resolved since last review

Review effort: Balanced

Comment on lines +113 to +114
EmitNameChanges(codeWriter, diff, unregister: true, rootType, compilation, xmlnsCache, typeCache, generatedFields, templateNodeIds);
EmitNameChanges(codeWriter, diff, unregister: false, rootType, compilation, xmlnsCache, typeCache, generatedFields, templateNodeIds);
&& fieldType is not null
&& IsAssignableTo(nodeType, fieldType, compilation))
{
codeWriter.WriteLine($"this.{GeneratorHelpers.EscapeIdentifier(newName)} = ({fieldType.ToFQDisplayString()}){targetVar};");
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copilot-Session: c95b3039-fd19-4865-94d8-591f6237b063
Copilot AI balanced review requested due to automatic review settings October 19, 2026 09:16

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.

🟡 Changes recommended

Inconsistent name normalization can break generated-code compilation and leave backing fields unassigned.

4 open issues

Review effort: Balanced

cancellationToken.ThrowIfCancellationRequested();

var name = GetAttributeValue(node, "Name", XamlParser.X2006Uri, XamlParser.X2009Uri) ?? throw new Exception();
var name = GetAttributeValue(node, "Name", XamlParser.X2006Uri, XamlParser.X2009Uri)?.Trim() ?? throw new Exception();
@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Oct 19, 2026
@MauiBot

MauiBot commented Oct 19, 2026

Copy link
Copy Markdown
Collaborator

PR Test Gate

@StephaneDelcroix — existing-test verification for commit 38520114.

Result PASSED Platform Android Commit 38520114


🧪 Gate analysis — click to expand

✅ Passed (compilation-dependent baseline). The tests require API added by the fix, so the without-fix baseline could not compile. The with-fix run passed; no runtime failure-to-pass reproduction is claimed.

🧪 Unit tests
Test group Without fix With fix
BindingAndMarkupHotReloadTests ⚠ Build blocked ✅ Passed (23s)
CodeBehindFieldStabilityTests ⚠ Build blocked ✅ Passed (17s)
StructuralHotReloadTests ⚠ Build blocked ✅ Passed (19s)
UpdateComponentCodeWriterTests ⚠ Build blocked ✅ Passed (14s)
XamlIncrementalHotReloadCSharpExpressionTests ⚠ Build blocked ✅ Passed (19s)
XamlIncrementalHotReloadE2ETests ⚠ Build blocked ✅ Passed (18s)
XamlIncrementalHotReloadPipelineTests ⚠ Build blocked ✅ Passed (21s)
XamlNodeDiffTests ⚠ Build blocked ✅ Passed (20s)
Execution log excerpts

Without fix BindingAndMarkupHotReloadTests

/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlIncrementalHotReloadPipelineTests.cs(1081,26): error CS0246: The type or namespace name 'HotReloadSessionToken' could not 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/XamlIncrementalHotReloadPipelineTests.cs(1093,22): error CS1503: Argument 2: cannot convert from 'Microsoft.Maui.Controls.SourceGen.SGRootNode' to 'System.Collections.Generic.IAsyncEnumerable<char>?' [/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(1110,26): error CS0246: The type or namespace name 'HotReloadSessionToken' could not 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/XamlIncrementalHotReloadPipelineTests.cs(1116,27): error CS0246: The type or namespace name 'HotReloadFieldContract' could not 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/XamlIncrementalHotReloadPipelineTests.cs(1112,22): error CS0117: 'XamlHotReloadState' does not contain a definition for 'SetAccumulatedCodeBehindFields' [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]

With fix BindingAndMarkupHotReloadTests

gAndMarkupHotReloadTests.XReferenceBinding_RenamedName_RetainsElementAndUpdatesSource [1 ms]
  Skipped Microsoft.Maui.Controls.SourceGen.UnitTests.HotReload.AiAssisted.BindingAndMarkupHotReloadTests.UserReferenceExtension_IsNotRewrittenAsMauiXReference [1 ms]
  Skipped Microsoft.Maui.Controls.SourceGen.UnitTests.HotReload.AiAssisted.BindingAndMarkupHotReloadTests.XReferenceBinding_MissingLiveNameScope_RetainsExistingBinding [1 ms]
  Passed Microsoft.Maui.Controls.SourceGen.UnitTests.HotReload.AiAssisted.BindingAndMarkupHotReloadTests.MultiBinding_ComplexProperty_EmitsSkipMarker [48 ms]
  Skipped Microsoft.Maui.Controls.SourceGen.UnitTests.HotReload.AiAssisted.BindingAndMarkupHotReloadTests.XReferenceBinding_StringFormatEdit_RetainsSourceAcrossUpdates [1 ms]
  Skipped Microsoft.Maui.Controls.SourceGen.UnitTests.HotReload.AiAssisted.BindingAndMarkupHotReloadTests.DynamicResourceToBinding_SwapAndReverse_UpdatesVisibleValue [1 ms]
  Skipped Microsoft.Maui.Controls.SourceGen.UnitTests.HotReload.AiAssisted.BindingAndMarkupHotReloadTests.CustomMarkupExtension_EditAndReverse_ReprovidesValue [1 ms]
Test Run Successful.
Total tests: 9
     Passed: 2
    Skipped: 7
 Total time: 5.5356 Seconds

Without fix CodeBehindFieldStabilityTests

/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlIncrementalHotReloadPipelineTests.cs(1081,26): error CS0246: The type or namespace name 'HotReloadSessionToken' could not 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/XamlIncrementalHotReloadPipelineTests.cs(1093,22): error CS1503: Argument 2: cannot convert from 'Microsoft.Maui.Controls.SourceGen.SGRootNode' to 'System.Collections.Generic.IAsyncEnumerable<char>?' [/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(1110,26): error CS0246: The type or namespace name 'HotReloadSessionToken' could not 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/XamlIncrementalHotReloadPipelineTests.cs(1116,27): error CS0246: The type or namespace name 'HotReloadFieldContract' could not 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/XamlIncrementalHotReloadPipelineTests.cs(1112,22): error CS0117: 'XamlHotReloadState' does not contain a definition for 'SetAccumulatedCodeBehindFields' [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]

With fix CodeBehindFieldStabilityTests

ype_KeepsOriginalFieldTypeAndDoesNotCrashOnReplace [21 ms]
[xUnit.net 00:00:05.36]   Finished:    Microsoft.Maui.Controls.SourceGen.UnitTests
  Passed Microsoft.Maui.Controls.Xaml.UnitTests.SourceGen.CodeBehindFieldStabilityTests.FreshGeneratorSession_DoesNotReuseAccumulatedFieldsFromPreviousSession [73 ms]
  Passed Microsoft.Maui.Controls.Xaml.UnitTests.SourceGen.CodeBehindFieldStabilityTests.OverlappingDriverWithSameCacheKey_DoesNotInvalidateLiveDriversAccumulatedFields [80 ms]
  Passed Microsoft.Maui.Controls.Xaml.UnitTests.SourceGen.CodeBehindFieldStabilityTests.TransientUnresolvedType_DoesNotPoisonFieldHistory [91 ms]
  Passed Microsoft.Maui.Controls.Xaml.UnitTests.SourceGen.CodeBehindFieldStabilityTests.FreshGeneratorSession_DoesNotReusePreviousXamlPatchState [70 ms]
  Passed Microsoft.Maui.Controls.Xaml.UnitTests.SourceGen.CodeBehindFieldStabilityTests.ReusingObjectFieldWithValueType_UsesImplicitBoxingAssignment [271 ms]
  Passed Microsoft.Maui.Controls.Xaml.UnitTests.SourceGen.CodeBehindFieldStabilityTests.ReusingXNameWithAssignableDerivedType_KeepsFieldAssigned_AndGeneratedCodeCompiles [83 ms]
Test Run Successful.
Total tests: 15
     Passed: 15
 Total time: 6.0796 Seconds

PR head: 38520114.

Without-fix baseline: 1f6eccaf.

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

@github-actions github-actions Bot 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.

Expert Review — 2 findings

Reviewed commit 3852011.

See inline comments for details.

var targetVar = isRoot ? "this" : $"__nameTarget_{phase}_{changeIndex}";
if (!isRoot)
{
codeWriter.WriteLine($"if (global::Microsoft.Maui.Controls.Xaml.XamlComponentRegistry.TryGet(this, \"{EscapeString(nodeDiff.NodeId)}\", out var {targetVar}))");

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.

[moderate] Logic and Correctness - Adding x:Name to a previously lazy resource leaves its generated field unassigned. With SourceGen, incremental Hot Reload and the default LazyRD setting, start a ResourceDictionary subclass with <SolidColorBrush x:Key="brush" Color="Red" />, then add x:Name="namedBrush" without changing its key or type. IsLazyResource excludes the original resource from the outer Variables dictionary, and AddLazyResourceToResourceDictionary's factory never registers its node ID, even after realization. The new name-only patch therefore misses this TryGet and skips the field assignment; namedBrush remains null on the live dictionary, whereas fresh initialization makes the named resource eager and assigns it. Resolve this transition through the owning dictionary/key or another supported fallback, and add a regression covering an initially unnamed lazy resource.

}
}

if (!unregister && nameDiff.Kind == PropertyDiffKind.Set && !string.IsNullOrEmpty(nameDiff.NewValue))

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.

[moderate] XAML & Bindings - In-place x:Name changes do not update RuntimeNameProperty. In a SourceGen ResourceDictionary subclass, rename <VisualState x:Key="state" x:Name="OldState" /> to x:Name="NewState". InitializeComponent originally sets VisualState.Name through SetPropertiesVisitor.TrySetRuntimeName, but this name-change pass only updates namescope/field/StyleId state, and the subsequent property pass explicitly skips x:Name. The retained resource consequently keeps Name == "OldState", unlike a freshly inflated dictionary. If that resource is used in a VisualStateGroup, GetState still matches the old name, so GoToState(element, "NewState") cannot select it. Apply the RuntimeNameProperty contract when patching retained names and cover this case.

@kubaflo

This comment has been minimized.

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

This comment has been minimized.

@azure-pipelines

This comment has been minimized.

@kubaflo
kubaflo merged commit e38973a into net11.0 Oct 20, 2026
118 of 141 checks passed
@kubaflo
kubaflo deleted the fix-38993-cb-incremental-fields branch October 20, 2026 22:47
@github-actions github-actions Bot added this to the .NET 11.0-rc2 milestone Oct 20, 2026
kubaflo added a commit that referenced this pull request Oct 24, 2026
…kups (#39568)

<!-- 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!

<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Description of Change

<!-- Enter description of the fix in this section -->

Intentionally targets **net11.0**, where #39281 introduced this
regression.

`CodeBehindCodeWriter.GetNamedFields` trims `x:Name` for field identity
and Hot Reload reconciliation. The runtime XAML loader still registers
the original name. For the existing `x:Name=" label0"` fixture,
generated runtime initialization therefore looks up `"label0"` instead
of `" label0"`, leaving the generated field null.

Keep the original XAML name alongside the trimmed field identifier and
use it for runtime `FindByName` calls, including conditional assignments
after Hot Reload type changes. Reconciliation uses the current XAML
lookup name while preserving existing field contracts. Quote lookup keys
with Roslyn's string-literal formatter.

Runtime parsing, namescope registration, `StyleId`, and `x:Reference`
semantics are unchanged. The original `Maui27121` fixture and
`Assert.NotNull(page.label0)` are unchanged. Add generator coverage for
whitespace-only name edits with incremental Hot Reload enabled and
disabled, including generated-code compilation.

The original assertion is already failing in the target branch's [build
1643728](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1643728).
This is a focused baseline repair, not a change to GC tests, device
fixtures, packages, or pipelines.

**Validation**

Used the repository-pinned `11.0.100-rtm.26514.118` SDK in a private
installation, with platform-neutral `net11.0` unit execution only. No
Apple UI/XCTest execution.

The exact `Maui27121.Tests.XNameAreTrimmed(inflator: Runtime)` case was
**baseline red → fix green → fix reverted red → fix restored green**.
Both red runs failed the original `Assert.NotNull` at
`Maui27121.xaml.cs:30`. The full verification script ended with
`VERIFICATION PASSED`; the worktree was clean after restoration.

Commands and results:

```sh
# PASS: prerequisite build, zero warnings/errors
dotnet build Microsoft.Maui.BuildTasks.slnf -p:BuildTaskOnlyBuild=true -p:IncludeAndroidTargetFrameworks=false -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -p:IncludeMacOSTargetFrameworks=false -p:IncludeWindowsTargetFrameworks=false -v:quiet

# PASS: formatting, exit 0
dotnet format Microsoft.Maui.sln --no-restore --exclude Templates/src --exclude-diagnostics CA1822 --include src/Controls/src/SourceGen/CodeBehindCodeWriter.cs src/Controls/tests/SourceGen.UnitTests/CodeBehindFieldStabilityTests.cs --verbosity quiet

# PASS: 96 generator/code-behind/Hot Reload tests
dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj --no-restore --filter 'FullyQualifiedName~CodeBehindFieldStabilityTests|FullyQualifiedName~SourceGenXamlCodeBehindTests|FullyQualifiedName~XamlIncrementalHotReloadPipelineTests' -p:IncludeAndroidTargetFrameworks=false -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -p:IncludeMacOSTargetFrameworks=false -p:IncludeWindowsTargetFrameworks=false -v:quiet

# PASS: 49 related name tests in Debug, including all three Maui27121 inflators
dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj --no-restore --filter 'FullyQualifiedName~Maui27121|FullyQualifiedName~NameScopeTests|FullyQualifiedName~FindByName|FullyQualifiedName~SetStyleIdFromXName|FullyQualifiedName~XReference' -p:IncludeAndroidTargetFrameworks=false -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -p:IncludeMacOSTargetFrameworks=false -p:IncludeWindowsTargetFrameworks=false -v:quiet

# VERIFICATION PASSED: reverted Runtime 1 failed; restored Runtime 1 passed
# "unknown" is the runner's output-folder sentinel for this then-unpublished PR.
pwsh -NoProfile -File .github/skills/verify-tests-fail-without-fix/scripts/verify-tests-fail.ps1 -PRNumber unknown -TestType XamlUnitTest -TestFilter 'FullyQualifiedName~Maui27121&DisplayName~Runtime' -BaseBranch 3c9c033 -FixFiles src/Controls/src/SourceGen/CodeBehindCodeWriter.cs -RequireFullVerification

# PASS: 49 related name tests in Release, including all three Maui27121 inflators
dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj -c Release --no-restore --filter 'FullyQualifiedName~Maui27121|FullyQualifiedName~NameScopeTests|FullyQualifiedName~FindByName|FullyQualifiedName~SetStyleIdFromXName|FullyQualifiedName~XReference' '-p:DefaultItemExcludesInProjectFolder=**/Generated/**' -p:IncludeAndroidTargetFrameworks=false -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -p:IncludeMacOSTargetFrameworks=false -p:IncludeWindowsTargetFrameworks=false -v:quiet
```

The first Release attempt included previously emitted Debug `Generated`
sources and failed with duplicate declarations. The command-only
exclusion above removed those duplicate inputs; no project or pipeline
configuration was changed. Full suites, Windows execution, and hosted CI
are not claimed by these local results.

Validated against base `3c9c033482797b64d878ef3f59bc6ac8a92f6ebd`. The
subsequent target update to `7b0ea7800db3f3faccbaecb665d32b7c61eaf932`
does not change the relevant XAML source, tests, or dependency inputs.
Open and recently merged upstream PRs were checked for the same
issue/files/mechanism; no equivalent net11.0 fix was found. The
cumulative inflight PR retains older raw-name handling but does not
contain the net11.0 field reconciliation that this fix preserves.

**Hosted validation — build 1645738**

Actual uploaded `testResults.xml` files from [maui-pr
1645738](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1645738),
not aggregate badges, confirm the following for head
`e4d0c17f19b64b0bb20c9fafc96f0f77fa43371e` / merge
`9177af7ae9323da1e620ec8d6418f8e5b6bb8d7b`:

| Configuration | Maui27121 Runtime / XamlC / SourceGen | New generator
cases (off / on) | Assembly results (passed / skipped) |
|---|---|---|---|
| macOS Debug | 3/3 pass | 2/2 pass | XAML 2147/8; generator 626/38 |
| Windows Debug | 3/3 pass | 2/2 pass | XAML 2147/8; generator 626/38 |
| macOS Release | 3/3 pass | 2/2 pass | XAML 2127/14; generator 626/38 |
| Windows Release | 3/3 pass | 2/2 pass | XAML 2127/14; generator 626/38
|

All eight assembly result files have **zero failures and zero errors**.
The new cases are
`CodeBehindFieldStabilityTests.RuntimeInflation_PreservesXNameWhitespaceInNameScopeLookup(enableIncrementalHotReload:
False/True)`.

Direct XML evidence: [macOS Debug
XAML](https://helixr1107v0xdeko0k025g8.blob.core.windows.net/dotnet-maui-refs-pull-39568-merge-26482b1441b344e898/Microsoft.Maui.Controls.Xaml.UnitTests.dll/1/testResults.xml?helixlogtype=result),
[Windows Debug
XAML](https://helixr1107v0xdeko0k025g8.blob.core.windows.net/dotnet-maui-refs-pull-39568-merge-49b6e89f7fec47bb82/Microsoft.Maui.Controls.Xaml.UnitTests.dll/1/testResults.xml?helixlogtype=result),
[macOS Release
XAML](https://helixr1107v0xdeko0k025g8.blob.core.windows.net/dotnet-maui-refs-pull-39568-merge-85b4282be7464f77b1/Microsoft.Maui.Controls.Xaml.UnitTests.dll/1/testResults.xml?helixlogtype=result),
[Windows Release
XAML](https://helixr1107v0xdeko0k025g8.blob.core.windows.net/dotnet-maui-refs-pull-39568-merge-f7f51120b4a84e9ca4/Microsoft.Maui.Controls.Xaml.UnitTests.dll/1/testResults.xml?helixlogtype=result).
Generator XML files are in the same respective containers under
`Microsoft.Maui.Controls.SourceGen.UnitTests.dll/1/testResults.xml`.

The raw Azure Helix monitor log reports four jobs processed, zero
jobs/work items resubmitted, 46 work items submitted, and zero failed.
**At the bounded observation cutoff (2026-10-22 19:46 UTC), the overall
build was still in progress: 28 of 31 jobs had succeeded; `Blazor
windows`, `Build windows`, and `Samples macOS` integration jobs remained
active. No failed timeline records were present at that cutoff.** The
focused unit-test evidence above is complete, but no overall CI or
merge-readiness verdict is implied. The observation watch ended at its
fixed deadline; no additional dispatches or retries were requested.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

Fixes the runtime regression of #27121 introduced by #39281,
demonstrated by the existing `Maui27121.Tests.XNameAreTrimmed`
assertion.

<!--
Are you targeting main? All PRs should target the main branch unless
otherwise noted.
-->

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: ba91d542-6d91-4dc8-b270-c1b5b57a958c
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 20, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-gate-passed AI verified tests catch the bug (fail without fix, pass with fix) s/agent-review-in-progress AI review is currently running for this PR s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants