Skip to content

[XSG] XamlHotReloadState static cache is brittle across multiple throwaway Roslyn compilations #36937

Done

Description

@StephaneDelcroix

Follow-up to @tmat's review on #36833 (inline comment on src/Controls/src/SourceGen/XamlHotReloadState.cs).

Concern

XamlHotReloadState holds XAML Incremental Hot Reload (XIHR) generation state in mutable static state and diffs the CURRENT generation against a CACHED PREVIOUS one to produce the incremental patch (the UpdateComponent() body).

Tomas asked (paraphrased): "Sounds somewhat brittle. Would it work well if Roslyn created multiple compilations in the same process, ran source generators on them, and then threw them away?"

Why it's brittle

The cache is static (not tied to a specific Compilation) and survives across compilations in the same process — e.g. an IDE/design-time host, dotnet watch, or a test host that spins up several Compilations. Interleaved or throwaway compilations can:

  • Miss a real change — if the "previous" cached snapshot came from an unrelated/throwaway compilation, the diff against the current content can come out empty, so UpdateComponent() is emitted empty and Hot Reload silently drops a genuine XAML edit.
  • Report a spurious change — conversely, a stale cached "previous" can make an unchanged file look changed.

This matters now that XIHR is on-by-default in Debug (#36833) and the diagnostics signal is "empty UpdateComponent() body ⟺ no XAML change", classified pre-dispatch on UpdateRequested.HandledTypes. A poisoned cache corrupts that signal.

Options

  1. Key the cache by Compilation (e.g. ConditionalWeakTable<Compilation, …>) so throwaway compilations don't cross-contaminate and entries are collected with the compilation. Lowest-risk; keeps the empty-UC signal.
  2. Drop the cache entirely and always full-reapply the UpdateComponent() body. Most robust, but then UpdateComponent() is never empty, which breaks the empty-UC diagnostics signal — would require moving change-classification to a runtime UpdateComponent() IL diff and re-aligning with the XamlTools team (@noiseonwires).
  3. Move to incremental-generator-native caching (IncrementalValueProvider) instead of hand-rolled static state.

Option 1 is the likely near-term fix; option 2 is the "correct" long-term design but carries a cross-team contract implication.

References

cc @tmat

Activity

  1. added
    partner/hot-reload-xaml
    xsg
    on Jul 30, 2026
  2. added
    s/triaged
    on Jul 30, 2026
  3. noiseonwires commented on Nov 6, 2026

    @noiseonwires
    Member

    We now have a concrete reproduction of the lost UpdateComponent patch described here, on the build containing #39928.

    Tested build

    Important distinction: #39928 fixes the original implicit-style replacement problem in #39780. The attached minimal app now works in a manual VS test. A larger demo and CommunityToolkit.Maui.Sample still fail, but their captured deltas lack the live patch entirely; this is a separate generation-state problem, not evidence that executing the replacement code fails.

    Deterministic generator-driver reproduction

    Use the actual packaged Microsoft.Maui.Controls.SourceGen.XamlGenerator with a reusable Roslyn driver. Supply a ResourceDictionary with an implicit Label style:

    <ResourceDictionary xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
                        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                        x:Class="Repro.Styles">
        <Style TargetType="Label">
            <Setter Property="TextColor" Value="Red" />
        </Style>
    </ResourceDictionary>

    Use a partial Styles : ResourceDictionary whose constructor calls InitializeComponent. Additional-file metadata selects GenKind=Xaml, Inflator=SourceGen, EnableIncrementalHotReload=true, with consistent RelativePath/TargetPath/ManifestResourceName; the global configuration is Debug/net11.0. Replace only the Red literal with Blue.

    The critical sequence is two branches from the same immutable edited driver, not two distinct generator instances:

    var baseline = configuredRedDriver.RunGenerators(compilation);
    var edited = baseline.ReplaceAdditionalText(redText, blueText);
    
    var first = edited.RunGenerators(compilation);
    var second = edited.RunGenerators(compilation); // SAME inputs and driver snapshot
    
    static string Patch(GeneratorDriver driver) => driver.GetRunResult()
        .Results.Single().GeneratedSources
        .Single(s => s.HintName.EndsWith(".uc.xsg.cs"))
        .SourceText.ToString();
    
    // Expected: Patch(first) == Patch(second), both contain the Blue replacement.
    // Actual: first contains CreateStyle_... + dictionary Remove/AddFactory;
    //         second contains an empty UpdateComponent, identical to the Red baseline.

    The second branch still generates Blue initialization, so relative to the Red baseline it changes InitializeComponent only. Compiling baseline initialization plus each generated patch and invoking it on retained implicit-style consumers gives:

    • First branch: retained Label becomes Blue.
    • Second branch: retained Label remains Red.

    A controlled probe passed 32 assertions across explicit/implicit XML namespaces and simple/complex styles, including the demo's actual implicit Label style with VisualStateGroups and AppThemeBinding resource lookups. The first patch works for all four shapes; the second branch loses it for all four. This rules out those style/namespace differences as an inherent reason the replacement cannot work.

    Captured VS evidence

    Windows session Initialization delta Live patch delta
    Larger demo, failed Red -> Blue Missing; method remains empty
    CommunityToolkit sample, failed Red -> Blue Missing; method remains empty
    Minimal app from #39780, works Red -> Blue Present

    For the larger demo, the captured baseline dictionary's InitializeComponent token is 06000011, and its UpdateComponent is 06000013. The emitted Windows method list includes the former, not the latter. The baseline patch is two bytes, 00 2A (nop; ret). The inactive Android target in the same apply does receive the typed style-replacement patch.

    For the subsequent Toolkit retest (update 2.1), Windows initialization token 060000C6 is updated, while patch token 060000C8 is omitted and its baseline is also 00 2A. The old/new initialization snapshots differ at exactly one line, Colors.Red -> Colors.Blue. All four Toolkit TFMs show initializer-only changes and no changed .uc.xsg.cs source in that apply.

    State mechanism

    The per-driver session token does not isolate driver snapshots/branches sharing the same pipeline closure:

    The first branch advances shared cached text to Blue before runtime apply acknowledgment. The second branch sees previousXaml == currentXaml, computes no patch, and emits the empty method. Locking cache access does not provide snapshot isolation or deterministic output.

    Limit: the controlled test proves this failure mechanism and matches the captured VS output. The logs do not identify the exact earlier VS background/speculative invocation that consumed the patch in either session; that still needs cache/driver instrumentation.

    Please add regression coverage for repeated evaluation/driver forks with identical edited inputs, alongside the existing linear metadata-update tests. A valid pending patch must not disappear because another generation evaluated the same XAML first. Baseline ownership also needs to remain correct across cancellation, rejected deltas, reverts, unrelated C# regeneration and concurrent design-time requests.

  4. noiseonwires commented on Nov 11, 2026

    @noiseonwires
    Member

    One proposal for preserving XIHR E2E classification while moving away from history-dependent empty/non-empty UpdateComponent() bodies: generate a dedicated, XAML-only companion signal type per document.

    // Schematic; emitted from the first generation, with stable type/member names.
    internal static class MainPageXamlSignal
    {
        internal static string Identity() => "semantic-XAML-fingerprint";
        internal static Type RootType() => typeof(MainPage);
    }

    A XAML change changes the fingerprint method body, so the companion appears in Roslyn's changed-type list. A pure C# edit leaves it unchanged. The MUH recognizes companions in updatedTypes, maps/deduplicates them to their roots, and preserves synchronous UpdateRequested.HandledTypes classification plus the existing UpdateApplied/UpdateSkipped/UpdateFailed contract. This needs neither page instances nor startup capture of old fingerprints; Roslyn's existing accepted compilation baseline supplies the comparison, without a new Roslyn/PS origin flag.

    A small EmitDifference probe passed four cases: C#-only excludes the companion; XAML-only, mixed, and replayed XAML edits include it. The signal must be independent of unrelated C# regeneration and use semantic fingerprinting to avoid formatting-only false positives.

  5. added 7 commits that reference this issue on Nov 13, 2026
    cd545a2
    4887ef6
    1a5b0b5
    5e01d4b
    32ef9fd
    9b6b626
    0ff5024
  6. added 2 commits that reference this issue on Nov 17, 2026
    4335068
    861a183
  7. 22 remaining items

  8. added 5 commits that reference this issue on Nov 26, 2026
    d2fd292
    af16ecc
    2459adf
    ecbae46
    0cbb037
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

partner/hot-reload-xamls/triagedxsg

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions