Repository navigation
[XSG] XIHR: re-derive the pending UpdateComponent patch on repeated evaluation - #40233
Conversation
…valuation Roslyn can evaluate the same generator-driver snapshot more than once (driver forks, speculative/design-time requests, cancelled or discarded runs). XamlHotReloadState advanced its cached "previous" XAML on the first evaluation, so any later evaluation of the same inputs saw no change and emitted an empty UpdateComponent(), silently dropping the XAML edit. When a generation produces a patch, the cache entry now also keeps the exact generation it was diffed from plus a fingerprint of the user C# sources (path + SourceText content hash, memoized per Compilation). A later generation with the same XAML and the same user sources re-derives the same patch; one with different user sources (a C#-only edit) still emits an empty UpdateComponent(). The baseline is only replaced by the next XAML edit, so output no longer depends on evaluation order. Fixes #36937 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
|
🚀 Dogfood this PR with:
curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 40233Or
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 40233" |
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
|
/rebase |
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
PR Test Gate
🧪 Gate analysis — click to expand⚠ Inconclusive. Setup, build, or execution did not produce a conclusive result. This does not prove the fix is incorrect. No interpretable test-group summary was produced. No additional test execution is inferred. Setup did not capture a verified PR head; no commit is claimed as tested. No immutable without-fix baseline was prepared. |
| // generation (C#-only edit): UC is emitted empty. The baseline is left untouched either | ||
| // way, so the output only depends on the inputs, never on evaluation order. | ||
| if (pendingSources is not null | ||
| && pendingSources.Equals(UserSourcesFingerprint.Get(userCompilation, sourceProductionContext.CancellationToken))) |
There was a problem hiding this comment.
[major] Logic and Correctness Verification - Undoing a subsequent C# edit replays an already-applied, non-idempotent XAML patch. For example, apply a XAML change from Clicked="OnA" to Clicked="OnB" (both methods already exist), apply an unrelated code-behind method-body edit, then undo that C# edit without changing XAML. The intermediate run emits an empty UC but retains PatchSources; undo restores its fingerprint, so this branch emits the old patch again. XamlIncrementalHotReloadHandler treats the now-nonempty UC as a XAML update and invokes it on live instances. TryEmitEventChange emits Clicked -= OnA; Clicked += OnB;, leaving the existing OnB subscription and adding another: each click now invokes OnB twice. The new C#-only test stops before returning to the original fingerprint and does not cover this regression.
| var edited = baseline.ReplaceAdditionalText(v1.Text, v2.Text).WithUpdatedAnalyzerConfigOptions(new OptionsProvider([v2])).RunGenerators(compilation); | ||
| Assert.Contains("\"World\"", FindUCSource(edited.GetRunResult(), "uc.xsg"), StringComparison.Ordinal); | ||
|
|
||
| var csharpEdited = compilation.AddSyntaxTrees(CSharpSyntaxTree.ParseText("namespace TestApp; class Unrelated { }", path: "Unrelated.cs")); |
There was a problem hiding this comment.
[moderate] Regression Prevention and Test Coverage - The C#-only negative case adds a syntax tree, so UserSourcesFingerprint.Equals rejects it on tree count before comparing any content hashes. The different-C# interleaving test uses the same shortcut. These tests therefore still pass if content-hash comparison is removed, leaving an edit to an existing C# file at the same path and tree count unprotected against replaying the previous XAML patch. Replace an existing tree with changed method-body text and assert that UpdateComponent stays empty; retain the original-snapshot replay assertion to discriminate both outcomes.
|
Thanks for the fix. The identical-input driver-fork case now works, and this is not a blanket break of C# versus XAML detection. However, I reproduced a new behavioral compatibility regression in the signal used for Hot Reload reporting and telemetry. We cannot merge this as-is while that classification regresses. I compared base New regression: C# edit followed by an exact undo after a XAML patch
The third accepted delta is C#-only, but:
The new fingerprint-equality branch re-derives the retained XAML patch when C# returns to F1, even though no XAML changed relative to the last accepted runtime generation. The unchanged MUH consequently recognizes the page as a XAML update. Preserving the event names and signatures is not sufficient: their classification semantics also need to remain compatible. This is deterministic once that edit sequence occurs; I have not measured its incidence in normal sessions. Other cases checked
The comparison verified nine applied cycles per revision on Windows/.NET 11 CoreCLR with Roslyn 4.12. No page instances were created, since classification must also work without instances. UI mutation, non-idempotent replay, Mono/mobile runtimes, and actual VS scheduling were not exercised. Please add an accepted-delta/runtime-MUH regression test for XAML edit -> C# edit -> C# undo, and preserve the synchronous |
This comment has been minimized.
This comment has been minimized.
Tests Failure Analysis
🧪 CI Analysis — click to expand📊 maui-prNo failures found. 🧪 maui-pr-devicetests
These explain the Windows task's exit 1, not a separate compilation failure. 🧪 maui-pr-uitestsFive
🧭 Follow-up — actions and refreshNext action: Compare unresolved failures on unchanged
|
Preserve the ambiguity diagnostics pipeline alongside the original user compilation used to fingerprint repeated Hot Reload evaluations. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
|
Resolved the conflict with Preserved the target’s ambiguity-diagnostics pipeline alongside the PR’s original user-compilation input for Hot Reload source fingerprinting. Both pipelines remain intact, as do the repeated-evaluation patch behavior and the target’s resource-addition regression assertions. |
…valuation (#40233) <!-- 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! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change XAML Incremental Hot Reload (XIHR) keeps per-driver state in `XamlHotReloadState` and diffs the previous generation against the current one to emit `UpdateComponent()`. Roslyn can evaluate the **same driver snapshot more than once**: driver forks, speculative or design-time requests, and cancelled or discarded runs. The first evaluation advanced the cached "previous" XAML. Every later evaluation of the same inputs then saw `previous == current` and emitted an **empty** `UpdateComponent()`, which silently dropped the edit. @noiseonwires reproduced this deterministically on the issue (`edited.RunGenerators(c)` twice gives a patch, then an empty method) and matched it to captured VS deltas. **Fix (option 1 of the issue, extended):** - When a generation produces a patch, the cache entry also stores the **exact generation it was diffed from** (`PatchBaseline`). It also stores a `UserSourcesFingerprint` of the user C# sources it was produced with: path plus `SourceText.GetContentHash()` per tree, taken from the original compilation without the generated code-behind trees, and memoized per `Compilation`. - A later generation with the **same XAML and the same user sources** re-derives the identical patch from that baseline. - A generation with the same XAML but **different user sources** (a C#-only edit) still emits an empty `UpdateComponent()`. This preserves the runtime "non-empty body ⟺ XAML change" classification. It matters because patches aren't always idempotent (reorders use `RemoveAt`/`Insert`), so a stale patch must not be re-invoked on later C#-only edits of the same type. - The baseline is never dropped by such a run; only the next XAML edit replaces it. The output is therefore a function of the inputs, not of evaluation order. A side effect is that a pending patch also survives regeneration caused by edits to *other* XAML files. - Fingerprinting only runs for XIHR-enabled files that have a pending patch, so non-hot-reload and Release builds are unaffected. **Known limitation (needs the cross-team design discussed on the issue):** the generator can't tell "a discarded run with *different* C# evaluated the new XAML first, then the real run" apart from "a XAML edit, then a real C#-only edit". In both cases it sees a patch produced under fingerprint F1 followed by the same XAML under F2. The second case must stay empty, so the first case still loses the patch. Exactly reverting C# to the snapshot of the XAML edit would also re-emit the patch. Fully removing history-dependence needs the classification to move off the empty-`UpdateComponent()` signal, for example the per-document companion signal type @noiseonwires proposed. **Tests:** 7 new cases in `XamlIncrementalHotReloadPipelineTests`: forked runs of the same edited driver, the implicit-style `ResourceDictionary` repro shape from the issue, a discarded throwaway run, an interleaved run with different C#, an edit to another XAML file, a revert after forked runs, and a C#-only edit after a XAML edit staying empty. Five of them fail without the fix. The revert and C#-only cases guard existing behavior. **Validation:** - `dotnet test` SourceGen.UnitTests (run from a copy of the output in a path without `~`): **635 passed, 0 failed, 40 skipped**. - With the fix reverted: the 5 new regression tests fail. - `dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`: **2179 passed, 2 failed, 8 skipped**. The 2 failures (`TwoWayDecimalBinding_*`) are locale-dependent on the dev machine (comma decimal separator) and pass with `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1`. - `dotnet format whitespace --verify-no-changes` on the changed files: clean. ### Issues Fixed Fixes #36937 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
… different C# (#40330) <!-- 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! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). **Base note:** this is a follow-up to #40233, which was merged into `candidate/11.0.1xx-sr2` and is not in `net11` (or `main`) yet. This change modifies code that only exists there, so the PR targets `candidate/11.0.1xx-sr2`. For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change Follow-up to #40233, closing the gap it documented: if a **throwaway compilation with different user C#** (speculative or design-time snapshot) evaluates the edited XAML before the real compilation does, the pending `UpdateComponent()` patch is lost. The generator couldn't tell this apart from a genuine C#-only edit, which had to emit an *empty* `UpdateComponent()` because the runtime classified a delta as a XAML change by the emptiness of that body. **Fix: move the classification to a companion signal type, as @noiseonwires proposed on #36937.** The `MetadataUpdateHandler` is in this repo, so no Roslyn or hot reload agent changes are needed. - **Generator (`UpdateComponentCodeWriter`)**: the `.uc.xsg.cs` file now also nests a private `__XamlHotReloadSignal` type in each XIHR root, with `Fingerprint() => "<sha256 of the patch body>"` (`""` when there's no patch). It's emitted on every generation, like `UpdateComponent()`, so there's no member churn. Its content only changes when the patch changes, so Roslyn lists it in a delta exactly when there's a new patch to apply. - **Generator (`XamlGenerator` / `XamlHotReloadState`)**: when the XAML is unchanged and a patch is pending, the patch is always re-derived from its baseline, whatever the C# sources are. The output becomes a function of the inputs, not of evaluation order or of which compilation ran first. The `UserSourcesFingerprint` gate from #40233 (and the extra compilation input to the pipeline) is removed. - **Runtime (`XamlIncrementalHotReloadHandler`)**: a root that has the companion type counts as a XAML change only if the delta lists the companion **and** `UpdateComponent()` isn't empty. This keeps structural changes, which reset the body to empty, out, as before. A companion listed without its root is mapped back to the root. Roots without a companion (older generated code) keep the existing empty-body check. `UpdateRequested.HandledTypes` and the `UpdateApplied`/`UpdateSkipped`/`UpdateFailed` contract are unchanged. With this, a C#-only edit re-emits the same patch. `UpdateComponent()` and the companion are byte-identical, so they aren't in the delta and the patch isn't re-applied. This matters because patches aren't always idempotent: reorders use `RemoveAt`/`Insert`. As a side benefit, a XAML edit whose delta was rejected (e.g. it was combined with a C# rude edit) still carries its patch on the next generation instead of an empty body. **Remaining limitation (not addressed here):** a throwaway run with *different XAML* (e.g. an intermediate keystroke) still advances the cached "previous" XAML. The next real patch is then diffed from that intermediate state rather than from what the app last applied. Fixing that would need knowledge of the last applied generation. **Tests** - `XamlIncrementalHotReloadPipelineTests` - `ThrowawayRunWithDifferentCSharpFirst_DoesNotConsumePendingPatch` is the gap from #40233. It fails without the fix. - `CSharpOnlyEditAfterXamlEdit_KeepsPatchAndSignalUnchanged` replaces `CSharpOnlyEditAfterXamlEdit_EmitsEmptyUpdateComponent`, whose expectation is intentionally changed. - `SignalFingerprint_ChangesWithThePatchOnly`. - `XamlIncrementalHotReloadE2ETests` (real `MetadataUpdater.ApplyUpdate`) - `CSharpOnlyEditAfterXamlEdit_DoesNotReapplyPatch` checks that a live label changed at runtime isn't overwritten by a C#-only delta. - `UpdateRequested_ReportsXamlChange_WhenSignalTypeIsUpdated` updates the existing classification test. - The test harness now lists the companion type among the delta's updated types only when its fingerprint changed, like Roslyn does. - `Controls.Core.UnitTests/XamlIncrementalHotReloadHandlerTests`: two handler tests cover a root with a companion type and a companion listed alone. **Validation** - `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj`: **855 passed, 0 failed, 0 skipped**. - With only the generator/state change reverted, 3 new tests fail, including the throwaway test. With only the handler change reverted, the 2 E2E runtime tests fail. - `dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`: **2250 passed, 2 failed, 8 skipped**. The 2 failures (`TwoWayDecimalBinding_*`) depend on the dev machine's locale and pass with `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1`. - `dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --filter "FullyQualifiedName~HotReload"`: **12 passed**. - `dotnet format whitespace --verify-no-changes` on the changed files: clean. ### Issues Fixed Fixes #36937 Follow-up to #40233. --------- Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
<!-- 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! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). This PR targets `candidate/11.0.1xx-sr2`, not `net11`. It's a follow-up to #40235, which was merged into `candidate/11.0.1xx-sr2` and isn't in `net11` (or `main`) yet. The change builds on the code #40235 added. For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change Follow-up to #40235 (fix for #36156). #40235 rolls back the XAML Incremental Hot Reload state (`XamlHotReloadState.Restore`) when a XAML edit can't build. It checks three things: the generator reported an error, the generated IC/UC has C# **syntax** errors, or generation threw. It deliberately skipped **semantic** errors. Members added by other generators (CommunityToolkit.Mvvm `[ObservableProperty]` / `[RelayCommand]`) aren't visible to the XAML generator, so a naive type check would roll back valid edits. As a result, an edit that only fails type checking, such as `{Count.Nope()}` (CS1061), still advanced the baseline. The next valid edit was then diffed against a generation the app never received, and the changes made together with the rude edit were lost. **Fix:** `HasSemanticErrors` type-checks the generated `InitializeComponent` and `UpdateComponent` trees against the generator's compilation (user code plus generated code-behind). It runs only when a XAML edit was diffed, i.e. when a rollback snapshot exists. An error counts only if: - it is located in the generated IC/UC code (errors in user code are ignored), and - `MayBeFixedByAnotherGenerator` returns false for it. That helper ignores errors that a declaration added by another generator could resolve: - unresolved names, types and namespaces (CS0103, CS0234, CS0246, CS0426); - failed member lookup (CS1061, CS0117, …) or overload resolution on a receiver whose type is a **`partial` type declared in source**, the only kind of type other generators can add members to. This also covers `?.` member bindings, implicit-`this` invocations, object creations, and errors reported on an argument. **Options considered:** - *Defer the baseline commit until a later signal confirms the compile.* Rejected: inside the generator there is no such signal. The next run's input compilation never contains the previous output, and nothing tells the generator whether the emit or EnC apply succeeded. - *Count all semantic errors.* Rejected: false rollbacks for MVVM Toolkit members. A false positive is worse than a miss, because the next patch re-adds children that are already live. - *Restrict to diagnostics attributable to XAML-generated code and filter out what another generator could fix.* Chosen. **Known remaining gap:** a lookup on a non-`partial` or metadata type (e.g. `int`) that only an extension method from *another generator* could satisfy still counts as an error. That's rare in XAML expressions. C# 14 extension members generated elsewhere fall in the same case. `XamlHotReloadState` is unchanged. The change is limited to `XamlGenerator.cs`, to keep conflicts with the #40233 follow-up low. **Tests** (`XamlIncrementalHotReloadRudeEditTests`): - `EditAfterRudeEdit_IsDiffedAgainstLastAppliedGeneration(Semantic)`: new case for a type-check-only rude edit, `{Count.Nope()}`. The theory parameter changed from `bool` to a `RudeEdit` enum. - `ElementAddedWithSemanticRudeEdit_IsAddedOnceTheEditIsFixed`: an element added together with a semantic rude edit is added once the edit is fixed. - `MembersGeneratedByAnotherGenerator_DoNotRollBack`: guard. The view model uses `[ObservableProperty]` and `[RelayCommand]`, and the XAML references `Count` (C# expression) and `{Binding SaveCommand}`. The previous edit must not be rolled back, so the added `Button` isn't added again. Without the fix, the 2 semantic cases fail. With `MayBeFixedByAnotherGenerator` disabled, the guard fails. **Validation:** - `dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj --filter FullyQualifiedName~XamlIncrementalHotReloadRudeEditTests`: **9 passed**. Before the fix: 2 failed (the semantic cases), 7 passed. With the filter disabled: 1 failed (the MVVM guard). - `dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj` (full suite): **772 passed, 0 failed, 53 skipped**. - `dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj` with `-p:IncludeAndroidTargetFrameworks=false -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -p:IncludeMacOSTargetFrameworks=false`. The mobile TFMs were excluded because of a local workload mismatch. Result: **2250 passed, 2 failed, 8 skipped**. The 2 failures (`TwoWayDecimalBinding_*`) are known and depend on the machine's locale. - `dotnet format whitespace --folder --include <changed files> --verify-no-changes`: clean. ### Issues Fixed Follow-up to #40235. Relates to #36156. <!-- Verify the target branch follows the release workflow in docs/ReleaseBranchWorkflow.md. Infrastructure and documentation changes should target the branch where they apply. --> --------- Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
…ns (#40378) <!-- 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! ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). > [!IMPORTANT] > **Base: `candidate/11.0.1xx-sr2` (decided).** This PR builds on #40233, #40235, #40329 and #40330, which exist only on `candidate/11.0.1xx-sr2` (not on `net11`, `main` or `inflight/11.0.1xx-sr3`). Against `net11` the diff would include about 527 unrelated files. As with #40329 and #40330, it targets `candidate/11.0.1xx-sr2` directly so it ships together with its prerequisites. ### Description of Change #40330 left one limitation. A throwaway generator run with different XAML, such as a design-time or speculative run whose output never reaches the app, advanced the cached previous XAML. The next real `UpdateComponent()` was then diffed from that intermediate generation instead of the generation the running app actually has. The result was missed edits: for example, an edit already present in the throwaway XAML was never applied. The generator cannot tell which of its runs reached the app, so this PR has `UpdateComponent()` decide at runtime: - **Generation key.** Each successful generation gets a key: a SHA-256 of the normalized XAML plus the node IDs (`NodeIdHelper.ComputeGenerationKey`). `XamlHotReloadState` keeps the current generation and the previously generated ones as baselines, up to `MaxBaselines = 4`. - **InitializeComponent** records `XamlComponentRegistry.Register(this, "__xihr_generation:<type>", key)`. - **UpdateComponent** reads the instance's recorded key: - A retained generation whose diff produces exactly the current node IDs gets its own branch: the patch diffed from that generation. - Anything else gets the default patch, diffed from the last generated XAML. This matches the previous behavior. - Every patched instance then records the new key, so running the patch again, or for a C#-only edit, changes nothing. - When there is nothing to patch, the output is unchanged: an empty UC, with no marker. Rude-edit rollback behavior is preserved, and the older applied generation now also gets its own branch. **Known edge, not a regression:** a retained generation whose diff would assign different IDs from the current ones (e.g. some reverts) is not given a branch. Instances at that generation fall back to the default patch, which is the old behavior. ### Issues Fixed Fixes #36937 (remaining limitation from #40330) ### Tests - `XamlIncrementalHotReloadE2ETests.ThrowawayRunWithDifferentXaml_PatchStartsFromTheAppliedGeneration`: real metadata update. Applied `Text="Hello"`, then a throwaway run with `Text="World" FontSize="30"`, then the real edit to `Text="World"`. The live label ends at `World` with its default `FontSize`, re-running UC is a no-op, and new instances are already current. A new harness hook, `GenerateWithThrowawayRuns`, runs and discards a forked driver run. - `XamlIncrementalHotReloadPipelineTests.ThrowawayRunWithDifferentXaml_PatchesFromEveryRetainedGeneration`: checks the branch structure and determinism (same snapshot and C#-only edits give an identical UC). - `XamlIncrementalHotReloadPipelineTests.RetainedGenerations_AreBounded` - Existing rude-edit assertions now target the default patch (`UpdateComponentText.DefaultPatch`), because the UC legitimately contains a branch for the older applied generation. ### Validation - `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj`: **passed**, 899/899. - `dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --filter "FullyQualifiedName~HotReload"`: **passed**, 12/12. - `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1 dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`: 2274 passed, 12 failed. All 12 failures are `CultureNotFoundException` from culture-specific tests under invariant-globalization mode; none involve hot reload. - `dotnet format whitespace Microsoft.Maui.sln --verify-no-changes --include <changed files>`: **passed**. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…40413) (#40417) <!-- 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! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). **Base is `candidate/11.0.1xx-sr2`, not `net11`.** The PR is test-only and covers behavior that exists only on the candidate branch, from the #36937 fix chain #40233, #40235, #40329, #40330, and #40378. Against `net11` the test fails, because that fix has not flowed there yet. This follows the precedent of #40329, #40330, and #40378, which targeted this branch for the same reason. Maintainers: retarget if you prefer a different lane. For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change #40413 reports that in VS on Windows (.NET 11, SourceGen inflator, XAML Incremental Hot Reload on by default in Debug), editing a Label's `Text` in the default template's `MainPage.xaml` is not applied. **Root cause.** This is #36937. Roslyn/VS evaluate the same edited generator-driver snapshot more than once, for example forked or speculative runs, or a throwaway compilation before the applied one. On `net11`, the first evaluation advances the cached previous XAML. The evaluation that is actually applied then sees no diff and emits an empty `UpdateComponent`, and the runtime silently skips it. The bug became visible in .NET 11 because XIHR is now the default; 10.0.120 used legacy XAML Hot Reload. I reproduced this with the issue's own template `MainPage.xaml` through the source generator: | Sequence | `net11` (a25e629) | `candidate/11.0.1xx-sr2` (cec6650) | | --- | --- | --- | | Edit evaluated once | patch | patch | | Same edited snapshot evaluated twice: 2nd run | **empty UC** | patch | | Throwaway compilation first, then real run: real run | **empty UC** | patch | On the candidate branch the existing fixes already handle this. This PR adds `DefaultTemplateMainPageTextEdit_SurvivesRepeatedAndThrowawayEvaluations`, a theory with repeated and throwaway-first cases. It uses the template page shape (`StaticResource` styles from a sibling `Styles.xaml`, `x:Name`, a `Clicked` handler in code-behind) to lock in the reported scenario. There are no product changes. **Android .NET 10 (validation comment).** This is a separate scenario. XIHR was not the default in .NET 10, so that report involves the legacy XAML Hot Reload path and is not caused by this regression. It is not addressed here. **Validation** - `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj --filter "FullyQualifiedName~XamlIncrementalHotReloadPipelineTests|FullyQualifiedName~CodeBehindFieldStabilityTests"`: **passed**, 93/93, on this branch. - `net11`: the same two sequences, run through an equivalent temporary probe with the template XAML, produce an empty UC, as shown in the table. I did not port the committed test itself to `net11`: its helpers exist only on candidate, and reverting the fix commits in place conflicts. - Not verified in Visual Studio on Windows or on device; I worked on a macOS host. ### Issues Fixed Fixes #40413 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…valuation (#40233) <!-- 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! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change XAML Incremental Hot Reload (XIHR) keeps per-driver state in `XamlHotReloadState` and diffs the previous generation against the current one to emit `UpdateComponent()`. Roslyn can evaluate the **same driver snapshot more than once**: driver forks, speculative or design-time requests, and cancelled or discarded runs. The first evaluation advanced the cached "previous" XAML. Every later evaluation of the same inputs then saw `previous == current` and emitted an **empty** `UpdateComponent()`, which silently dropped the edit. @noiseonwires reproduced this deterministically on the issue (`edited.RunGenerators(c)` twice gives a patch, then an empty method) and matched it to captured VS deltas. **Fix (option 1 of the issue, extended):** - When a generation produces a patch, the cache entry also stores the **exact generation it was diffed from** (`PatchBaseline`). It also stores a `UserSourcesFingerprint` of the user C# sources it was produced with: path plus `SourceText.GetContentHash()` per tree, taken from the original compilation without the generated code-behind trees, and memoized per `Compilation`. - A later generation with the **same XAML and the same user sources** re-derives the identical patch from that baseline. - A generation with the same XAML but **different user sources** (a C#-only edit) still emits an empty `UpdateComponent()`. This preserves the runtime "non-empty body ⟺ XAML change" classification. It matters because patches aren't always idempotent (reorders use `RemoveAt`/`Insert`), so a stale patch must not be re-invoked on later C#-only edits of the same type. - The baseline is never dropped by such a run; only the next XAML edit replaces it. The output is therefore a function of the inputs, not of evaluation order. A side effect is that a pending patch also survives regeneration caused by edits to *other* XAML files. - Fingerprinting only runs for XIHR-enabled files that have a pending patch, so non-hot-reload and Release builds are unaffected. **Known limitation (needs the cross-team design discussed on the issue):** the generator can't tell "a discarded run with *different* C# evaluated the new XAML first, then the real run" apart from "a XAML edit, then a real C#-only edit". In both cases it sees a patch produced under fingerprint F1 followed by the same XAML under F2. The second case must stay empty, so the first case still loses the patch. Exactly reverting C# to the snapshot of the XAML edit would also re-emit the patch. Fully removing history-dependence needs the classification to move off the empty-`UpdateComponent()` signal, for example the per-document companion signal type @noiseonwires proposed. **Tests:** 7 new cases in `XamlIncrementalHotReloadPipelineTests`: forked runs of the same edited driver, the implicit-style `ResourceDictionary` repro shape from the issue, a discarded throwaway run, an interleaved run with different C#, an edit to another XAML file, a revert after forked runs, and a C#-only edit after a XAML edit staying empty. Five of them fail without the fix. The revert and C#-only cases guard existing behavior. **Validation:** - `dotnet test` SourceGen.UnitTests (run from a copy of the output in a path without `~`): **635 passed, 0 failed, 40 skipped**. - With the fix reverted: the 5 new regression tests fail. - `dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`: **2179 passed, 2 failed, 8 skipped**. The 2 failures (`TwoWayDecimalBinding_*`) are locale-dependent on the dev machine (comma decimal separator) and pass with `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1`. - `dotnet format whitespace --verify-no-changes` on the changed files: clean. ### Issues Fixed Fixes #36937 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
<!-- 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! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change XAML Incremental Hot Reload (XIHR) keeps per-file state in `XamlHotReloadState` (last XAML, parsed tree, node IDs) and emits `UpdateComponent()` as a diff from the previous generation to the current one. A **rude edit** is a XAML edit whose generated code doesn't compile, for example a malformed XAML C# expression, or an error reported by the generator such as an unresolved member. The build fails, so that edit never reaches the running app. The state had already moved to the broken generation, though. The next, fixed edit was then diffed against the broken generation, not against what the app is running. Changes made together with the rude edit were never applied: property sets, and elements added in the same edit. They stayed lost until a full restart. **Fix:** - Before diffing a XAML edit, the generator captures a copy of the file's state entry (`XamlHotReloadState.Capture`). - After generating `InitializeComponent` and `UpdateComponent`, it restores that entry (`XamlHotReloadState.Restore`) when the generation can't build: - the generator reported an error while generating `InitializeComponent`. A new optional `diagnosticObserver` on `GenerateInitializeComponent` reports these. User severity overrides are honored (`NoWarn`, `WarningsNotAsErrors`, `.editorconfig`/`.globalconfig`), so a downgraded MAUIX error doesn't count; - or the generated IC/UC code has C# **syntax** errors; - or generation throws. - The next edit is then diffed against the last generation that could have been applied. Its patch also carries the changes made together with the rude edit. Re-evaluating the rude edit is deterministic, and reverting to the applied XAML is "no change". **Deliberately not checked: semantic C# errors** in the generated code, such as `{Count.Nope()}` (CS1061). Generated code can legitimately reference members that other generators add later, such as CommunityToolkit.Mvvm `[ObservableProperty]` / `[RelayCommand]`, which `ITypeSymbolExtensions` already infers. A false positive is worse than a miss: it pins the state to a generation the app has already moved past, and the next patch would re-add children, for example. Those edits keep today's behavior. A C#-only compile failure that happens at the same time as a XAML edit is also out of scope. **Interaction with #40233 (fix for #36937):** The two are independent, so this PR is not stacked on #40233. #40233 adds `PatchBaseline`/`PatchSources` to `CacheEntry` and replays the pending patch when the same inputs are evaluated again. This PR snapshots and restores the whole `CacheEntry` with `MemberwiseClone`, so after a rebase, rolling back a rude edit also restores those fields. The restored state is exactly what the applied generation left, so the output for identical inputs stays identical. Expected conflicts are textual only, in `XamlGenerator.cs` (adjacent lines in the IC output callback) and `XamlHotReloadState.cs`. The new tests are in their own file to avoid conflicts in `XamlIncrementalHotReloadPipelineTests.cs`. **Tests:** new `XamlIncrementalHotReloadRudeEditTests` (6 cases): - an edit after a rude edit carries the changes made with the rude edit, for both a C# syntax error and a generator-reported error (MAUIX2009); - an element added with a rude edit is added once the edit is fixed; - reverting after a rude edit emits the same output as the applied state; - repeated evaluation of a rude edit is deterministic; - an error the user downgraded doesn't roll back (no duplicate element). The first 5 cases fail without the fix. The downgrade case fails if the severity lookup is removed. **Validation:** - `dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj --filter XamlIncrementalHotReloadRudeEditTests`: 6 passed; 5 failed before the fix. - SourceGen.UnitTests, full suite. It was run from a copy of the output in a path without `~`, because the `XTypeMultiFileHotReloadTests` fail when the path contains `~`. Result: **634 passed, 0 failed, 40 skipped**. - `dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`, built with Apple/Android TFMs excluded because of a local workload mismatch. Result: **2179 passed, 2 failed, 8 skipped**. The 2 failures (`TwoWayDecimalBinding_*`) depend on the dev machine's locale (comma decimal separator) and pass with `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1`. - `dotnet format whitespace --verify-no-changes` on the changed files: clean. ### Issues Fixed Fixes #36156 <!-- Verify the target branch follows the release workflow in docs/ReleaseBranchWorkflow.md. Infrastructure and documentation changes should target the branch where they apply. --> --------- Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
… different C# (#40330) <!-- 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! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). **Base note:** this is a follow-up to #40233, which was merged into `candidate/11.0.1xx-sr2` and is not in `net11` (or `main`) yet. This change modifies code that only exists there, so the PR targets `candidate/11.0.1xx-sr2`. For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change Follow-up to #40233, closing the gap it documented: if a **throwaway compilation with different user C#** (speculative or design-time snapshot) evaluates the edited XAML before the real compilation does, the pending `UpdateComponent()` patch is lost. The generator couldn't tell this apart from a genuine C#-only edit, which had to emit an *empty* `UpdateComponent()` because the runtime classified a delta as a XAML change by the emptiness of that body. **Fix: move the classification to a companion signal type, as @noiseonwires proposed on #36937.** The `MetadataUpdateHandler` is in this repo, so no Roslyn or hot reload agent changes are needed. - **Generator (`UpdateComponentCodeWriter`)**: the `.uc.xsg.cs` file now also nests a private `__XamlHotReloadSignal` type in each XIHR root, with `Fingerprint() => "<sha256 of the patch body>"` (`""` when there's no patch). It's emitted on every generation, like `UpdateComponent()`, so there's no member churn. Its content only changes when the patch changes, so Roslyn lists it in a delta exactly when there's a new patch to apply. - **Generator (`XamlGenerator` / `XamlHotReloadState`)**: when the XAML is unchanged and a patch is pending, the patch is always re-derived from its baseline, whatever the C# sources are. The output becomes a function of the inputs, not of evaluation order or of which compilation ran first. The `UserSourcesFingerprint` gate from #40233 (and the extra compilation input to the pipeline) is removed. - **Runtime (`XamlIncrementalHotReloadHandler`)**: a root that has the companion type counts as a XAML change only if the delta lists the companion **and** `UpdateComponent()` isn't empty. This keeps structural changes, which reset the body to empty, out, as before. A companion listed without its root is mapped back to the root. Roots without a companion (older generated code) keep the existing empty-body check. `UpdateRequested.HandledTypes` and the `UpdateApplied`/`UpdateSkipped`/`UpdateFailed` contract are unchanged. With this, a C#-only edit re-emits the same patch. `UpdateComponent()` and the companion are byte-identical, so they aren't in the delta and the patch isn't re-applied. This matters because patches aren't always idempotent: reorders use `RemoveAt`/`Insert`. As a side benefit, a XAML edit whose delta was rejected (e.g. it was combined with a C# rude edit) still carries its patch on the next generation instead of an empty body. **Remaining limitation (not addressed here):** a throwaway run with *different XAML* (e.g. an intermediate keystroke) still advances the cached "previous" XAML. The next real patch is then diffed from that intermediate state rather than from what the app last applied. Fixing that would need knowledge of the last applied generation. **Tests** - `XamlIncrementalHotReloadPipelineTests` - `ThrowawayRunWithDifferentCSharpFirst_DoesNotConsumePendingPatch` is the gap from #40233. It fails without the fix. - `CSharpOnlyEditAfterXamlEdit_KeepsPatchAndSignalUnchanged` replaces `CSharpOnlyEditAfterXamlEdit_EmitsEmptyUpdateComponent`, whose expectation is intentionally changed. - `SignalFingerprint_ChangesWithThePatchOnly`. - `XamlIncrementalHotReloadE2ETests` (real `MetadataUpdater.ApplyUpdate`) - `CSharpOnlyEditAfterXamlEdit_DoesNotReapplyPatch` checks that a live label changed at runtime isn't overwritten by a C#-only delta. - `UpdateRequested_ReportsXamlChange_WhenSignalTypeIsUpdated` updates the existing classification test. - The test harness now lists the companion type among the delta's updated types only when its fingerprint changed, like Roslyn does. - `Controls.Core.UnitTests/XamlIncrementalHotReloadHandlerTests`: two handler tests cover a root with a companion type and a companion listed alone. **Validation** - `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj`: **855 passed, 0 failed, 0 skipped**. - With only the generator/state change reverted, 3 new tests fail, including the throwaway test. With only the handler change reverted, the 2 E2E runtime tests fail. - `dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`: **2250 passed, 2 failed, 8 skipped**. The 2 failures (`TwoWayDecimalBinding_*`) depend on the dev machine's locale and pass with `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1`. - `dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --filter "FullyQualifiedName~HotReload"`: **12 passed**. - `dotnet format whitespace --verify-no-changes` on the changed files: clean. ### Issues Fixed Fixes #36937 Follow-up to #40233. --------- Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
<!-- 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! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). This PR targets `candidate/11.0.1xx-sr2`, not `net11`. It's a follow-up to #40235, which was merged into `candidate/11.0.1xx-sr2` and isn't in `net11` (or `main`) yet. The change builds on the code #40235 added. For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change Follow-up to #40235 (fix for #36156). #40235 rolls back the XAML Incremental Hot Reload state (`XamlHotReloadState.Restore`) when a XAML edit can't build. It checks three things: the generator reported an error, the generated IC/UC has C# **syntax** errors, or generation threw. It deliberately skipped **semantic** errors. Members added by other generators (CommunityToolkit.Mvvm `[ObservableProperty]` / `[RelayCommand]`) aren't visible to the XAML generator, so a naive type check would roll back valid edits. As a result, an edit that only fails type checking, such as `{Count.Nope()}` (CS1061), still advanced the baseline. The next valid edit was then diffed against a generation the app never received, and the changes made together with the rude edit were lost. **Fix:** `HasSemanticErrors` type-checks the generated `InitializeComponent` and `UpdateComponent` trees against the generator's compilation (user code plus generated code-behind). It runs only when a XAML edit was diffed, i.e. when a rollback snapshot exists. An error counts only if: - it is located in the generated IC/UC code (errors in user code are ignored), and - `MayBeFixedByAnotherGenerator` returns false for it. That helper ignores errors that a declaration added by another generator could resolve: - unresolved names, types and namespaces (CS0103, CS0234, CS0246, CS0426); - failed member lookup (CS1061, CS0117, …) or overload resolution on a receiver whose type is a **`partial` type declared in source**, the only kind of type other generators can add members to. This also covers `?.` member bindings, implicit-`this` invocations, object creations, and errors reported on an argument. **Options considered:** - *Defer the baseline commit until a later signal confirms the compile.* Rejected: inside the generator there is no such signal. The next run's input compilation never contains the previous output, and nothing tells the generator whether the emit or EnC apply succeeded. - *Count all semantic errors.* Rejected: false rollbacks for MVVM Toolkit members. A false positive is worse than a miss, because the next patch re-adds children that are already live. - *Restrict to diagnostics attributable to XAML-generated code and filter out what another generator could fix.* Chosen. **Known remaining gap:** a lookup on a non-`partial` or metadata type (e.g. `int`) that only an extension method from *another generator* could satisfy still counts as an error. That's rare in XAML expressions. C# 14 extension members generated elsewhere fall in the same case. `XamlHotReloadState` is unchanged. The change is limited to `XamlGenerator.cs`, to keep conflicts with the #40233 follow-up low. **Tests** (`XamlIncrementalHotReloadRudeEditTests`): - `EditAfterRudeEdit_IsDiffedAgainstLastAppliedGeneration(Semantic)`: new case for a type-check-only rude edit, `{Count.Nope()}`. The theory parameter changed from `bool` to a `RudeEdit` enum. - `ElementAddedWithSemanticRudeEdit_IsAddedOnceTheEditIsFixed`: an element added together with a semantic rude edit is added once the edit is fixed. - `MembersGeneratedByAnotherGenerator_DoNotRollBack`: guard. The view model uses `[ObservableProperty]` and `[RelayCommand]`, and the XAML references `Count` (C# expression) and `{Binding SaveCommand}`. The previous edit must not be rolled back, so the added `Button` isn't added again. Without the fix, the 2 semantic cases fail. With `MayBeFixedByAnotherGenerator` disabled, the guard fails. **Validation:** - `dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj --filter FullyQualifiedName~XamlIncrementalHotReloadRudeEditTests`: **9 passed**. Before the fix: 2 failed (the semantic cases), 7 passed. With the filter disabled: 1 failed (the MVVM guard). - `dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj` (full suite): **772 passed, 0 failed, 53 skipped**. - `dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj` with `-p:IncludeAndroidTargetFrameworks=false -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -p:IncludeMacOSTargetFrameworks=false`. The mobile TFMs were excluded because of a local workload mismatch. Result: **2250 passed, 2 failed, 8 skipped**. The 2 failures (`TwoWayDecimalBinding_*`) are known and depend on the machine's locale. - `dotnet format whitespace --folder --include <changed files> --verify-no-changes`: clean. ### Issues Fixed Follow-up to #40235. Relates to #36156. <!-- Verify the target branch follows the release workflow in docs/ReleaseBranchWorkflow.md. Infrastructure and documentation changes should target the branch where they apply. --> --------- Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
…ns (#40378) <!-- 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! ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). > [!IMPORTANT] > **Base: `candidate/11.0.1xx-sr2` (decided).** This PR builds on #40233, #40235, #40329 and #40330, which exist only on `candidate/11.0.1xx-sr2` (not on `net11`, `main` or `inflight/11.0.1xx-sr3`). Against `net11` the diff would include about 527 unrelated files. As with #40329 and #40330, it targets `candidate/11.0.1xx-sr2` directly so it ships together with its prerequisites. ### Description of Change #40330 left one limitation. A throwaway generator run with different XAML, such as a design-time or speculative run whose output never reaches the app, advanced the cached previous XAML. The next real `UpdateComponent()` was then diffed from that intermediate generation instead of the generation the running app actually has. The result was missed edits: for example, an edit already present in the throwaway XAML was never applied. The generator cannot tell which of its runs reached the app, so this PR has `UpdateComponent()` decide at runtime: - **Generation key.** Each successful generation gets a key: a SHA-256 of the normalized XAML plus the node IDs (`NodeIdHelper.ComputeGenerationKey`). `XamlHotReloadState` keeps the current generation and the previously generated ones as baselines, up to `MaxBaselines = 4`. - **InitializeComponent** records `XamlComponentRegistry.Register(this, "__xihr_generation:<type>", key)`. - **UpdateComponent** reads the instance's recorded key: - A retained generation whose diff produces exactly the current node IDs gets its own branch: the patch diffed from that generation. - Anything else gets the default patch, diffed from the last generated XAML. This matches the previous behavior. - Every patched instance then records the new key, so running the patch again, or for a C#-only edit, changes nothing. - When there is nothing to patch, the output is unchanged: an empty UC, with no marker. Rude-edit rollback behavior is preserved, and the older applied generation now also gets its own branch. **Known edge, not a regression:** a retained generation whose diff would assign different IDs from the current ones (e.g. some reverts) is not given a branch. Instances at that generation fall back to the default patch, which is the old behavior. ### Issues Fixed Fixes #36937 (remaining limitation from #40330) ### Tests - `XamlIncrementalHotReloadE2ETests.ThrowawayRunWithDifferentXaml_PatchStartsFromTheAppliedGeneration`: real metadata update. Applied `Text="Hello"`, then a throwaway run with `Text="World" FontSize="30"`, then the real edit to `Text="World"`. The live label ends at `World` with its default `FontSize`, re-running UC is a no-op, and new instances are already current. A new harness hook, `GenerateWithThrowawayRuns`, runs and discards a forked driver run. - `XamlIncrementalHotReloadPipelineTests.ThrowawayRunWithDifferentXaml_PatchesFromEveryRetainedGeneration`: checks the branch structure and determinism (same snapshot and C#-only edits give an identical UC). - `XamlIncrementalHotReloadPipelineTests.RetainedGenerations_AreBounded` - Existing rude-edit assertions now target the default patch (`UpdateComponentText.DefaultPatch`), because the UC legitimately contains a branch for the older applied generation. ### Validation - `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj`: **passed**, 899/899. - `dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --filter "FullyQualifiedName~HotReload"`: **passed**, 12/12. - `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1 dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`: 2274 passed, 12 failed. All 12 failures are `CultureNotFoundException` from culture-specific tests under invariant-globalization mode; none involve hot reload. - `dotnet format whitespace Microsoft.Maui.sln --verify-no-changes --include <changed files>`: **passed**. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…40413) (#40417) <!-- 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! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). **Base is `candidate/11.0.1xx-sr2`, not `net11`.** The PR is test-only and covers behavior that exists only on the candidate branch, from the #36937 fix chain #40233, #40235, #40329, #40330, and #40378. Against `net11` the test fails, because that fix has not flowed there yet. This follows the precedent of #40329, #40330, and #40378, which targeted this branch for the same reason. Maintainers: retarget if you prefer a different lane. For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change #40413 reports that in VS on Windows (.NET 11, SourceGen inflator, XAML Incremental Hot Reload on by default in Debug), editing a Label's `Text` in the default template's `MainPage.xaml` is not applied. **Root cause.** This is #36937. Roslyn/VS evaluate the same edited generator-driver snapshot more than once, for example forked or speculative runs, or a throwaway compilation before the applied one. On `net11`, the first evaluation advances the cached previous XAML. The evaluation that is actually applied then sees no diff and emits an empty `UpdateComponent`, and the runtime silently skips it. The bug became visible in .NET 11 because XIHR is now the default; 10.0.120 used legacy XAML Hot Reload. I reproduced this with the issue's own template `MainPage.xaml` through the source generator: | Sequence | `net11` (a25e629) | `candidate/11.0.1xx-sr2` (cec6650) | | --- | --- | --- | | Edit evaluated once | patch | patch | | Same edited snapshot evaluated twice: 2nd run | **empty UC** | patch | | Throwaway compilation first, then real run: real run | **empty UC** | patch | On the candidate branch the existing fixes already handle this. This PR adds `DefaultTemplateMainPageTextEdit_SurvivesRepeatedAndThrowawayEvaluations`, a theory with repeated and throwaway-first cases. It uses the template page shape (`StaticResource` styles from a sibling `Styles.xaml`, `x:Name`, a `Clicked` handler in code-behind) to lock in the reported scenario. There are no product changes. **Android .NET 10 (validation comment).** This is a separate scenario. XIHR was not the default in .NET 10, so that report involves the legacy XAML Hot Reload path and is not caused by this regression. It is not addressed here. **Validation** - `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj --filter "FullyQualifiedName~XamlIncrementalHotReloadPipelineTests|FullyQualifiedName~CodeBehindFieldStabilityTests"`: **passed**, 93/93, on this branch. - `net11`: the same two sequences, run through an equivalent temporary probe with the template XAML, produce an empty UC, as shown in the table. I did not port the committed test itself to `net11`: its helpers exist only on candidate, and reverting the fix commits in place conflicts. - Not verified in Visual Studio on Windows or on device; I worked on a macOS host. ### Issues Fixed Fixes #40413 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…valuation (#40233) <!-- 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! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change XAML Incremental Hot Reload (XIHR) keeps per-driver state in `XamlHotReloadState` and diffs the previous generation against the current one to emit `UpdateComponent()`. Roslyn can evaluate the **same driver snapshot more than once**: driver forks, speculative or design-time requests, and cancelled or discarded runs. The first evaluation advanced the cached "previous" XAML. Every later evaluation of the same inputs then saw `previous == current` and emitted an **empty** `UpdateComponent()`, which silently dropped the edit. @noiseonwires reproduced this deterministically on the issue (`edited.RunGenerators(c)` twice gives a patch, then an empty method) and matched it to captured VS deltas. **Fix (option 1 of the issue, extended):** - When a generation produces a patch, the cache entry also stores the **exact generation it was diffed from** (`PatchBaseline`). It also stores a `UserSourcesFingerprint` of the user C# sources it was produced with: path plus `SourceText.GetContentHash()` per tree, taken from the original compilation without the generated code-behind trees, and memoized per `Compilation`. - A later generation with the **same XAML and the same user sources** re-derives the identical patch from that baseline. - A generation with the same XAML but **different user sources** (a C#-only edit) still emits an empty `UpdateComponent()`. This preserves the runtime "non-empty body ⟺ XAML change" classification. It matters because patches aren't always idempotent (reorders use `RemoveAt`/`Insert`), so a stale patch must not be re-invoked on later C#-only edits of the same type. - The baseline is never dropped by such a run; only the next XAML edit replaces it. The output is therefore a function of the inputs, not of evaluation order. A side effect is that a pending patch also survives regeneration caused by edits to *other* XAML files. - Fingerprinting only runs for XIHR-enabled files that have a pending patch, so non-hot-reload and Release builds are unaffected. **Known limitation (needs the cross-team design discussed on the issue):** the generator can't tell "a discarded run with *different* C# evaluated the new XAML first, then the real run" apart from "a XAML edit, then a real C#-only edit". In both cases it sees a patch produced under fingerprint F1 followed by the same XAML under F2. The second case must stay empty, so the first case still loses the patch. Exactly reverting C# to the snapshot of the XAML edit would also re-emit the patch. Fully removing history-dependence needs the classification to move off the empty-`UpdateComponent()` signal, for example the per-document companion signal type @noiseonwires proposed. **Tests:** 7 new cases in `XamlIncrementalHotReloadPipelineTests`: forked runs of the same edited driver, the implicit-style `ResourceDictionary` repro shape from the issue, a discarded throwaway run, an interleaved run with different C#, an edit to another XAML file, a revert after forked runs, and a C#-only edit after a XAML edit staying empty. Five of them fail without the fix. The revert and C#-only cases guard existing behavior. **Validation:** - `dotnet test` SourceGen.UnitTests (run from a copy of the output in a path without `~`): **635 passed, 0 failed, 40 skipped**. - With the fix reverted: the 5 new regression tests fail. - `dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`: **2179 passed, 2 failed, 8 skipped**. The 2 failures (`TwoWayDecimalBinding_*`) are locale-dependent on the dev machine (comma decimal separator) and pass with `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1`. - `dotnet format whitespace --verify-no-changes` on the changed files: clean. ### Issues Fixed Fixes #36937 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
<!-- 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! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change XAML Incremental Hot Reload (XIHR) keeps per-file state in `XamlHotReloadState` (last XAML, parsed tree, node IDs) and emits `UpdateComponent()` as a diff from the previous generation to the current one. A **rude edit** is a XAML edit whose generated code doesn't compile, for example a malformed XAML C# expression, or an error reported by the generator such as an unresolved member. The build fails, so that edit never reaches the running app. The state had already moved to the broken generation, though. The next, fixed edit was then diffed against the broken generation, not against what the app is running. Changes made together with the rude edit were never applied: property sets, and elements added in the same edit. They stayed lost until a full restart. **Fix:** - Before diffing a XAML edit, the generator captures a copy of the file's state entry (`XamlHotReloadState.Capture`). - After generating `InitializeComponent` and `UpdateComponent`, it restores that entry (`XamlHotReloadState.Restore`) when the generation can't build: - the generator reported an error while generating `InitializeComponent`. A new optional `diagnosticObserver` on `GenerateInitializeComponent` reports these. User severity overrides are honored (`NoWarn`, `WarningsNotAsErrors`, `.editorconfig`/`.globalconfig`), so a downgraded MAUIX error doesn't count; - or the generated IC/UC code has C# **syntax** errors; - or generation throws. - The next edit is then diffed against the last generation that could have been applied. Its patch also carries the changes made together with the rude edit. Re-evaluating the rude edit is deterministic, and reverting to the applied XAML is "no change". **Deliberately not checked: semantic C# errors** in the generated code, such as `{Count.Nope()}` (CS1061). Generated code can legitimately reference members that other generators add later, such as CommunityToolkit.Mvvm `[ObservableProperty]` / `[RelayCommand]`, which `ITypeSymbolExtensions` already infers. A false positive is worse than a miss: it pins the state to a generation the app has already moved past, and the next patch would re-add children, for example. Those edits keep today's behavior. A C#-only compile failure that happens at the same time as a XAML edit is also out of scope. **Interaction with #40233 (fix for #36937):** The two are independent, so this PR is not stacked on #40233. #40233 adds `PatchBaseline`/`PatchSources` to `CacheEntry` and replays the pending patch when the same inputs are evaluated again. This PR snapshots and restores the whole `CacheEntry` with `MemberwiseClone`, so after a rebase, rolling back a rude edit also restores those fields. The restored state is exactly what the applied generation left, so the output for identical inputs stays identical. Expected conflicts are textual only, in `XamlGenerator.cs` (adjacent lines in the IC output callback) and `XamlHotReloadState.cs`. The new tests are in their own file to avoid conflicts in `XamlIncrementalHotReloadPipelineTests.cs`. **Tests:** new `XamlIncrementalHotReloadRudeEditTests` (6 cases): - an edit after a rude edit carries the changes made with the rude edit, for both a C# syntax error and a generator-reported error (MAUIX2009); - an element added with a rude edit is added once the edit is fixed; - reverting after a rude edit emits the same output as the applied state; - repeated evaluation of a rude edit is deterministic; - an error the user downgraded doesn't roll back (no duplicate element). The first 5 cases fail without the fix. The downgrade case fails if the severity lookup is removed. **Validation:** - `dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj --filter XamlIncrementalHotReloadRudeEditTests`: 6 passed; 5 failed before the fix. - SourceGen.UnitTests, full suite. It was run from a copy of the output in a path without `~`, because the `XTypeMultiFileHotReloadTests` fail when the path contains `~`. Result: **634 passed, 0 failed, 40 skipped**. - `dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`, built with Apple/Android TFMs excluded because of a local workload mismatch. Result: **2179 passed, 2 failed, 8 skipped**. The 2 failures (`TwoWayDecimalBinding_*`) depend on the dev machine's locale (comma decimal separator) and pass with `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1`. - `dotnet format whitespace --verify-no-changes` on the changed files: clean. ### Issues Fixed Fixes #36156 <!-- Verify the target branch follows the release workflow in docs/ReleaseBranchWorkflow.md. Infrastructure and documentation changes should target the branch where they apply. --> --------- Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
… different C# (#40330) <!-- 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! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). **Base note:** this is a follow-up to #40233, which was merged into `candidate/11.0.1xx-sr2` and is not in `net11` (or `main`) yet. This change modifies code that only exists there, so the PR targets `candidate/11.0.1xx-sr2`. For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change Follow-up to #40233, closing the gap it documented: if a **throwaway compilation with different user C#** (speculative or design-time snapshot) evaluates the edited XAML before the real compilation does, the pending `UpdateComponent()` patch is lost. The generator couldn't tell this apart from a genuine C#-only edit, which had to emit an *empty* `UpdateComponent()` because the runtime classified a delta as a XAML change by the emptiness of that body. **Fix: move the classification to a companion signal type, as @noiseonwires proposed on #36937.** The `MetadataUpdateHandler` is in this repo, so no Roslyn or hot reload agent changes are needed. - **Generator (`UpdateComponentCodeWriter`)**: the `.uc.xsg.cs` file now also nests a private `__XamlHotReloadSignal` type in each XIHR root, with `Fingerprint() => "<sha256 of the patch body>"` (`""` when there's no patch). It's emitted on every generation, like `UpdateComponent()`, so there's no member churn. Its content only changes when the patch changes, so Roslyn lists it in a delta exactly when there's a new patch to apply. - **Generator (`XamlGenerator` / `XamlHotReloadState`)**: when the XAML is unchanged and a patch is pending, the patch is always re-derived from its baseline, whatever the C# sources are. The output becomes a function of the inputs, not of evaluation order or of which compilation ran first. The `UserSourcesFingerprint` gate from #40233 (and the extra compilation input to the pipeline) is removed. - **Runtime (`XamlIncrementalHotReloadHandler`)**: a root that has the companion type counts as a XAML change only if the delta lists the companion **and** `UpdateComponent()` isn't empty. This keeps structural changes, which reset the body to empty, out, as before. A companion listed without its root is mapped back to the root. Roots without a companion (older generated code) keep the existing empty-body check. `UpdateRequested.HandledTypes` and the `UpdateApplied`/`UpdateSkipped`/`UpdateFailed` contract are unchanged. With this, a C#-only edit re-emits the same patch. `UpdateComponent()` and the companion are byte-identical, so they aren't in the delta and the patch isn't re-applied. This matters because patches aren't always idempotent: reorders use `RemoveAt`/`Insert`. As a side benefit, a XAML edit whose delta was rejected (e.g. it was combined with a C# rude edit) still carries its patch on the next generation instead of an empty body. **Remaining limitation (not addressed here):** a throwaway run with *different XAML* (e.g. an intermediate keystroke) still advances the cached "previous" XAML. The next real patch is then diffed from that intermediate state rather than from what the app last applied. Fixing that would need knowledge of the last applied generation. **Tests** - `XamlIncrementalHotReloadPipelineTests` - `ThrowawayRunWithDifferentCSharpFirst_DoesNotConsumePendingPatch` is the gap from #40233. It fails without the fix. - `CSharpOnlyEditAfterXamlEdit_KeepsPatchAndSignalUnchanged` replaces `CSharpOnlyEditAfterXamlEdit_EmitsEmptyUpdateComponent`, whose expectation is intentionally changed. - `SignalFingerprint_ChangesWithThePatchOnly`. - `XamlIncrementalHotReloadE2ETests` (real `MetadataUpdater.ApplyUpdate`) - `CSharpOnlyEditAfterXamlEdit_DoesNotReapplyPatch` checks that a live label changed at runtime isn't overwritten by a C#-only delta. - `UpdateRequested_ReportsXamlChange_WhenSignalTypeIsUpdated` updates the existing classification test. - The test harness now lists the companion type among the delta's updated types only when its fingerprint changed, like Roslyn does. - `Controls.Core.UnitTests/XamlIncrementalHotReloadHandlerTests`: two handler tests cover a root with a companion type and a companion listed alone. **Validation** - `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj`: **855 passed, 0 failed, 0 skipped**. - With only the generator/state change reverted, 3 new tests fail, including the throwaway test. With only the handler change reverted, the 2 E2E runtime tests fail. - `dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`: **2250 passed, 2 failed, 8 skipped**. The 2 failures (`TwoWayDecimalBinding_*`) depend on the dev machine's locale and pass with `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1`. - `dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --filter "FullyQualifiedName~HotReload"`: **12 passed**. - `dotnet format whitespace --verify-no-changes` on the changed files: clean. ### Issues Fixed Fixes #36937 Follow-up to #40233. --------- Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
<!-- 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! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). This PR targets `candidate/11.0.1xx-sr2`, not `net11`. It's a follow-up to #40235, which was merged into `candidate/11.0.1xx-sr2` and isn't in `net11` (or `main`) yet. The change builds on the code #40235 added. For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change Follow-up to #40235 (fix for #36156). #40235 rolls back the XAML Incremental Hot Reload state (`XamlHotReloadState.Restore`) when a XAML edit can't build. It checks three things: the generator reported an error, the generated IC/UC has C# **syntax** errors, or generation threw. It deliberately skipped **semantic** errors. Members added by other generators (CommunityToolkit.Mvvm `[ObservableProperty]` / `[RelayCommand]`) aren't visible to the XAML generator, so a naive type check would roll back valid edits. As a result, an edit that only fails type checking, such as `{Count.Nope()}` (CS1061), still advanced the baseline. The next valid edit was then diffed against a generation the app never received, and the changes made together with the rude edit were lost. **Fix:** `HasSemanticErrors` type-checks the generated `InitializeComponent` and `UpdateComponent` trees against the generator's compilation (user code plus generated code-behind). It runs only when a XAML edit was diffed, i.e. when a rollback snapshot exists. An error counts only if: - it is located in the generated IC/UC code (errors in user code are ignored), and - `MayBeFixedByAnotherGenerator` returns false for it. That helper ignores errors that a declaration added by another generator could resolve: - unresolved names, types and namespaces (CS0103, CS0234, CS0246, CS0426); - failed member lookup (CS1061, CS0117, …) or overload resolution on a receiver whose type is a **`partial` type declared in source**, the only kind of type other generators can add members to. This also covers `?.` member bindings, implicit-`this` invocations, object creations, and errors reported on an argument. **Options considered:** - *Defer the baseline commit until a later signal confirms the compile.* Rejected: inside the generator there is no such signal. The next run's input compilation never contains the previous output, and nothing tells the generator whether the emit or EnC apply succeeded. - *Count all semantic errors.* Rejected: false rollbacks for MVVM Toolkit members. A false positive is worse than a miss, because the next patch re-adds children that are already live. - *Restrict to diagnostics attributable to XAML-generated code and filter out what another generator could fix.* Chosen. **Known remaining gap:** a lookup on a non-`partial` or metadata type (e.g. `int`) that only an extension method from *another generator* could satisfy still counts as an error. That's rare in XAML expressions. C# 14 extension members generated elsewhere fall in the same case. `XamlHotReloadState` is unchanged. The change is limited to `XamlGenerator.cs`, to keep conflicts with the #40233 follow-up low. **Tests** (`XamlIncrementalHotReloadRudeEditTests`): - `EditAfterRudeEdit_IsDiffedAgainstLastAppliedGeneration(Semantic)`: new case for a type-check-only rude edit, `{Count.Nope()}`. The theory parameter changed from `bool` to a `RudeEdit` enum. - `ElementAddedWithSemanticRudeEdit_IsAddedOnceTheEditIsFixed`: an element added together with a semantic rude edit is added once the edit is fixed. - `MembersGeneratedByAnotherGenerator_DoNotRollBack`: guard. The view model uses `[ObservableProperty]` and `[RelayCommand]`, and the XAML references `Count` (C# expression) and `{Binding SaveCommand}`. The previous edit must not be rolled back, so the added `Button` isn't added again. Without the fix, the 2 semantic cases fail. With `MayBeFixedByAnotherGenerator` disabled, the guard fails. **Validation:** - `dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj --filter FullyQualifiedName~XamlIncrementalHotReloadRudeEditTests`: **9 passed**. Before the fix: 2 failed (the semantic cases), 7 passed. With the filter disabled: 1 failed (the MVVM guard). - `dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj` (full suite): **772 passed, 0 failed, 53 skipped**. - `dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj` with `-p:IncludeAndroidTargetFrameworks=false -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -p:IncludeMacOSTargetFrameworks=false`. The mobile TFMs were excluded because of a local workload mismatch. Result: **2250 passed, 2 failed, 8 skipped**. The 2 failures (`TwoWayDecimalBinding_*`) are known and depend on the machine's locale. - `dotnet format whitespace --folder --include <changed files> --verify-no-changes`: clean. ### Issues Fixed Follow-up to #40235. Relates to #36156. <!-- Verify the target branch follows the release workflow in docs/ReleaseBranchWorkflow.md. Infrastructure and documentation changes should target the branch where they apply. --> --------- Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
…ns (#40378) <!-- 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! ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). > [!IMPORTANT] > **Base: `candidate/11.0.1xx-sr2` (decided).** This PR builds on #40233, #40235, #40329 and #40330, which exist only on `candidate/11.0.1xx-sr2` (not on `net11`, `main` or `inflight/11.0.1xx-sr3`). Against `net11` the diff would include about 527 unrelated files. As with #40329 and #40330, it targets `candidate/11.0.1xx-sr2` directly so it ships together with its prerequisites. ### Description of Change #40330 left one limitation. A throwaway generator run with different XAML, such as a design-time or speculative run whose output never reaches the app, advanced the cached previous XAML. The next real `UpdateComponent()` was then diffed from that intermediate generation instead of the generation the running app actually has. The result was missed edits: for example, an edit already present in the throwaway XAML was never applied. The generator cannot tell which of its runs reached the app, so this PR has `UpdateComponent()` decide at runtime: - **Generation key.** Each successful generation gets a key: a SHA-256 of the normalized XAML plus the node IDs (`NodeIdHelper.ComputeGenerationKey`). `XamlHotReloadState` keeps the current generation and the previously generated ones as baselines, up to `MaxBaselines = 4`. - **InitializeComponent** records `XamlComponentRegistry.Register(this, "__xihr_generation:<type>", key)`. - **UpdateComponent** reads the instance's recorded key: - A retained generation whose diff produces exactly the current node IDs gets its own branch: the patch diffed from that generation. - Anything else gets the default patch, diffed from the last generated XAML. This matches the previous behavior. - Every patched instance then records the new key, so running the patch again, or for a C#-only edit, changes nothing. - When there is nothing to patch, the output is unchanged: an empty UC, with no marker. Rude-edit rollback behavior is preserved, and the older applied generation now also gets its own branch. **Known edge, not a regression:** a retained generation whose diff would assign different IDs from the current ones (e.g. some reverts) is not given a branch. Instances at that generation fall back to the default patch, which is the old behavior. ### Issues Fixed Fixes #36937 (remaining limitation from #40330) ### Tests - `XamlIncrementalHotReloadE2ETests.ThrowawayRunWithDifferentXaml_PatchStartsFromTheAppliedGeneration`: real metadata update. Applied `Text="Hello"`, then a throwaway run with `Text="World" FontSize="30"`, then the real edit to `Text="World"`. The live label ends at `World` with its default `FontSize`, re-running UC is a no-op, and new instances are already current. A new harness hook, `GenerateWithThrowawayRuns`, runs and discards a forked driver run. - `XamlIncrementalHotReloadPipelineTests.ThrowawayRunWithDifferentXaml_PatchesFromEveryRetainedGeneration`: checks the branch structure and determinism (same snapshot and C#-only edits give an identical UC). - `XamlIncrementalHotReloadPipelineTests.RetainedGenerations_AreBounded` - Existing rude-edit assertions now target the default patch (`UpdateComponentText.DefaultPatch`), because the UC legitimately contains a branch for the older applied generation. ### Validation - `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj`: **passed**, 899/899. - `dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --filter "FullyQualifiedName~HotReload"`: **passed**, 12/12. - `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1 dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`: 2274 passed, 12 failed. All 12 failures are `CultureNotFoundException` from culture-specific tests under invariant-globalization mode; none involve hot reload. - `dotnet format whitespace Microsoft.Maui.sln --verify-no-changes --include <changed files>`: **passed**. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…40413) (#40417) <!-- 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! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). **Base is `candidate/11.0.1xx-sr2`, not `net11`.** The PR is test-only and covers behavior that exists only on the candidate branch, from the #36937 fix chain #40233, #40235, #40329, #40330, and #40378. Against `net11` the test fails, because that fix has not flowed there yet. This follows the precedent of #40329, #40330, and #40378, which targeted this branch for the same reason. Maintainers: retarget if you prefer a different lane. For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change #40413 reports that in VS on Windows (.NET 11, SourceGen inflator, XAML Incremental Hot Reload on by default in Debug), editing a Label's `Text` in the default template's `MainPage.xaml` is not applied. **Root cause.** This is #36937. Roslyn/VS evaluate the same edited generator-driver snapshot more than once, for example forked or speculative runs, or a throwaway compilation before the applied one. On `net11`, the first evaluation advances the cached previous XAML. The evaluation that is actually applied then sees no diff and emits an empty `UpdateComponent`, and the runtime silently skips it. The bug became visible in .NET 11 because XIHR is now the default; 10.0.120 used legacy XAML Hot Reload. I reproduced this with the issue's own template `MainPage.xaml` through the source generator: | Sequence | `net11` (a25e629) | `candidate/11.0.1xx-sr2` (cec6650) | | --- | --- | --- | | Edit evaluated once | patch | patch | | Same edited snapshot evaluated twice: 2nd run | **empty UC** | patch | | Throwaway compilation first, then real run: real run | **empty UC** | patch | On the candidate branch the existing fixes already handle this. This PR adds `DefaultTemplateMainPageTextEdit_SurvivesRepeatedAndThrowawayEvaluations`, a theory with repeated and throwaway-first cases. It uses the template page shape (`StaticResource` styles from a sibling `Styles.xaml`, `x:Name`, a `Clicked` handler in code-behind) to lock in the reported scenario. There are no product changes. **Android .NET 10 (validation comment).** This is a separate scenario. XIHR was not the default in .NET 10, so that report involves the legacy XAML Hot Reload path and is not caused by this regression. It is not addressed here. **Validation** - `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj --filter "FullyQualifiedName~XamlIncrementalHotReloadPipelineTests|FullyQualifiedName~CodeBehindFieldStabilityTests"`: **passed**, 93/93, on this branch. - `net11`: the same two sequences, run through an equivalent temporary probe with the template XAML, produce an empty UC, as shown in the table. I did not port the committed test itself to `net11`: its helpers exist only on candidate, and reverting the fix commits in place conflicts. - Not verified in Visual Studio on Windows or on device; I worked on a macOS host. ### Issues Fixed Fixes #40413 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…valuation (#40233) <!-- 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! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change XAML Incremental Hot Reload (XIHR) keeps per-driver state in `XamlHotReloadState` and diffs the previous generation against the current one to emit `UpdateComponent()`. Roslyn can evaluate the **same driver snapshot more than once**: driver forks, speculative or design-time requests, and cancelled or discarded runs. The first evaluation advanced the cached "previous" XAML. Every later evaluation of the same inputs then saw `previous == current` and emitted an **empty** `UpdateComponent()`, which silently dropped the edit. @noiseonwires reproduced this deterministically on the issue (`edited.RunGenerators(c)` twice gives a patch, then an empty method) and matched it to captured VS deltas. **Fix (option 1 of the issue, extended):** - When a generation produces a patch, the cache entry also stores the **exact generation it was diffed from** (`PatchBaseline`). It also stores a `UserSourcesFingerprint` of the user C# sources it was produced with: path plus `SourceText.GetContentHash()` per tree, taken from the original compilation without the generated code-behind trees, and memoized per `Compilation`. - A later generation with the **same XAML and the same user sources** re-derives the identical patch from that baseline. - A generation with the same XAML but **different user sources** (a C#-only edit) still emits an empty `UpdateComponent()`. This preserves the runtime "non-empty body ⟺ XAML change" classification. It matters because patches aren't always idempotent (reorders use `RemoveAt`/`Insert`), so a stale patch must not be re-invoked on later C#-only edits of the same type. - The baseline is never dropped by such a run; only the next XAML edit replaces it. The output is therefore a function of the inputs, not of evaluation order. A side effect is that a pending patch also survives regeneration caused by edits to *other* XAML files. - Fingerprinting only runs for XIHR-enabled files that have a pending patch, so non-hot-reload and Release builds are unaffected. **Known limitation (needs the cross-team design discussed on the issue):** the generator can't tell "a discarded run with *different* C# evaluated the new XAML first, then the real run" apart from "a XAML edit, then a real C#-only edit". In both cases it sees a patch produced under fingerprint F1 followed by the same XAML under F2. The second case must stay empty, so the first case still loses the patch. Exactly reverting C# to the snapshot of the XAML edit would also re-emit the patch. Fully removing history-dependence needs the classification to move off the empty-`UpdateComponent()` signal, for example the per-document companion signal type @noiseonwires proposed. **Tests:** 7 new cases in `XamlIncrementalHotReloadPipelineTests`: forked runs of the same edited driver, the implicit-style `ResourceDictionary` repro shape from the issue, a discarded throwaway run, an interleaved run with different C#, an edit to another XAML file, a revert after forked runs, and a C#-only edit after a XAML edit staying empty. Five of them fail without the fix. The revert and C#-only cases guard existing behavior. **Validation:** - `dotnet test` SourceGen.UnitTests (run from a copy of the output in a path without `~`): **635 passed, 0 failed, 40 skipped**. - With the fix reverted: the 5 new regression tests fail. - `dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`: **2179 passed, 2 failed, 8 skipped**. The 2 failures (`TwoWayDecimalBinding_*`) are locale-dependent on the dev machine (comma decimal separator) and pass with `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1`. - `dotnet format whitespace --verify-no-changes` on the changed files: clean. ### Issues Fixed Fixes #36937 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
<!-- 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! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change XAML Incremental Hot Reload (XIHR) keeps per-file state in `XamlHotReloadState` (last XAML, parsed tree, node IDs) and emits `UpdateComponent()` as a diff from the previous generation to the current one. A **rude edit** is a XAML edit whose generated code doesn't compile, for example a malformed XAML C# expression, or an error reported by the generator such as an unresolved member. The build fails, so that edit never reaches the running app. The state had already moved to the broken generation, though. The next, fixed edit was then diffed against the broken generation, not against what the app is running. Changes made together with the rude edit were never applied: property sets, and elements added in the same edit. They stayed lost until a full restart. **Fix:** - Before diffing a XAML edit, the generator captures a copy of the file's state entry (`XamlHotReloadState.Capture`). - After generating `InitializeComponent` and `UpdateComponent`, it restores that entry (`XamlHotReloadState.Restore`) when the generation can't build: - the generator reported an error while generating `InitializeComponent`. A new optional `diagnosticObserver` on `GenerateInitializeComponent` reports these. User severity overrides are honored (`NoWarn`, `WarningsNotAsErrors`, `.editorconfig`/`.globalconfig`), so a downgraded MAUIX error doesn't count; - or the generated IC/UC code has C# **syntax** errors; - or generation throws. - The next edit is then diffed against the last generation that could have been applied. Its patch also carries the changes made together with the rude edit. Re-evaluating the rude edit is deterministic, and reverting to the applied XAML is "no change". **Deliberately not checked: semantic C# errors** in the generated code, such as `{Count.Nope()}` (CS1061). Generated code can legitimately reference members that other generators add later, such as CommunityToolkit.Mvvm `[ObservableProperty]` / `[RelayCommand]`, which `ITypeSymbolExtensions` already infers. A false positive is worse than a miss: it pins the state to a generation the app has already moved past, and the next patch would re-add children, for example. Those edits keep today's behavior. A C#-only compile failure that happens at the same time as a XAML edit is also out of scope. **Interaction with #40233 (fix for #36937):** The two are independent, so this PR is not stacked on #40233. #40233 adds `PatchBaseline`/`PatchSources` to `CacheEntry` and replays the pending patch when the same inputs are evaluated again. This PR snapshots and restores the whole `CacheEntry` with `MemberwiseClone`, so after a rebase, rolling back a rude edit also restores those fields. The restored state is exactly what the applied generation left, so the output for identical inputs stays identical. Expected conflicts are textual only, in `XamlGenerator.cs` (adjacent lines in the IC output callback) and `XamlHotReloadState.cs`. The new tests are in their own file to avoid conflicts in `XamlIncrementalHotReloadPipelineTests.cs`. **Tests:** new `XamlIncrementalHotReloadRudeEditTests` (6 cases): - an edit after a rude edit carries the changes made with the rude edit, for both a C# syntax error and a generator-reported error (MAUIX2009); - an element added with a rude edit is added once the edit is fixed; - reverting after a rude edit emits the same output as the applied state; - repeated evaluation of a rude edit is deterministic; - an error the user downgraded doesn't roll back (no duplicate element). The first 5 cases fail without the fix. The downgrade case fails if the severity lookup is removed. **Validation:** - `dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj --filter XamlIncrementalHotReloadRudeEditTests`: 6 passed; 5 failed before the fix. - SourceGen.UnitTests, full suite. It was run from a copy of the output in a path without `~`, because the `XTypeMultiFileHotReloadTests` fail when the path contains `~`. Result: **634 passed, 0 failed, 40 skipped**. - `dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`, built with Apple/Android TFMs excluded because of a local workload mismatch. Result: **2179 passed, 2 failed, 8 skipped**. The 2 failures (`TwoWayDecimalBinding_*`) depend on the dev machine's locale (comma decimal separator) and pass with `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1`. - `dotnet format whitespace --verify-no-changes` on the changed files: clean. ### Issues Fixed Fixes #36156 <!-- Verify the target branch follows the release workflow in docs/ReleaseBranchWorkflow.md. Infrastructure and documentation changes should target the branch where they apply. --> --------- Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
… different C# (#40330) <!-- 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! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). **Base note:** this is a follow-up to #40233, which was merged into `candidate/11.0.1xx-sr2` and is not in `net11` (or `main`) yet. This change modifies code that only exists there, so the PR targets `candidate/11.0.1xx-sr2`. For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change Follow-up to #40233, closing the gap it documented: if a **throwaway compilation with different user C#** (speculative or design-time snapshot) evaluates the edited XAML before the real compilation does, the pending `UpdateComponent()` patch is lost. The generator couldn't tell this apart from a genuine C#-only edit, which had to emit an *empty* `UpdateComponent()` because the runtime classified a delta as a XAML change by the emptiness of that body. **Fix: move the classification to a companion signal type, as @noiseonwires proposed on #36937.** The `MetadataUpdateHandler` is in this repo, so no Roslyn or hot reload agent changes are needed. - **Generator (`UpdateComponentCodeWriter`)**: the `.uc.xsg.cs` file now also nests a private `__XamlHotReloadSignal` type in each XIHR root, with `Fingerprint() => "<sha256 of the patch body>"` (`""` when there's no patch). It's emitted on every generation, like `UpdateComponent()`, so there's no member churn. Its content only changes when the patch changes, so Roslyn lists it in a delta exactly when there's a new patch to apply. - **Generator (`XamlGenerator` / `XamlHotReloadState`)**: when the XAML is unchanged and a patch is pending, the patch is always re-derived from its baseline, whatever the C# sources are. The output becomes a function of the inputs, not of evaluation order or of which compilation ran first. The `UserSourcesFingerprint` gate from #40233 (and the extra compilation input to the pipeline) is removed. - **Runtime (`XamlIncrementalHotReloadHandler`)**: a root that has the companion type counts as a XAML change only if the delta lists the companion **and** `UpdateComponent()` isn't empty. This keeps structural changes, which reset the body to empty, out, as before. A companion listed without its root is mapped back to the root. Roots without a companion (older generated code) keep the existing empty-body check. `UpdateRequested.HandledTypes` and the `UpdateApplied`/`UpdateSkipped`/`UpdateFailed` contract are unchanged. With this, a C#-only edit re-emits the same patch. `UpdateComponent()` and the companion are byte-identical, so they aren't in the delta and the patch isn't re-applied. This matters because patches aren't always idempotent: reorders use `RemoveAt`/`Insert`. As a side benefit, a XAML edit whose delta was rejected (e.g. it was combined with a C# rude edit) still carries its patch on the next generation instead of an empty body. **Remaining limitation (not addressed here):** a throwaway run with *different XAML* (e.g. an intermediate keystroke) still advances the cached "previous" XAML. The next real patch is then diffed from that intermediate state rather than from what the app last applied. Fixing that would need knowledge of the last applied generation. **Tests** - `XamlIncrementalHotReloadPipelineTests` - `ThrowawayRunWithDifferentCSharpFirst_DoesNotConsumePendingPatch` is the gap from #40233. It fails without the fix. - `CSharpOnlyEditAfterXamlEdit_KeepsPatchAndSignalUnchanged` replaces `CSharpOnlyEditAfterXamlEdit_EmitsEmptyUpdateComponent`, whose expectation is intentionally changed. - `SignalFingerprint_ChangesWithThePatchOnly`. - `XamlIncrementalHotReloadE2ETests` (real `MetadataUpdater.ApplyUpdate`) - `CSharpOnlyEditAfterXamlEdit_DoesNotReapplyPatch` checks that a live label changed at runtime isn't overwritten by a C#-only delta. - `UpdateRequested_ReportsXamlChange_WhenSignalTypeIsUpdated` updates the existing classification test. - The test harness now lists the companion type among the delta's updated types only when its fingerprint changed, like Roslyn does. - `Controls.Core.UnitTests/XamlIncrementalHotReloadHandlerTests`: two handler tests cover a root with a companion type and a companion listed alone. **Validation** - `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj`: **855 passed, 0 failed, 0 skipped**. - With only the generator/state change reverted, 3 new tests fail, including the throwaway test. With only the handler change reverted, the 2 E2E runtime tests fail. - `dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`: **2250 passed, 2 failed, 8 skipped**. The 2 failures (`TwoWayDecimalBinding_*`) depend on the dev machine's locale and pass with `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1`. - `dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --filter "FullyQualifiedName~HotReload"`: **12 passed**. - `dotnet format whitespace --verify-no-changes` on the changed files: clean. ### Issues Fixed Fixes #36937 Follow-up to #40233. --------- Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
<!-- 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! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). This PR targets `candidate/11.0.1xx-sr2`, not `net11`. It's a follow-up to #40235, which was merged into `candidate/11.0.1xx-sr2` and isn't in `net11` (or `main`) yet. The change builds on the code #40235 added. For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change Follow-up to #40235 (fix for #36156). #40235 rolls back the XAML Incremental Hot Reload state (`XamlHotReloadState.Restore`) when a XAML edit can't build. It checks three things: the generator reported an error, the generated IC/UC has C# **syntax** errors, or generation threw. It deliberately skipped **semantic** errors. Members added by other generators (CommunityToolkit.Mvvm `[ObservableProperty]` / `[RelayCommand]`) aren't visible to the XAML generator, so a naive type check would roll back valid edits. As a result, an edit that only fails type checking, such as `{Count.Nope()}` (CS1061), still advanced the baseline. The next valid edit was then diffed against a generation the app never received, and the changes made together with the rude edit were lost. **Fix:** `HasSemanticErrors` type-checks the generated `InitializeComponent` and `UpdateComponent` trees against the generator's compilation (user code plus generated code-behind). It runs only when a XAML edit was diffed, i.e. when a rollback snapshot exists. An error counts only if: - it is located in the generated IC/UC code (errors in user code are ignored), and - `MayBeFixedByAnotherGenerator` returns false for it. That helper ignores errors that a declaration added by another generator could resolve: - unresolved names, types and namespaces (CS0103, CS0234, CS0246, CS0426); - failed member lookup (CS1061, CS0117, …) or overload resolution on a receiver whose type is a **`partial` type declared in source**, the only kind of type other generators can add members to. This also covers `?.` member bindings, implicit-`this` invocations, object creations, and errors reported on an argument. **Options considered:** - *Defer the baseline commit until a later signal confirms the compile.* Rejected: inside the generator there is no such signal. The next run's input compilation never contains the previous output, and nothing tells the generator whether the emit or EnC apply succeeded. - *Count all semantic errors.* Rejected: false rollbacks for MVVM Toolkit members. A false positive is worse than a miss, because the next patch re-adds children that are already live. - *Restrict to diagnostics attributable to XAML-generated code and filter out what another generator could fix.* Chosen. **Known remaining gap:** a lookup on a non-`partial` or metadata type (e.g. `int`) that only an extension method from *another generator* could satisfy still counts as an error. That's rare in XAML expressions. C# 14 extension members generated elsewhere fall in the same case. `XamlHotReloadState` is unchanged. The change is limited to `XamlGenerator.cs`, to keep conflicts with the #40233 follow-up low. **Tests** (`XamlIncrementalHotReloadRudeEditTests`): - `EditAfterRudeEdit_IsDiffedAgainstLastAppliedGeneration(Semantic)`: new case for a type-check-only rude edit, `{Count.Nope()}`. The theory parameter changed from `bool` to a `RudeEdit` enum. - `ElementAddedWithSemanticRudeEdit_IsAddedOnceTheEditIsFixed`: an element added together with a semantic rude edit is added once the edit is fixed. - `MembersGeneratedByAnotherGenerator_DoNotRollBack`: guard. The view model uses `[ObservableProperty]` and `[RelayCommand]`, and the XAML references `Count` (C# expression) and `{Binding SaveCommand}`. The previous edit must not be rolled back, so the added `Button` isn't added again. Without the fix, the 2 semantic cases fail. With `MayBeFixedByAnotherGenerator` disabled, the guard fails. **Validation:** - `dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj --filter FullyQualifiedName~XamlIncrementalHotReloadRudeEditTests`: **9 passed**. Before the fix: 2 failed (the semantic cases), 7 passed. With the filter disabled: 1 failed (the MVVM guard). - `dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj` (full suite): **772 passed, 0 failed, 53 skipped**. - `dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj` with `-p:IncludeAndroidTargetFrameworks=false -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -p:IncludeMacOSTargetFrameworks=false`. The mobile TFMs were excluded because of a local workload mismatch. Result: **2250 passed, 2 failed, 8 skipped**. The 2 failures (`TwoWayDecimalBinding_*`) are known and depend on the machine's locale. - `dotnet format whitespace --folder --include <changed files> --verify-no-changes`: clean. ### Issues Fixed Follow-up to #40235. Relates to #36156. <!-- Verify the target branch follows the release workflow in docs/ReleaseBranchWorkflow.md. Infrastructure and documentation changes should target the branch where they apply. --> --------- Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
…ns (#40378) <!-- 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! ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). > [!IMPORTANT] > **Base: `candidate/11.0.1xx-sr2` (decided).** This PR builds on #40233, #40235, #40329 and #40330, which exist only on `candidate/11.0.1xx-sr2` (not on `net11`, `main` or `inflight/11.0.1xx-sr3`). Against `net11` the diff would include about 527 unrelated files. As with #40329 and #40330, it targets `candidate/11.0.1xx-sr2` directly so it ships together with its prerequisites. ### Description of Change #40330 left one limitation. A throwaway generator run with different XAML, such as a design-time or speculative run whose output never reaches the app, advanced the cached previous XAML. The next real `UpdateComponent()` was then diffed from that intermediate generation instead of the generation the running app actually has. The result was missed edits: for example, an edit already present in the throwaway XAML was never applied. The generator cannot tell which of its runs reached the app, so this PR has `UpdateComponent()` decide at runtime: - **Generation key.** Each successful generation gets a key: a SHA-256 of the normalized XAML plus the node IDs (`NodeIdHelper.ComputeGenerationKey`). `XamlHotReloadState` keeps the current generation and the previously generated ones as baselines, up to `MaxBaselines = 4`. - **InitializeComponent** records `XamlComponentRegistry.Register(this, "__xihr_generation:<type>", key)`. - **UpdateComponent** reads the instance's recorded key: - A retained generation whose diff produces exactly the current node IDs gets its own branch: the patch diffed from that generation. - Anything else gets the default patch, diffed from the last generated XAML. This matches the previous behavior. - Every patched instance then records the new key, so running the patch again, or for a C#-only edit, changes nothing. - When there is nothing to patch, the output is unchanged: an empty UC, with no marker. Rude-edit rollback behavior is preserved, and the older applied generation now also gets its own branch. **Known edge, not a regression:** a retained generation whose diff would assign different IDs from the current ones (e.g. some reverts) is not given a branch. Instances at that generation fall back to the default patch, which is the old behavior. ### Issues Fixed Fixes #36937 (remaining limitation from #40330) ### Tests - `XamlIncrementalHotReloadE2ETests.ThrowawayRunWithDifferentXaml_PatchStartsFromTheAppliedGeneration`: real metadata update. Applied `Text="Hello"`, then a throwaway run with `Text="World" FontSize="30"`, then the real edit to `Text="World"`. The live label ends at `World` with its default `FontSize`, re-running UC is a no-op, and new instances are already current. A new harness hook, `GenerateWithThrowawayRuns`, runs and discards a forked driver run. - `XamlIncrementalHotReloadPipelineTests.ThrowawayRunWithDifferentXaml_PatchesFromEveryRetainedGeneration`: checks the branch structure and determinism (same snapshot and C#-only edits give an identical UC). - `XamlIncrementalHotReloadPipelineTests.RetainedGenerations_AreBounded` - Existing rude-edit assertions now target the default patch (`UpdateComponentText.DefaultPatch`), because the UC legitimately contains a branch for the older applied generation. ### Validation - `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj`: **passed**, 899/899. - `dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --filter "FullyQualifiedName~HotReload"`: **passed**, 12/12. - `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1 dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`: 2274 passed, 12 failed. All 12 failures are `CultureNotFoundException` from culture-specific tests under invariant-globalization mode; none involve hot reload. - `dotnet format whitespace Microsoft.Maui.sln --verify-no-changes --include <changed files>`: **passed**. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…40413) (#40417) <!-- 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! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). **Base is `candidate/11.0.1xx-sr2`, not `net11`.** The PR is test-only and covers behavior that exists only on the candidate branch, from the #36937 fix chain #40233, #40235, #40329, #40330, and #40378. Against `net11` the test fails, because that fix has not flowed there yet. This follows the precedent of #40329, #40330, and #40378, which targeted this branch for the same reason. Maintainers: retarget if you prefer a different lane. For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change #40413 reports that in VS on Windows (.NET 11, SourceGen inflator, XAML Incremental Hot Reload on by default in Debug), editing a Label's `Text` in the default template's `MainPage.xaml` is not applied. **Root cause.** This is #36937. Roslyn/VS evaluate the same edited generator-driver snapshot more than once, for example forked or speculative runs, or a throwaway compilation before the applied one. On `net11`, the first evaluation advances the cached previous XAML. The evaluation that is actually applied then sees no diff and emits an empty `UpdateComponent`, and the runtime silently skips it. The bug became visible in .NET 11 because XIHR is now the default; 10.0.120 used legacy XAML Hot Reload. I reproduced this with the issue's own template `MainPage.xaml` through the source generator: | Sequence | `net11` (a25e629) | `candidate/11.0.1xx-sr2` (cec6650) | | --- | --- | --- | | Edit evaluated once | patch | patch | | Same edited snapshot evaluated twice: 2nd run | **empty UC** | patch | | Throwaway compilation first, then real run: real run | **empty UC** | patch | On the candidate branch the existing fixes already handle this. This PR adds `DefaultTemplateMainPageTextEdit_SurvivesRepeatedAndThrowawayEvaluations`, a theory with repeated and throwaway-first cases. It uses the template page shape (`StaticResource` styles from a sibling `Styles.xaml`, `x:Name`, a `Clicked` handler in code-behind) to lock in the reported scenario. There are no product changes. **Android .NET 10 (validation comment).** This is a separate scenario. XIHR was not the default in .NET 10, so that report involves the legacy XAML Hot Reload path and is not caused by this regression. It is not addressed here. **Validation** - `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj --filter "FullyQualifiedName~XamlIncrementalHotReloadPipelineTests|FullyQualifiedName~CodeBehindFieldStabilityTests"`: **passed**, 93/93, on this branch. - `net11`: the same two sequences, run through an equivalent temporary probe with the template XAML, produce an empty UC, as shown in the table. I did not port the committed test itself to `net11`: its helpers exist only on candidate, and reverting the fix commits in place conflicts. - Not verified in Visual Studio on Windows or on device; I worked on a macOS host. ### Issues Fixed Fixes #40413 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…valuation (dotnet#40233) <!-- 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! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change XAML Incremental Hot Reload (XIHR) keeps per-driver state in `XamlHotReloadState` and diffs the previous generation against the current one to emit `UpdateComponent()`. Roslyn can evaluate the **same driver snapshot more than once**: driver forks, speculative or design-time requests, and cancelled or discarded runs. The first evaluation advanced the cached "previous" XAML. Every later evaluation of the same inputs then saw `previous == current` and emitted an **empty** `UpdateComponent()`, which silently dropped the edit. @noiseonwires reproduced this deterministically on the issue (`edited.RunGenerators(c)` twice gives a patch, then an empty method) and matched it to captured VS deltas. **Fix (option 1 of the issue, extended):** - When a generation produces a patch, the cache entry also stores the **exact generation it was diffed from** (`PatchBaseline`). It also stores a `UserSourcesFingerprint` of the user C# sources it was produced with: path plus `SourceText.GetContentHash()` per tree, taken from the original compilation without the generated code-behind trees, and memoized per `Compilation`. - A later generation with the **same XAML and the same user sources** re-derives the identical patch from that baseline. - A generation with the same XAML but **different user sources** (a C#-only edit) still emits an empty `UpdateComponent()`. This preserves the runtime "non-empty body ⟺ XAML change" classification. It matters because patches aren't always idempotent (reorders use `RemoveAt`/`Insert`), so a stale patch must not be re-invoked on later C#-only edits of the same type. - The baseline is never dropped by such a run; only the next XAML edit replaces it. The output is therefore a function of the inputs, not of evaluation order. A side effect is that a pending patch also survives regeneration caused by edits to *other* XAML files. - Fingerprinting only runs for XIHR-enabled files that have a pending patch, so non-hot-reload and Release builds are unaffected. **Known limitation (needs the cross-team design discussed on the issue):** the generator can't tell "a discarded run with *different* C# evaluated the new XAML first, then the real run" apart from "a XAML edit, then a real C#-only edit". In both cases it sees a patch produced under fingerprint F1 followed by the same XAML under F2. The second case must stay empty, so the first case still loses the patch. Exactly reverting C# to the snapshot of the XAML edit would also re-emit the patch. Fully removing history-dependence needs the classification to move off the empty-`UpdateComponent()` signal, for example the per-document companion signal type @noiseonwires proposed. **Tests:** 7 new cases in `XamlIncrementalHotReloadPipelineTests`: forked runs of the same edited driver, the implicit-style `ResourceDictionary` repro shape from the issue, a discarded throwaway run, an interleaved run with different C#, an edit to another XAML file, a revert after forked runs, and a C#-only edit after a XAML edit staying empty. Five of them fail without the fix. The revert and C#-only cases guard existing behavior. **Validation:** - `dotnet test` SourceGen.UnitTests (run from a copy of the output in a path without `~`): **635 passed, 0 failed, 40 skipped**. - With the fix reverted: the 5 new regression tests fail. - `dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`: **2179 passed, 2 failed, 8 skipped**. The 2 failures (`TwoWayDecimalBinding_*`) are locale-dependent on the dev machine (comma decimal separator) and pass with `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1`. - `dotnet format whitespace --verify-no-changes` on the changed files: clean. ### Issues Fixed Fixes dotnet#36937 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
<!-- 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! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change XAML Incremental Hot Reload (XIHR) keeps per-file state in `XamlHotReloadState` (last XAML, parsed tree, node IDs) and emits `UpdateComponent()` as a diff from the previous generation to the current one. A **rude edit** is a XAML edit whose generated code doesn't compile, for example a malformed XAML C# expression, or an error reported by the generator such as an unresolved member. The build fails, so that edit never reaches the running app. The state had already moved to the broken generation, though. The next, fixed edit was then diffed against the broken generation, not against what the app is running. Changes made together with the rude edit were never applied: property sets, and elements added in the same edit. They stayed lost until a full restart. **Fix:** - Before diffing a XAML edit, the generator captures a copy of the file's state entry (`XamlHotReloadState.Capture`). - After generating `InitializeComponent` and `UpdateComponent`, it restores that entry (`XamlHotReloadState.Restore`) when the generation can't build: - the generator reported an error while generating `InitializeComponent`. A new optional `diagnosticObserver` on `GenerateInitializeComponent` reports these. User severity overrides are honored (`NoWarn`, `WarningsNotAsErrors`, `.editorconfig`/`.globalconfig`), so a downgraded MAUIX error doesn't count; - or the generated IC/UC code has C# **syntax** errors; - or generation throws. - The next edit is then diffed against the last generation that could have been applied. Its patch also carries the changes made together with the rude edit. Re-evaluating the rude edit is deterministic, and reverting to the applied XAML is "no change". **Deliberately not checked: semantic C# errors** in the generated code, such as `{Count.Nope()}` (CS1061). Generated code can legitimately reference members that other generators add later, such as CommunityToolkit.Mvvm `[ObservableProperty]` / `[RelayCommand]`, which `ITypeSymbolExtensions` already infers. A false positive is worse than a miss: it pins the state to a generation the app has already moved past, and the next patch would re-add children, for example. Those edits keep today's behavior. A C#-only compile failure that happens at the same time as a XAML edit is also out of scope. **Interaction with dotnet#40233 (fix for dotnet#36937):** The two are independent, so this PR is not stacked on dotnet#40233. dotnet#40233 adds `PatchBaseline`/`PatchSources` to `CacheEntry` and replays the pending patch when the same inputs are evaluated again. This PR snapshots and restores the whole `CacheEntry` with `MemberwiseClone`, so after a rebase, rolling back a rude edit also restores those fields. The restored state is exactly what the applied generation left, so the output for identical inputs stays identical. Expected conflicts are textual only, in `XamlGenerator.cs` (adjacent lines in the IC output callback) and `XamlHotReloadState.cs`. The new tests are in their own file to avoid conflicts in `XamlIncrementalHotReloadPipelineTests.cs`. **Tests:** new `XamlIncrementalHotReloadRudeEditTests` (6 cases): - an edit after a rude edit carries the changes made with the rude edit, for both a C# syntax error and a generator-reported error (MAUIX2009); - an element added with a rude edit is added once the edit is fixed; - reverting after a rude edit emits the same output as the applied state; - repeated evaluation of a rude edit is deterministic; - an error the user downgraded doesn't roll back (no duplicate element). The first 5 cases fail without the fix. The downgrade case fails if the severity lookup is removed. **Validation:** - `dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj --filter XamlIncrementalHotReloadRudeEditTests`: 6 passed; 5 failed before the fix. - SourceGen.UnitTests, full suite. It was run from a copy of the output in a path without `~`, because the `XTypeMultiFileHotReloadTests` fail when the path contains `~`. Result: **634 passed, 0 failed, 40 skipped**. - `dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`, built with Apple/Android TFMs excluded because of a local workload mismatch. Result: **2179 passed, 2 failed, 8 skipped**. The 2 failures (`TwoWayDecimalBinding_*`) depend on the dev machine's locale (comma decimal separator) and pass with `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1`. - `dotnet format whitespace --verify-no-changes` on the changed files: clean. ### Issues Fixed Fixes dotnet#36156 <!-- Verify the target branch follows the release workflow in docs/ReleaseBranchWorkflow.md. Infrastructure and documentation changes should target the branch where they apply. --> --------- Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
… different C# (dotnet#40330) <!-- 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! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). **Base note:** this is a follow-up to dotnet#40233, which was merged into `candidate/11.0.1xx-sr2` and is not in `net11` (or `main`) yet. This change modifies code that only exists there, so the PR targets `candidate/11.0.1xx-sr2`. For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change Follow-up to dotnet#40233, closing the gap it documented: if a **throwaway compilation with different user C#** (speculative or design-time snapshot) evaluates the edited XAML before the real compilation does, the pending `UpdateComponent()` patch is lost. The generator couldn't tell this apart from a genuine C#-only edit, which had to emit an *empty* `UpdateComponent()` because the runtime classified a delta as a XAML change by the emptiness of that body. **Fix: move the classification to a companion signal type, as @noiseonwires proposed on dotnet#36937.** The `MetadataUpdateHandler` is in this repo, so no Roslyn or hot reload agent changes are needed. - **Generator (`UpdateComponentCodeWriter`)**: the `.uc.xsg.cs` file now also nests a private `__XamlHotReloadSignal` type in each XIHR root, with `Fingerprint() => "<sha256 of the patch body>"` (`""` when there's no patch). It's emitted on every generation, like `UpdateComponent()`, so there's no member churn. Its content only changes when the patch changes, so Roslyn lists it in a delta exactly when there's a new patch to apply. - **Generator (`XamlGenerator` / `XamlHotReloadState`)**: when the XAML is unchanged and a patch is pending, the patch is always re-derived from its baseline, whatever the C# sources are. The output becomes a function of the inputs, not of evaluation order or of which compilation ran first. The `UserSourcesFingerprint` gate from dotnet#40233 (and the extra compilation input to the pipeline) is removed. - **Runtime (`XamlIncrementalHotReloadHandler`)**: a root that has the companion type counts as a XAML change only if the delta lists the companion **and** `UpdateComponent()` isn't empty. This keeps structural changes, which reset the body to empty, out, as before. A companion listed without its root is mapped back to the root. Roots without a companion (older generated code) keep the existing empty-body check. `UpdateRequested.HandledTypes` and the `UpdateApplied`/`UpdateSkipped`/`UpdateFailed` contract are unchanged. With this, a C#-only edit re-emits the same patch. `UpdateComponent()` and the companion are byte-identical, so they aren't in the delta and the patch isn't re-applied. This matters because patches aren't always idempotent: reorders use `RemoveAt`/`Insert`. As a side benefit, a XAML edit whose delta was rejected (e.g. it was combined with a C# rude edit) still carries its patch on the next generation instead of an empty body. **Remaining limitation (not addressed here):** a throwaway run with *different XAML* (e.g. an intermediate keystroke) still advances the cached "previous" XAML. The next real patch is then diffed from that intermediate state rather than from what the app last applied. Fixing that would need knowledge of the last applied generation. **Tests** - `XamlIncrementalHotReloadPipelineTests` - `ThrowawayRunWithDifferentCSharpFirst_DoesNotConsumePendingPatch` is the gap from dotnet#40233. It fails without the fix. - `CSharpOnlyEditAfterXamlEdit_KeepsPatchAndSignalUnchanged` replaces `CSharpOnlyEditAfterXamlEdit_EmitsEmptyUpdateComponent`, whose expectation is intentionally changed. - `SignalFingerprint_ChangesWithThePatchOnly`. - `XamlIncrementalHotReloadE2ETests` (real `MetadataUpdater.ApplyUpdate`) - `CSharpOnlyEditAfterXamlEdit_DoesNotReapplyPatch` checks that a live label changed at runtime isn't overwritten by a C#-only delta. - `UpdateRequested_ReportsXamlChange_WhenSignalTypeIsUpdated` updates the existing classification test. - The test harness now lists the companion type among the delta's updated types only when its fingerprint changed, like Roslyn does. - `Controls.Core.UnitTests/XamlIncrementalHotReloadHandlerTests`: two handler tests cover a root with a companion type and a companion listed alone. **Validation** - `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj`: **855 passed, 0 failed, 0 skipped**. - With only the generator/state change reverted, 3 new tests fail, including the throwaway test. With only the handler change reverted, the 2 E2E runtime tests fail. - `dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`: **2250 passed, 2 failed, 8 skipped**. The 2 failures (`TwoWayDecimalBinding_*`) depend on the dev machine's locale and pass with `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1`. - `dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --filter "FullyQualifiedName~HotReload"`: **12 passed**. - `dotnet format whitespace --verify-no-changes` on the changed files: clean. ### Issues Fixed Fixes dotnet#36937 Follow-up to dotnet#40233. --------- Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
…#40329) <!-- 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! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). This PR targets `candidate/11.0.1xx-sr2`, not `net11`. It's a follow-up to dotnet#40235, which was merged into `candidate/11.0.1xx-sr2` and isn't in `net11` (or `main`) yet. The change builds on the code dotnet#40235 added. For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change Follow-up to dotnet#40235 (fix for dotnet#36156). dotnet#40235 rolls back the XAML Incremental Hot Reload state (`XamlHotReloadState.Restore`) when a XAML edit can't build. It checks three things: the generator reported an error, the generated IC/UC has C# **syntax** errors, or generation threw. It deliberately skipped **semantic** errors. Members added by other generators (CommunityToolkit.Mvvm `[ObservableProperty]` / `[RelayCommand]`) aren't visible to the XAML generator, so a naive type check would roll back valid edits. As a result, an edit that only fails type checking, such as `{Count.Nope()}` (CS1061), still advanced the baseline. The next valid edit was then diffed against a generation the app never received, and the changes made together with the rude edit were lost. **Fix:** `HasSemanticErrors` type-checks the generated `InitializeComponent` and `UpdateComponent` trees against the generator's compilation (user code plus generated code-behind). It runs only when a XAML edit was diffed, i.e. when a rollback snapshot exists. An error counts only if: - it is located in the generated IC/UC code (errors in user code are ignored), and - `MayBeFixedByAnotherGenerator` returns false for it. That helper ignores errors that a declaration added by another generator could resolve: - unresolved names, types and namespaces (CS0103, CS0234, CS0246, CS0426); - failed member lookup (CS1061, CS0117, …) or overload resolution on a receiver whose type is a **`partial` type declared in source**, the only kind of type other generators can add members to. This also covers `?.` member bindings, implicit-`this` invocations, object creations, and errors reported on an argument. **Options considered:** - *Defer the baseline commit until a later signal confirms the compile.* Rejected: inside the generator there is no such signal. The next run's input compilation never contains the previous output, and nothing tells the generator whether the emit or EnC apply succeeded. - *Count all semantic errors.* Rejected: false rollbacks for MVVM Toolkit members. A false positive is worse than a miss, because the next patch re-adds children that are already live. - *Restrict to diagnostics attributable to XAML-generated code and filter out what another generator could fix.* Chosen. **Known remaining gap:** a lookup on a non-`partial` or metadata type (e.g. `int`) that only an extension method from *another generator* could satisfy still counts as an error. That's rare in XAML expressions. C# 14 extension members generated elsewhere fall in the same case. `XamlHotReloadState` is unchanged. The change is limited to `XamlGenerator.cs`, to keep conflicts with the dotnet#40233 follow-up low. **Tests** (`XamlIncrementalHotReloadRudeEditTests`): - `EditAfterRudeEdit_IsDiffedAgainstLastAppliedGeneration(Semantic)`: new case for a type-check-only rude edit, `{Count.Nope()}`. The theory parameter changed from `bool` to a `RudeEdit` enum. - `ElementAddedWithSemanticRudeEdit_IsAddedOnceTheEditIsFixed`: an element added together with a semantic rude edit is added once the edit is fixed. - `MembersGeneratedByAnotherGenerator_DoNotRollBack`: guard. The view model uses `[ObservableProperty]` and `[RelayCommand]`, and the XAML references `Count` (C# expression) and `{Binding SaveCommand}`. The previous edit must not be rolled back, so the added `Button` isn't added again. Without the fix, the 2 semantic cases fail. With `MayBeFixedByAnotherGenerator` disabled, the guard fails. **Validation:** - `dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj --filter FullyQualifiedName~XamlIncrementalHotReloadRudeEditTests`: **9 passed**. Before the fix: 2 failed (the semantic cases), 7 passed. With the filter disabled: 1 failed (the MVVM guard). - `dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj` (full suite): **772 passed, 0 failed, 53 skipped**. - `dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj` with `-p:IncludeAndroidTargetFrameworks=false -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -p:IncludeMacOSTargetFrameworks=false`. The mobile TFMs were excluded because of a local workload mismatch. Result: **2250 passed, 2 failed, 8 skipped**. The 2 failures (`TwoWayDecimalBinding_*`) are known and depend on the machine's locale. - `dotnet format whitespace --folder --include <changed files> --verify-no-changes`: clean. ### Issues Fixed Follow-up to dotnet#40235. Relates to dotnet#36156. <!-- Verify the target branch follows the release workflow in docs/ReleaseBranchWorkflow.md. Infrastructure and documentation changes should target the branch where they apply. --> --------- Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
…ns (dotnet#40378) <!-- 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! ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). > [!IMPORTANT] > **Base: `candidate/11.0.1xx-sr2` (decided).** This PR builds on dotnet#40233, dotnet#40235, dotnet#40329 and dotnet#40330, which exist only on `candidate/11.0.1xx-sr2` (not on `net11`, `main` or `inflight/11.0.1xx-sr3`). Against `net11` the diff would include about 527 unrelated files. As with dotnet#40329 and dotnet#40330, it targets `candidate/11.0.1xx-sr2` directly so it ships together with its prerequisites. ### Description of Change dotnet#40330 left one limitation. A throwaway generator run with different XAML, such as a design-time or speculative run whose output never reaches the app, advanced the cached previous XAML. The next real `UpdateComponent()` was then diffed from that intermediate generation instead of the generation the running app actually has. The result was missed edits: for example, an edit already present in the throwaway XAML was never applied. The generator cannot tell which of its runs reached the app, so this PR has `UpdateComponent()` decide at runtime: - **Generation key.** Each successful generation gets a key: a SHA-256 of the normalized XAML plus the node IDs (`NodeIdHelper.ComputeGenerationKey`). `XamlHotReloadState` keeps the current generation and the previously generated ones as baselines, up to `MaxBaselines = 4`. - **InitializeComponent** records `XamlComponentRegistry.Register(this, "__xihr_generation:<type>", key)`. - **UpdateComponent** reads the instance's recorded key: - A retained generation whose diff produces exactly the current node IDs gets its own branch: the patch diffed from that generation. - Anything else gets the default patch, diffed from the last generated XAML. This matches the previous behavior. - Every patched instance then records the new key, so running the patch again, or for a C#-only edit, changes nothing. - When there is nothing to patch, the output is unchanged: an empty UC, with no marker. Rude-edit rollback behavior is preserved, and the older applied generation now also gets its own branch. **Known edge, not a regression:** a retained generation whose diff would assign different IDs from the current ones (e.g. some reverts) is not given a branch. Instances at that generation fall back to the default patch, which is the old behavior. ### Issues Fixed Fixes dotnet#36937 (remaining limitation from dotnet#40330) ### Tests - `XamlIncrementalHotReloadE2ETests.ThrowawayRunWithDifferentXaml_PatchStartsFromTheAppliedGeneration`: real metadata update. Applied `Text="Hello"`, then a throwaway run with `Text="World" FontSize="30"`, then the real edit to `Text="World"`. The live label ends at `World` with its default `FontSize`, re-running UC is a no-op, and new instances are already current. A new harness hook, `GenerateWithThrowawayRuns`, runs and discards a forked driver run. - `XamlIncrementalHotReloadPipelineTests.ThrowawayRunWithDifferentXaml_PatchesFromEveryRetainedGeneration`: checks the branch structure and determinism (same snapshot and C#-only edits give an identical UC). - `XamlIncrementalHotReloadPipelineTests.RetainedGenerations_AreBounded` - Existing rude-edit assertions now target the default patch (`UpdateComponentText.DefaultPatch`), because the UC legitimately contains a branch for the older applied generation. ### Validation - `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj`: **passed**, 899/899. - `dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --filter "FullyQualifiedName~HotReload"`: **passed**, 12/12. - `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1 dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`: 2274 passed, 12 failed. All 12 failures are `CultureNotFoundException` from culture-specific tests under invariant-globalization mode; none involve hot reload. - `dotnet format whitespace Microsoft.Maui.sln --verify-no-changes --include <changed files>`: **passed**. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…otnet#40413) (dotnet#40417) <!-- 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! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). **Base is `candidate/11.0.1xx-sr2`, not `net11`.** The PR is test-only and covers behavior that exists only on the candidate branch, from the dotnet#36937 fix chain dotnet#40233, dotnet#40235, dotnet#40329, dotnet#40330, and dotnet#40378. Against `net11` the test fails, because that fix has not flowed there yet. This follows the precedent of dotnet#40329, dotnet#40330, and dotnet#40378, which targeted this branch for the same reason. Maintainers: retarget if you prefer a different lane. For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change dotnet#40413 reports that in VS on Windows (.NET 11, SourceGen inflator, XAML Incremental Hot Reload on by default in Debug), editing a Label's `Text` in the default template's `MainPage.xaml` is not applied. **Root cause.** This is dotnet#36937. Roslyn/VS evaluate the same edited generator-driver snapshot more than once, for example forked or speculative runs, or a throwaway compilation before the applied one. On `net11`, the first evaluation advances the cached previous XAML. The evaluation that is actually applied then sees no diff and emits an empty `UpdateComponent`, and the runtime silently skips it. The bug became visible in .NET 11 because XIHR is now the default; 10.0.120 used legacy XAML Hot Reload. I reproduced this with the issue's own template `MainPage.xaml` through the source generator: | Sequence | `net11` (a25e629) | `candidate/11.0.1xx-sr2` (cec6650) | | --- | --- | --- | | Edit evaluated once | patch | patch | | Same edited snapshot evaluated twice: 2nd run | **empty UC** | patch | | Throwaway compilation first, then real run: real run | **empty UC** | patch | On the candidate branch the existing fixes already handle this. This PR adds `DefaultTemplateMainPageTextEdit_SurvivesRepeatedAndThrowawayEvaluations`, a theory with repeated and throwaway-first cases. It uses the template page shape (`StaticResource` styles from a sibling `Styles.xaml`, `x:Name`, a `Clicked` handler in code-behind) to lock in the reported scenario. There are no product changes. **Android .NET 10 (validation comment).** This is a separate scenario. XIHR was not the default in .NET 10, so that report involves the legacy XAML Hot Reload path and is not caused by this regression. It is not addressed here. **Validation** - `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj --filter "FullyQualifiedName~XamlIncrementalHotReloadPipelineTests|FullyQualifiedName~CodeBehindFieldStabilityTests"`: **passed**, 93/93, on this branch. - `net11`: the same two sequences, run through an equivalent temporary probe with the template XAML, produce an empty UC, as shown in the table. I did not port the committed test itself to `net11`: its helpers exist only on candidate, and reverting the fix commits in place conflicts. - Not verified in Visual Studio on Windows or on device; I worked on a macOS host. ### Issues Fixed Fixes dotnet#40413 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
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!
Target Branch
mainnet11, for reviewFor .NET 11 fixes, only a maintainer retargets the approved PR to the active
inflight lane and merges it after CI validates that final base. Do not merge
individual fixes directly into
net11; agents must not retarget or merge.Description of Change
XAML Incremental Hot Reload (XIHR) keeps per-driver state in
XamlHotReloadStateand diffs the previous generation against the current one to emitUpdateComponent(). Roslyn can evaluate the same driver snapshot more than once: driver forks, speculative or design-time requests, and cancelled or discarded runs. The first evaluation advanced the cached "previous" XAML. Every later evaluation of the same inputs then sawprevious == currentand emitted an emptyUpdateComponent(), which silently dropped the edit. @noiseonwires reproduced this deterministically on the issue (edited.RunGenerators(c)twice gives a patch, then an empty method) and matched it to captured VS deltas.Fix (option 1 of the issue, extended):
PatchBaseline). It also stores aUserSourcesFingerprintof the user C# sources it was produced with: path plusSourceText.GetContentHash()per tree, taken from the original compilation without the generated code-behind trees, and memoized perCompilation.UpdateComponent(). This preserves the runtime "non-empty body ⟺ XAML change" classification. It matters because patches aren't always idempotent (reorders useRemoveAt/Insert), so a stale patch must not be re-invoked on later C#-only edits of the same type.Known limitation (needs the cross-team design discussed on the issue): the generator can't tell "a discarded run with different C# evaluated the new XAML first, then the real run" apart from "a XAML edit, then a real C#-only edit". In both cases it sees a patch produced under fingerprint F1 followed by the same XAML under F2. The second case must stay empty, so the first case still loses the patch. Exactly reverting C# to the snapshot of the XAML edit would also re-emit the patch. Fully removing history-dependence needs the classification to move off the empty-
UpdateComponent()signal, for example the per-document companion signal type @noiseonwires proposed.Tests: 7 new cases in
XamlIncrementalHotReloadPipelineTests: forked runs of the same edited driver, the implicit-styleResourceDictionaryrepro shape from the issue, a discarded throwaway run, an interleaved run with different C#, an edit to another XAML file, a revert after forked runs, and a C#-only edit after a XAML edit staying empty. Five of them fail without the fix. The revert and C#-only cases guard existing behavior.Validation:
dotnet testSourceGen.UnitTests (run from a copy of the output in a path without~): 635 passed, 0 failed, 40 skipped.dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj: 2179 passed, 2 failed, 8 skipped. The 2 failures (TwoWayDecimalBinding_*) are locale-dependent on the dev machine (comma decimal separator) and pass withDOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1.dotnet format whitespace --verify-no-changeson the changed files: clean.Issues Fixed
Fixes #36937