Skip to content

[net11.0][XAML] Preserve whitespace-padded names in runtime field lookups - #39568

Merged
kubaflo merged 1 commit into
net11.0from
kubaflo-runtime-xaml-name-trimming
Oct 24, 2026
Merged

kubaflo merged 1 commit into
net11.0from
kubaflo-runtime-xaml-name-trimming

Conversation

@kubaflo

@kubaflo kubaflo commented Oct 22, 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

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. 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:

# 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 3c9c033482797b64d878ef3f59bc6ac8a92f6ebd -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, 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, Windows Debug XAML, macOS Release XAML, Windows Release XAML. 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

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

Preserve the original x:Name alongside the normalized generated field identifier, including across Hot Reload field reconciliation. Keep runtime namescope and style semantics unchanged.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: ba91d542-6d91-4dc8-b270-c1b5b57a958c
Copilot AI balanced review requested due to automatic review settings October 22, 2026 17:43
@kubaflo
kubaflo temporarily deployed to copilot-pat-pool October 22, 2026 17:43 — with GitHub Actions Inactive
@github-actions

Copy link
Copy Markdown
Contributor

🚀 Dogfood this PR with:

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

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

Or

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

@kubaflo
kubaflo temporarily deployed to copilot-pat-pool October 22, 2026 17:43 — with GitHub Actions Inactive
@azure-pipelines

This comment has been minimized.

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.

🔵 Needs a closer look

Validation of the shared generator change remains unconfirmed because hosted CI and the reported local test results were not independently verified.

No open issues 🎉

What changed in this PR

Repairs the net11.0 XAML regression introduced by #39281 by preserving whitespace-padded runtime lookup names while keeping generated field identifiers trimmed.

Changes:

  • Carries original XAML names through field reconciliation without changing retained field contracts.
  • Uses safely quoted original names for direct and conditional runtime FindByName calls.
  • Adds whitespace-edit and generated-code compilation coverage with incremental Hot Reload enabled and disabled.
File Description
src/​Controls/​tests/​SourceGen.UnitTests/​CodeBehindFieldStabilityTests.cs Tests preserved lookup whitespace across edits in both Hot Reload modes.
src/​Controls/​src/​SourceGen/​CodeBehindCodeWriter.cs Separates runtime lookup names from trimmed field identifiers.

Review effort: Balanced

@kubaflo

This comment has been minimized.

@azure-pipelines

This comment has been minimized.

@github-actions github-actions Bot added s/agent-review-in-progress AI review is currently running for this PR and removed s/agent-review-in-progress AI review is currently running for this PR labels Oct 23, 2026
@MauiBot

This comment has been minimized.

@kubaflo

kubaflo commented Oct 23, 2026

Copy link
Copy Markdown
Contributor Author

/review expert-review

@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 23, 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 — 1 finding

Reviewed commit e4d0c17.

See inline comments for details.


AssertNoErrors(diagnostics, updatedCompilation);
Assert.Contains("Label label0;", output, StringComparison.Ordinal);
Assert.Contains("FindByName<global::Microsoft.Maui.Controls.Label>(this, \" label0 \")", output, StringComparison.Ordinal);

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] Regression Prevention and Test Coverage - Both XAML versions retain the same Label type, so the Hot Reload-enabled case exercises only the direct FindByName(Label) assignment, not the separately changed conditional FindByName(object) lookup. The neighboring type-change tests check SourceGen assignments or retained declarations rather than the runtime lookup key. Reverting only the conditional branch to the trimmed name would therefore escape these assertions: after an edit from Label to an assignable MyLabel with a whitespace-padded x:Name, runtime initialization would fail to assign the retained Label field. Add a Runtime generator case that changes the element type and name padding together, asserting the conditional lookup uses the current raw name while preserving the original field type.

@MauiBot

MauiBot commented Oct 23, 2026

Copy link
Copy Markdown
Collaborator

PR Test Gate

@kubaflo — existing-test verification for commit e4d0c17f.

Result PASSED Platform Android Commit e4d0c17f


🧪 Gate analysis — click to expand

✅ Passed. The selected verification satisfied the gate's passing conditions. Unmatched, skipped, or inconclusive groups are not passing evidence.

🧪 Unit tests
Test group Without fix With fix
CodeBehindFieldStabilityTests ✅ Failed as expected (74s) ✅ Passed (26s)
Execution log excerpts

Without fix CodeBehindFieldStabilityTests

     at Microsoft.Maui.Controls.Xaml.UnitTests.SourceGen.CodeBehindFieldStabilityTests.RuntimeInflation_PreservesXNameWhitespaceInNameScopeLookup(Boolean enableIncrementalHotReload) in /_/src/Controls/tests/SourceGen.UnitTests/CodeBehindFieldStabilityTests.cs:line 190
   at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)
   at System.Reflection.MethodBaseInvoker.InvokeDirectByRefWithFewArgs(Object obj, Span`1 copyOfArgs, BindingFlags invokeAttr)
   at InvokeStub_CodeBehindFieldStabilityTests.RuntimeInflation_PreservesXNameWhitespaceInNameScopeLookup(Object, Span`1)
   at System.Reflection.MethodBaseInvoker.InvokeWithOneArg(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)

With fix CodeBehindFieldStabilityTests

umulatedFields [47 ms]
  Passed Microsoft.Maui.Controls.Xaml.UnitTests.SourceGen.CodeBehindFieldStabilityTests.TransientUnresolvedType_DoesNotPoisonFieldHistory [83 ms]
  Passed Microsoft.Maui.Controls.Xaml.UnitTests.SourceGen.CodeBehindFieldStabilityTests.RuntimeInflation_PreservesXNameWhitespaceInNameScopeLookup(enableIncrementalHotReload: True) [53 ms]
  Passed Microsoft.Maui.Controls.Xaml.UnitTests.SourceGen.CodeBehindFieldStabilityTests.RuntimeInflation_PreservesXNameWhitespaceInNameScopeLookup(enableIncrementalHotReload: False) [305 ms]
  Passed Microsoft.Maui.Controls.Xaml.UnitTests.SourceGen.CodeBehindFieldStabilityTests.FreshGeneratorSession_DoesNotReusePreviousXamlPatchState [35 ms]
[xUnit.net 00:00:06.09]   Finished:    Microsoft.Maui.Controls.SourceGen.UnitTests
  Passed Microsoft.Maui.Controls.Xaml.UnitTests.SourceGen.CodeBehindFieldStabilityTests.ReusingObjectFieldWithValueType_UsesImplicitBoxingAssignment [75 ms]
  Passed Microsoft.Maui.Controls.Xaml.UnitTests.SourceGen.CodeBehindFieldStabilityTests.ReusingXNameWithAssignableDerivedType_KeepsFieldAssigned_AndGeneratedCodeCompiles [36 ms]
Test Run Successful.
Total tests: 17
     Passed: 17
 Total time: 7.2232 Seconds

PR head: e4d0c17f.

Without-fix baseline: 4ef2769e.

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

kubaflo commented Oct 23, 2026

Copy link
Copy Markdown
Contributor Author

@dalexsoto stamp

@dalexsoto dalexsoto left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Stamping as requested by @kubaflo; no code review performed.

@kubaflo
kubaflo merged commit a683676 into net11.0 Oct 24, 2026
153 of 180 checks passed
@kubaflo
kubaflo deleted the kubaflo-runtime-xaml-name-trimming branch October 24, 2026 10:34
@github-actions github-actions Bot added this to the .NET 11.0-rc2 milestone Oct 24, 2026

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — e4d0c17f Deployed Oct 22, 2026 by kubaflo via conclusion #2466
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

s/agent-gate-passed AI verified tests catch the bug (fail without fix, pass with fix)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants