Skip to content

[Blazor] Validate component metadata under Native AOT - #68302

Open
javiercn wants to merge 1 commit into
javiercn-framework-component-metadatafrom
javiercn-aspire-dashboard-aot-strict-proof
Open

javiercn wants to merge 1 commit into
javiercn-framework-component-metadatafrom
javiercn-aspire-dashboard-aot-strict-proof

Conversation

@javiercn

@javiercn javiercn commented Aug 9, 2026 •

Copy link
Copy Markdown
Member

Overview

Layer 6 of 6 for the Native AOT metadata stack; depends on #68300 and completes the umbrella feature tracked by #68332. It turns the existing feature matrix into a strict Native AOT proof without adding a product API, runtime feature, provider, root, or scenario. The cross-cutting constraint is that the app must publish and run with the STJ, component-metadata, and JS-invokable reflection fallbacks disabled; incomplete generated metadata or any ILC warning fails the build.

Design

There are no public API changes. The new contract is build-time and test-app-local: the application exposes RazorComponentsReflectionEnabledByDefault to the metadata generator, and the generator escalates only diagnostics whose runtime recovery requires component reflection.

// src/Components/Endpoints/gen/RazorComponentsMetadataGenerator.cs
// Unset/true preserves warning-plus-reflection compatibility; false requires complete generated metadata.
private const string ReflectionEnabledByDefaultPropertyName =
    "build_property.RazorComponentsReflectionEnabledByDefault";

var reflectionEnabledByDefault = context.AnalyzerConfigOptionsProvider
    .Select(static (provider, _) =>
        !provider.GlobalOptions.TryGetValue(ReflectionEnabledByDefaultPropertyName, out var value) ||
        !string.Equals(value, "false", StringComparison.OrdinalIgnoreCase));

context.RegisterSourceOutput(
    models.Combine(reflectionEnabledByDefault),
    static (spc, pair) => Emit(spc, pair.Left, pair.Right));

// BLAZORAOT001 is incomplete component metadata; BLAZORAOT004 is the parallel endpoint-attribute case.
var descriptor = (Id, reflectionEnabledByDefault) switch
{
    ("BLAZORAOT001", false) => DiagnosticDescriptors.ComponentNotFullyDescribedError,
    ("BLAZORAOT004", false) => DiagnosticDescriptors.ComponentAttributeNotDescribedError,
    ("BLAZORAOT004", _) => DiagnosticDescriptors.ComponentAttributeNotDescribed,
    _ => DiagnosticDescriptors.ComponentNotFullyDescribed,
};

The dedicated feature app enables Native AOT analysis, requires complete generated component metadata, and promotes ILC warnings to errors. Runtime fallback removal remains separately gated by BlazorAotStrictMode, so the same scenarios retain ordinary compatibility coverage.

<!-- src/Components/test/testassets/BlazorAotFeatures/BlazorServerAotSample/BlazorServerAotSample.csproj -->
<PropertyGroup>
  <PublishAot>true</PublishAot>
  <RazorComponentsReflectionEnabledByDefault>false</RazorComponentsReflectionEnabledByDefault>
  <IlcTreatWarningsAsErrors>true</IlcTreatWarningsAsErrors>
</PropertyGroup>

<ItemGroup Condition="'$(BlazorAotStrictMode)' == 'true'">
  <!-- Three equivalent fallback classes are disabled independently. -->
  <RuntimeHostConfigurationOption
      Include="System.Text.Json.JsonSerializer.IsReflectionEnabledByDefault"
      Value="false" Trim="true" />
  <RuntimeHostConfigurationOption
      Include="Microsoft.AspNetCore.Components.ComponentMetadata.IsReflectionEnabledByDefault"
      Value="false" Trim="true" />
  <RuntimeHostConfigurationOption
      Include="Microsoft.JSInterop.JSInvokableMethodResolution.IsReflectionEnabledByDefault"
      Value="false" Trim="true" />
</ItemGroup>

A broad NoWarn or product suppression was deliberately rejected because it would weaken the zero-warning proof. HTTP form mapping is not exercised by this matrix and is not Native-AOT-supported here, so the strict test image removes only that private implementation through an app-owned ILC substitution; product assemblies and non-strict behavior are unchanged.

Implementation

The test project uses the shared MSTest/Components.Testing harness introduced by #68289 and #67083. The app reference selects published Native AOT mode, provides the RID required by the shared target, and forwards strict mode through the standard AdditionalProperties contract.

<!-- src/Components/Testing/testassets/BlazorAotFeatures.E2E.Tests/BlazorAotFeatures.E2E.Tests.csproj -->
<ProjectReference Include="../../../test/testassets/BlazorAotFeatures/BlazorServerAotSample/BlazorServerAotSample.csproj">
  <E2EApp>true</E2EApp>
  <E2EAppMode>publish</E2EAppMode>
  <E2ENativeAot>true</E2ENativeAot>
  <E2ERuntimeIdentifier>$(RuntimeIdentifier)</E2ERuntimeIdentifier>
  <AdditionalProperties>UseIisNativeAssets=false</AdditionalProperties>
  <AdditionalProperties Condition="'$(BlazorAotStrictMode)' == 'true'">
    UseIisNativeAssets=false;BlazorAotStrictMode=true
  </AdditionalProperties>
</ProjectReference>

The shared target turns E2ENativeAot into E2ECompileTestHarness=true for the nested publish. In the source tree, the app references the shared Native AOT generator as an analyzer unconditionally so clean restore sees the project; generation itself remains property-gated. CreateSlimBuilder deliberately skips hosting startups, so the app invokes the shared generated extension explicitly only in that nested publish.

<!-- src/Components/test/testassets/BlazorAotFeatures/BlazorServerAotSample/BlazorServerAotSample.csproj -->
<PropertyGroup Condition="'$(E2ECompileTestHarness)' == 'true'">
  <DefineConstants>$(DefineConstants);E2E_COMPILE_TEST_HARNESS</DefineConstants>
</PropertyGroup>

<ItemGroup>
  <CompilerVisibleProperty Include="E2ECompileTestHarness" />
  <!-- Source-tree equivalent of the package's buildTransitive analyzer hook. -->
  <ProjectReference Include="../../../../Testing/nativeaot/Microsoft.AspNetCore.Components.Testing.NativeAot.csproj"
                    OutputItemType="Analyzer"
                    ReferenceOutputAssembly="false" />
</ItemGroup>
// src/Components/test/testassets/BlazorAotFeatures/BlazorServerAotSample/Program.cs
var builder = WebApplication.CreateSlimBuilder(args);

// Slim hosting omits static-web-assets manifest loading; Blazor Server still needs blazor.web.js.
builder.WebHost.UseStaticWebAssets();

#if E2E_COMPILE_TEST_HARNESS
// Use the shared source-generated harness. No old xUnit or custom NativeTesting plumbing remains.
builder.Services.AddE2ETestHarness();
#endif

[UnconditionalSuppressMessage("Trimming", "IL2026",
    Justification = "Every path this application exercises is covered by the descriptors in " +
        "SampleMetadata, which replace the reflection fallbacks these gates warn about.")]
static void AddInteractiveServerBlazor(IServiceCollection services)
{
    services.AddComponentMetadata<SampleMetadata>();
    services.AddRazorComponents()
        .AddInteractiveServerComponents(options =>
        {
            options.RootComponents.RegisterForJavaScript<AotDynamicRoot>("aot-dynamic-root");
        });
}

The only excluded behavior class is the unsupported HTTP form mapper. The target is doubly gated on strict mode and Native AOT, and the substitution has three exact deltas: CanMap returns false; Map and CreateDeserializer have no bodies. This makes the code unreachable in the proof image without suppressing a warning code or claiming form-mapping support.

<!-- src/Components/test/testassets/BlazorAotFeatures/BlazorServerAotSample/BlazorServerAotSample.csproj -->
<Target Name="AddStrictFormMappingSubstitutions"
        BeforeTargets="WriteIlcRspFileForCompilation"
        Condition="'$(BlazorAotStrictMode)' == 'true' and '$(PublishAot)' == 'true'">
  <ItemGroup>
    <IlcArg Include="--substitution:$([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)BlazorServerAotSample.ILLink.Substitutions.xml'))" />
  </ItemGroup>
</Target>
<!-- src/Components/test/testassets/BlazorAotFeatures/BlazorServerAotSample/BlazorServerAotSample.ILLink.Substitutions.xml -->
<linker>
  <assembly fullname="Microsoft.AspNetCore.Components.Endpoints">
    <type fullname="Microsoft.AspNetCore.Components.Endpoints.HttpContextFormValueMapper">
      <!-- The strict matrix never requests form mapping, so capability discovery returns false. -->
      <method signature="System.Boolean CanMap(System.Type,System.String,System.String)"
              body="stub" value="false" />
      <!-- Dynamic mapping and generic deserializer construction cannot be reached afterward. -->
      <method signature="System.Void Map(Microsoft.AspNetCore.Components.Forms.Mapping.FormValueMappingContext)"
              body="remove" />
      <method signature="Microsoft.AspNetCore.Components.Endpoints.HttpContextFormValueMapper/FormValueSupplier CreateDeserializer(System.Type)"
              body="remove" />
    </type>
  </assembly>
</linker>

Outcome

Equivalence class Result What it proves
Repository build 0 warnings, 0 errors The stacked change remains compatible with the complete managed/native build graph.
Affected unit and generator suites 3,592 passed, 8 skipped Runtime, provider, serialization, JSInterop, WebAssembly, and generator behavior remains intact.
Generator severity matrix 116/116 passed under MSTest Warning/error escalation survived the shared-harness migration.
JIT feature matrix 22/22 passed Existing scenarios still work with default compatibility behavior.
JIT fallback witness 1/1 passed Undescribed component, JS method, and JSON payload reflection remains enabled by default.
Strict Native AOT publish 0 compiler/ILC warnings, 0 errors Shared E2ENativeAot publishing removes all three supported reflection fallbacks without hiding warning codes.
Strict Native AOT MSTest matrix 21/21 passed Every generated-only browser scenario runs through the shared harness; only the intentional JitDefault witness is excluded.

Disable the STJ, component metadata, and JS-invokable reflection fallbacks in the strict feature app, promote incomplete generated metadata to errors, and require ILC warnings as errors. Keep unsupported HTTP form mapping outside the proof image through a strict-test-only substitution.

Co-authored-by: Copilot App <[email protected]>
@javiercn
javiercn force-pushed the javiercn-aspire-dashboard-aot-strict-proof branch from 7274404 to 43c0eb4 Compare August 11, 2026 11:49
@javiercn
javiercn marked this pull request as ready for review August 11, 2026 14:07
@javiercn
javiercn requested a review from a team as a code owner August 11, 2026 14:07
Copilot AI lite review requested due to automatic review settings August 11, 2026 14:07

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR completes the final “strict Native AOT proof” layer for the Blazor component metadata stack by making the test assets and generator diagnostics capable of running with reflection fallbacks disabled and with ILC warnings promoted to errors, without introducing new product-facing APIs.

Changes:

  • Updates the dedicated Blazor AOT feature E2E test asset to publish/run in Native AOT mode via the shared compiled-harness pipeline, including forwarding strict-mode properties and a required RID.
  • Extends RazorComponentsMetadataGenerator to read RazorComponentsReflectionEnabledByDefault from analyzer config and escalate selected diagnostics (BLAZORAOT001/BLAZORAOT004) to errors when reflection is disabled by default.
  • Adds strict-mode ILC substitution for the unsupported HTTP form mapper in the proof image, plus local suppressions for trimming warnings in the test app.

Reviewed changes

Copilot reviewed 9 out of 9 changed files in this pull request and generated no comments.

Show a summary per file
File Description
src/Components/Testing/testassets/BlazorAotFeatures.E2E.Tests/BlazorAotFeatures.E2E.Tests.csproj Switches the E2E project reference to publish-mode with Native AOT compiled harness and forwards strict-mode properties/RID.
src/Components/test/testassets/BlazorAotFeatures/BlazorServerAotSample/Program.cs Uses CreateSlimBuilder + UseStaticWebAssets, registers the compiled E2E harness, and adds trimming suppressions at call sites.
src/Components/test/testassets/BlazorAotFeatures/BlazorServerAotSample/BlazorServerAotSample.ILLink.Substitutions.xml Adds strict-mode linker substitutions to disable HTTP form mapping implementation in the proof image.
src/Components/test/testassets/BlazorAotFeatures/BlazorServerAotSample/BlazorServerAotSample.csproj Enables Native AOT publishing for the asset, disables reflection by default for generated component metadata, and wires strict-mode host config + substitutions.
src/Components/Endpoints/test/Microsoft.AspNetCore.Components.Endpoints.Generators.Tests/RazorComponentsMetadataGeneratorTestBase.cs Adds a test analyzer-config options provider to simulate RazorComponentsReflectionEnabledByDefault for generator tests.
src/Components/Endpoints/test/Microsoft.AspNetCore.Components.Endpoints.Generators.Tests/RazorComponentsMetadataGeneratorDiagnosticTests.cs Expands diagnostic tests to validate warning vs error severity depending on reflection-default mode.
src/Components/Endpoints/gen/RazorComponentsMetadataGenerator.cs Reads build property via analyzer config and routes severity selection into diagnostic creation.
src/Components/Endpoints/gen/Emitters/RazorComponentsMetadataGenerator.Emitter.cs Plumbs reflection-default mode into diagnostic reporting.
src/Components/Endpoints/gen/DiagnosticDescriptors.cs Adds “Error” variants of key descriptors by cloning existing descriptors with DiagnosticSeverity.Error.
Suppressed comments (1)

src/Components/test/testassets/BlazorAotFeatures/BlazorServerAotSample/Program.cs:80

  • AddSession() is explicitly annotated with [RequiresUnreferencedCode("Session State middleware does not currently support trimming or native AOT.")] (see src/Middleware/Session/src/SessionServiceCollectionExtensions.cs:21-28). Suppressing IL2026 here makes the strict Native AOT lane claim to be warning-free while still relying on a feature the framework marks as unsupported for Native AOT. Consider removing session usage from the strict matrix (or gating it out when BlazorAotStrictMode=true) so the proof image doesn’t depend on Session, or update the scenario to use an AOT-supported persistence mechanism.
[UnconditionalSuppressMessage("Trimming", "IL2026",
    Justification = "This sample only stores generated-contract values through the session-backed component state feature.")]
static void AddSessionSupport(IServiceCollection services)
{
    services.AddDistributedMemoryCache();
    services.AddSession();

💡 Add a code-review agent skill for context-aware, tailored reviews. Learn more in the docs.

@Youssef1313 Youssef1313 added the area-blazor Includes: Blazor, Razor Components label Sep 2, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been active for some time and the codebase could have been changed in the meantime.
To make sure no conflicting changes have occurred, please rerun validation before merging. You can do this by leaving an /azp run comment here (requires commit rights), or by simply closing and reopening.

@dotnet-policy-service dotnet-policy-service Bot added the pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun label Sep 26, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-blazor Includes: Blazor, Razor Components pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants