Skip to content

[wasm] Fix fingerprinting client-side assets for publish using the old school hosted approach - #55907

Merged
maraf merged 10 commits into
mainfrom
copilot/fix-blazor-wasm-html-placeholder-replacement
Sep 3, 2026
Merged

maraf merged 10 commits into
mainfrom
copilot/fix-blazor-wasm-html-placeholder-replacement

Conversation

Copilot AI commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Fixes dotnet/runtime#121993

Hosted Blazor WASM publishing used a separate project instance that lost the transient HTML placeholder input created during build. As a result, server publish output retained empty import maps and fingerprint placeholders.

Changes

  • Persist the placeholder source

    • Retain the original HTML as an AssetKind=Publish static web asset in the build manifest.
    • Keep the generated replacement HTML in the Build slot.
  • Reconstruct the publish input

    • Rebuild the publish HTML collection from the persisted non-build HTML assets (_HtmlStaticWebAssetsForPublish) instead of reusing _HtmlStaticWebAssets, which is only populated during build.
  • Exclude publish-only assets from build compression

    • _CandidateAssetsForBuild now filters on '%(AssetKind)' != 'Publish'.

Scoping the re-tag to the placeholder source assets

The first iteration re-tagged the original HTML with Update:

<StaticWebAsset Update="@(_HtmlFilesToRemove)">
  <AssetKind>Publish</AssetKind>
</StaticWebAsset>

Inside a target, Update="@(items)" applies the metadata to the entire StaticWebAsset item list, not just the referenced items. Every static web asset — including all 212 WasmResource assets — was flipped to AssetKind=Publish and persisted that way into the on-disk build manifest. At publish time those assets then matched dotnet/runtime's _WasmPublishAsset filter (AssetKind != Build and AssetTraitName == WasmResource) in addition to the copy produced by ProcessPublishFilesForWasm, so GenerateWasmBootJson hit a duplicate dictionary key and failed the build with System.ArgumentException: An item with the same key has already been added.

MatchOnMetadata / MatchOnMetadataOptions do not help here — they are matching controls for Remove, not a scoping mechanism for Update, and silently no-op. The fix builds a dedicated item list and does Remove + Include instead:

<_HtmlPlaceholderSourceAssets Include="@(_HtmlFilesToRemove)">
  <AssetKind>Publish</AssetKind>
</_HtmlPlaceholderSourceAssets>
<StaticWebAsset Remove="@(_HtmlFilesToRemove)" />
<StaticWebAsset Include="@(_HtmlPlaceholderSourceAssets)" />
<StaticWebAsset Include="@(_UpdatedHtmlStaticWebAssets)" />

Why build compression filters on AssetKind

Re-tagging the placeholder source as AssetKind=Publish made it visible to build compression. That asset is intentionally endpoint-less during build (ResolveHtmlAssetPlaceholdersBuildStaticWebAssets removes its endpoints and creates them only for the generated replacement HTML), so ApplyCompressionNegotiation failed looking up endpoints for the related asset:

error MSB4018: System.InvalidOperationException: Endpoints not found for related asset:
  .../Client/wwwroot/index.html

An intermediate commit filtered on a bespoke HtmlAssetPlaceholderSource metadata flag. Per review feedback that was replaced with '%(AssetKind)' != 'Publish', which mirrors the '%(AssetKind)' != 'Build' filter the publish side already applies. Each side now compresses only what it serves, and the bespoke flag is gone — it was never part of the StaticWebAsset schema and did not survive manifest round-tripping.

This is behaviour-preserving: publish compresses its own assets into $(IntermediateOutputPath)compressed\publish, independently of the build path, so build-time compressed copies of publish-only assets were redundant. It also means builds no longer do compression work for assets only publish serves.

Baseline updates. Seven baselines changed as a direct consequence, all verified field-by-field:

  • Six publish manifests each change exactly one asset (Identity, ContentRoot) and two endpoints (AssetFile), all gaining the publish\ path segment as the compressed asset now comes from publish's own folder. Routes, selectors, response headers, fingerprints, and item ordering are unchanged; the large line counts are a diff artifact of one JSON object being rewritten in place.
  • One build manifest (DoesNotFailToCompress_TwoAssetsWith_TheSameContent.Build) genuinely drops one AssetKind=Publish compressed asset and its two endpoints — the intended fix, since a plain /t:Build should not emit publish-kind compressed assets. This also removes a duplicate endpoint pair the old baseline carried (42 endpoints / 40 unique → 40 / 40).

Regression coverage

  • Enable placeholder replacement in the hosted WASM fixture.
  • Validate hosted publish output has populated import maps, replaced preload placeholders, no fingerprint tokens, and script/preload/import map entries that resolve to real endpoints and files on disk.
  • Add a NoBuild=true variant that builds the Server, deletes the publish output, then publishes. This covers the path where publish must rewrite the HTML from the persisted build manifest rather than from in-memory build state — the scenario the placeholder-source persistence exists for.
  • Assert the compressed index.html.gz / index.html.br payloads decompress to exactly the rewritten HTML, so compressed variants cannot go stale against the placeholder-replaced document.
  • Assert the Client build manifest keeps every WasmResource asset as a Build asset and that index.html is the only Publish asset. This is a direct guard against the metadata leak described above.
  • Extend Build_DoesNotFailToCompress_TwoAssetsWith_TheSameContent to cover publish. It only ran /t:Build, so nothing verified that a publish-only asset still gets compressed once build compression skips publish assets. It is now parameterized over build and publish (shared setup, branching assertions) and renamed to DoesNotFailToCompress_TwoAssetsWith_TheSameContent. The publish row asserts the compressed file reaches the publish output and compares against a new publish baseline showing the compressed assets sourced from compressed\publish. Inverting the publish-side compression filter fails the publish row and leaves the build row green, confirming the new coverage is load-bearing.

@azure-pipelines

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

`<StaticWebAsset Update="@(_HtmlFilesToRemove)">` inside a target's ItemGroup
applied `AssetKind=Publish` and `HtmlAssetPlaceholderSource=true` to the entire
StaticWebAsset item list instead of only the referenced HTML assets.

The contaminated metadata was persisted into the build manifest, so at publish
time `dotnet.native.js` came back as `AssetKind=Publish`. That made it eligible
for `_WasmPublishAsset` alongside the copy produced by `ProcessPublishFilesForWasm`,
causing GenerateWasmBootJson to throw "An item with the same key has already been
added".

Replace the Update with Remove + re-Include of a dedicated item list, which
scopes the metadata to exactly the HTML placeholder sources.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: ea27dbe7-6b4d-4c52-9c7b-7a0e53e340cb
Add coverage for the scenarios the placeholder fix touches:

- A no-build publish variant that builds the Server first, deletes the
  publish output, then publishes with NoBuild=true. This exercises the
  path where publish must rewrite the HTML from the persisted build
  manifest rather than from in-memory build state.
- Assert the compressed index.html.gz / index.html.br payloads decompress
  to exactly the rewritten HTML, so compressed variants cannot go stale
  against the placeholder-replaced document.
- Assert the Client build manifest keeps every WasmResource asset as a
  Build asset and that index.html is the only Publish asset. This guards
  the regression fixed in the previous commit, where placeholder metadata
  leaked onto unrelated assets and produced duplicate boot resources.

The publish assertions also now verify the rewritten script/preload/import
map entries resolve to real endpoints and files on disk.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: ea27dbe7-6b4d-4c52-9c7b-7a0e53e340cb
@marcpopMSFT marcpopMSFT added the Area-AspNetCore RazorSDK, BlazorWebAssemblySDK, StaticWebAssetsSDK label Aug 25, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Thanks for your PR, @copilot.
To learn about the PR process and branching schedule of this repo, please take a look at the SDK PR Guide.

maraf and others added 2 commits August 26, 2026 02:05
Build compression had no AssetKind guard, unlike the publish side which
filters _CandidateAssetsForPublish on '%(AssetKind)' != 'Build'. That gap
was harmless only because publish-only assets did not previously exist at
build time. The HTML placeholder source is the first one, so the missing
guard started producing compressed variants of an asset that intentionally
has no endpoints during build, which made ApplyCompressionNegotiation throw.

Filter on '%(AssetKind)' != 'Publish' instead of the HtmlAssetPlaceholderSource
marker. This restores the build/publish symmetry, states the rule once for all
publish-only assets rather than for one feature, and drops compression's
knowledge of the HTML placeholder feature.

HtmlAssetPlaceholderSource is removed since those two conditions were its only
consumers. It was never part of the StaticWebAsset schema, so it was dropped
when the manifest was written and only survived in memory within a single
project instance, which made it a poor thing to hang the invariant on.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: ea27dbe7-6b4d-4c52-9c7b-7a0e53e340cb
CI build 1567744 failed 18 Helix work items across every platform after
0a3541e switched the _CandidateAssetsForBuild filter to '%(AssetKind)' !=
'Publish'. The two preceding builds ran the identical 545 work items with zero
failures, so the filter change is the cause.

The premise of that commit was wrong. Build compression is supposed to compress
publish-kind assets: it writes them to obj/compressed/ so publish can reuse them.
Build_DoesNotFailToCompress_TwoAssetsWith_TheSameContent, a plain build with no
publish, lost obj/Debug/net11.0/compressed/file.txt.gz entirely, and
PublishProjectWithReferences_DifferentBuildAndPublish_LibraryInitializers lost the
AssetKind=Publish compressed library initializer. Whenever an asset has distinct
build and publish variants a publish-kind asset exists during build and must be
compressed there, so only the publish side can filter on AssetKind.

Leaving the original HTML endpoints in the pipeline instead of filtering was also
tried and does not work. The placeholder source is removed from the asset list at
publish, so its build-time compressed variant is orphaned and
ApplyCompressionNegotiation fails with "Related asset not found for compressed
asset". The exclusion has to happen at build compression.

Restore the HtmlAssetPlaceholderSource filter and the metadata that feeds it, and
document why the placeholder source is excluded so the condition does not read as
an optimization.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: ea27dbe7-6b4d-4c52-9c7b-7a0e53e340cb
@maraf

maraf commented Aug 26, 2026

Copy link
Copy Markdown
Member

Reverted the AssetKind compression filter (48d806e)

Following up on review feedback that suggested replacing the HtmlAssetPlaceholderSource filter in Microsoft.NET.Sdk.StaticWebAssets.Compression.targets with the more general '%(AssetKind)' != 'Publish'. I made that change in 0a3541e — it broke CI, so I've reverted it in 48d806e.

Evidence

Build progression on refs/pull/55907/merge:

Build Commit Helix result
1566735 d2e79f05 ✅ 545 submitted / 0 failed
1567230 e77fef87 ✅ 545 submitted / 0 failed
1567744 0a3541eb ❌ 545 submitted / 19 failed

Same work-item scope in all three, so conditional test filtering wasn't a confound. 18 of the 19 were static web asset baseline manifest mismatches in Microsoft.NET.Sdk.StaticWebAssets.Tests / Microsoft.NET.Sdk.BlazorWebAssembly.Tests across Linux/macOS/Windows x64/FullFramework. (The 19th, a dotnet-new.IntegrationTests Helix timeout, is unrelated — Known Build Error #40074.)

Why the premise was wrong

I had claimed build compression was missing an AssetKind guard that the publish side has, and that publish-kind assets never exist at build time. That was extrapolated from three placeholder-test manifests and is false.

Build compression deliberately compresses both Build and Publish kind assets into obj/compressed/ so publish can reuse them. Counter-examples straight from the failures:

  • Build_DoesNotFailToCompress_TwoAssetsWith_TheSameContent — a plain /t:Build with no publish at all — lost obj/Debug/$(Tfm)/compressed/file.txt.gz entirely.
  • PublishProjectWithReferences_DifferentBuildAndPublish_LibraryInitializers — lost AnotherClassLib.lib.module.js.gz, an AssetKind=Publish compressed asset produced during build.

Generalising: whenever an asset has distinct build and publish variants (library initializers, same-content dedup), a publish-kind asset exists at build time and must be compressed there. Only the publish side can legitimately filter on AssetKind, because build-only assets genuinely don't ship on publish. The asymmetry is by design, not an oversight.

The "keep the endpoints instead" alternative also fails

Suggested offline: don't remove the original HTML endpoints, leave the asset in the pipeline, and drop the compression filter entirely. I tried it — it just relocates the crash.

The placeholder source is a transient carrier: the original un-rewritten index.html, re-tagged AssetKind=Publish so ResolveHtmlAssetPlaceholdersPublishStaticWebAssets can rewrite from a pristine source. That target then removes it from the asset list (<StaticWebAsset Remove="@(_HtmlPublishFilesToRemove)" />). So any compressed variant produced at build is orphaned:

Compression.targets(379,5): error MSB4018: System.InvalidOperationException:
  Related asset not found for compressed asset: .../obj/Debug/net11.0/compressed/rh0ffzuatj-{0}-...gz

instead of the build-side failure it was meant to avoid:

Compression.targets(254,5): error MSB4018: System.InvalidOperationException:
  Endpoints not found for related asset: .../Client/wwwroot/index.html

Invariant: an asset that is removed at publish must not be compressed at build. The exclusion can't be pushed elsewhere.

Final shape

The two _CandidateAssetsForBuild conditions are back to '%(StaticWebAsset.HtmlAssetPlaceholderSource)' != 'true' (the form that was green in builds 1566735 and 1567230), plus a comment explaining the invariant — the != 'true' reads like an optimisation, while the actual failure mode is a task crash three targets away.

Verification (local, against the built redist SDK)

Scope Result
Placeholder tests + the 4 tests that failed in CI 10/10 pass
SWA compression + build/publish-variant suite (~Compress|~DifferentBuildAndPublish|~LibraryInitializers) 40/40 pass
The two specific regression tests, run isolated to confirm they executed 2/2 pass

CI is re-running on 48d806e (build 1568088).

Still open (not a blocker for this PR)

HtmlAssetPlaceholderSource is not part of the StaticWebAsset schema — I confirmed every Publish asset shows HtmlAssetPlaceholderSource: None in written manifests, so it only survives in-memory within a single project instance. That's safe here (build compression and the placeholder retag run in the same instance, and --no-build publish skips build compression), but a durable fix wants a real "not servable / transient asset" concept so compression can express the invariant without a feature-specific flag. Happy to file a follow-up issue.

maraf and others added 2 commits August 27, 2026 17:22
Build compression had no AssetKind filter, so it compressed publish-only
assets into obj/compressed even though publish compresses its own assets
into obj/compressed/publish. That was wasted work, and it broke outright
for assets publish rewrites or drops: the HTML placeholder source is
re-tagged AssetKind=Publish and removed from the asset list at publish, so
its build-time compressed variant had no endpoints during build and no
related asset at publish, crashing ApplyCompressionNegotiation.

Filter _CandidateAssetsForBuild on '%(AssetKind)' != 'Publish', mirroring
the '%(AssetKind)' != 'Build' filter the publish side already applies. This
removes the need for the feature-specific HtmlAssetPlaceholderSource
metadata, which is now dropped.

Regenerate the seven affected baselines. Six publish manifests only
relocate a compressed asset from obj/compressed to obj/compressed/publish
with identical asset and endpoint counts. The build manifest for
Build_DoesNotFailToCompress_TwoAssetsWith_TheSameContent drops the
publish-kind file.txt.gz and its two endpoints, which build should never
have produced.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: ea27dbe7-6b4d-4c52-9c7b-7a0e53e340cb
Build_DoesNotFailToCompress_TwoAssetsWith_TheSameContent only ran /t:Build,
so nothing verified that a publish only asset still gets compressed now that
build compression skips publish assets.

Parameterize the test over build and publish instead of duplicating it. The
setup is shared and only the assertions branch, so the two runs stay in sync.
The publish run asserts the compressed file reaches the publish output and
compares against a new publish baseline showing the compressed assets come
from the publish specific compressed asset folder.

Rename the method and its baselines to drop the Build_ prefix now that it
covers both.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: ea27dbe7-6b4d-4c52-9c7b-7a0e53e340cb
@maraf maraf changed the title Fix hosted Blazor WASM HTML placeholder publishing [wasm] Fix fingerprinting client-side assets for publish using the old school hosted approach Sep 2, 2026
@maraf
maraf marked this pull request as ready for review September 2, 2026 12:09
@maraf
maraf requested a review from a team as a code owner September 2, 2026 12:09
Copilot AI lite review requested due to automatic review settings September 2, 2026 12:09
@azure-pipelines

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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

It changes MSBuild Static Web Assets target/item semantics and compression candidate selection with broad potential impact beyond the covered test scenarios, so it warrants final human validation.

Pull request overview

This PR fixes hosted Blazor WebAssembly publish HTML rewriting/fingerprinting when publish runs from a separate project instance (not carrying transient build-time HTML placeholder inputs), by persisting the placeholder source into the build manifest and reconstructing publish-time HTML inputs from manifest-backed assets. It also updates build-time compression logic to avoid compressing publish-only assets (letting publish produce its own compressed outputs).

Changes:

  • Retag original HTML placeholder source assets as AssetKind=Publish (persisted) and keep the generated, placeholder-rewritten HTML as AssetKind=Build.
  • Rebuild the publish HTML candidate set from non-build .html static web assets rather than relying on build-only _HtmlStaticWebAssets.
  • Exclude AssetKind=Publish assets from build compression candidate selection; update/extend integration tests and baselines accordingly.
File summaries
File Description
test/TestAssets/TestProjects/BlazorWasmReferencedByAspNetCoreServer/Client/Client.csproj Enables HTML placeholder replacement in the hosted WASM test asset.
test/Microsoft.NET.Sdk.StaticWebAssets.Tests/StaticWebAssetsIntegrationTest.cs Parameterizes compression regression coverage across build vs publish and updates assertions/baselines usage.
test/Microsoft.NET.Sdk.StaticWebAssets.Tests/StaticWebAssetsBaselines/PublishProjectWithReferences_DifferentBuildAndPublish_LibraryInitializers.Publish.staticwebassets.json Updates publish manifest baseline to reflect publish-scoped compressed asset paths.
test/Microsoft.NET.Sdk.StaticWebAssets.Tests/StaticWebAssetsBaselines/Publish_CreatesEndpointsForAssets_BuildAndPublish_Assets.Publish.staticwebassets.json Updates publish manifest baseline so endpoints/assets reference compressed\\publish\\ outputs.
test/Microsoft.NET.Sdk.StaticWebAssets.Tests/StaticWebAssetsBaselines/DoesNotFailToCompress_TwoAssetsWith_TheSameContent.Publish.staticwebassets.json Adds new publish baseline for the extended compression regression test.
test/Microsoft.NET.Sdk.StaticWebAssets.Tests/StaticWebAssetsBaselines/DoesNotFailToCompress_TwoAssetsWith_TheSameContent.Publish.files.json Adds publish file baseline for compressed/published outputs.
test/Microsoft.NET.Sdk.StaticWebAssets.Tests/StaticWebAssetsBaselines/DoesNotFailToCompress_TwoAssetsWith_TheSameContent.Build.staticwebassets.json Updates build baseline to drop publish-kind compressed outputs from build manifests/endpoints.
test/Microsoft.NET.Sdk.StaticWebAssets.Tests/StaticWebAssetsBaselines/DoesNotFailToCompress_TwoAssetsWith_TheSameContent.Build.files.json Adds/updates build file baseline for build-only compression outputs.
test/Microsoft.NET.Sdk.BlazorWebAssembly.Tests/WasmPublishIntegrationTest.cs Adds hosted WASM publish/no-build regression assertions for rewritten HTML, import maps, and compressed HTML matching rewritten content.
test/Microsoft.NET.Sdk.BlazorWebAssembly.Tests/StaticWebAssetsBaselines/StaticWebAssets_Publish_Hosted_Works.Publish.staticwebassets.json Updates baseline to reflect publish-scoped compressed assets/endpoints.
test/Microsoft.NET.Sdk.BlazorWebAssembly.Tests/StaticWebAssetsBaselines/StaticWebAssets_Publish_DoesNotIncludeXmlDocumentationFiles_AsAssets.Publish.staticwebassets.json Updates baseline to reflect publish-scoped compressed assets/endpoints.
test/Microsoft.NET.Sdk.BlazorWebAssembly.Tests/StaticWebAssetsBaselines/JsModules_Hosted_CanCustomizeBlazorInitialization.Publish.staticwebassets.json Updates baseline to reflect publish-scoped compressed assets/endpoints.
test/Microsoft.NET.Sdk.BlazorWebAssembly.Tests/StaticWebAssetsBaselines/JsModules_CanHaveDifferentBuildAndPublishModules.Publish.staticwebassets.json Updates baseline to reflect publish-scoped compressed assets/endpoints.
src/StaticWebAssetsSdk/Targets/Microsoft.NET.Sdk.StaticWebAssets.HtmlAssetPlaceholders.targets Persists placeholder source as publish-kind and reconstructs publish HTML inputs from non-build HTML assets.
src/StaticWebAssetsSdk/Targets/Microsoft.NET.Sdk.StaticWebAssets.Compression.targets Filters build compression candidates to exclude publish-only assets.
Review details
  • Files reviewed: 13/15 changed files
  • Comments generated: 0
  • Review effort level: Lite

@maraf
maraf merged commit 34cf6f9 into main Sep 3, 2026
23 checks passed
@maraf
maraf deleted the copilot/fix-blazor-wasm-html-placeholder-replacement branch September 3, 2026 06:57
@Dresel

Dresel commented Oct 19, 2026

Copy link
Copy Markdown

@maraf would you consider backporting this to release/11.0.1xx? We hit the same issue with a hosted Blazor WebAssembly client on .NET 11 RC 2 (11.0.100-rc.2.26504.105).

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

Labels

Area-AspNetCore RazorSDK, BlazorWebAssemblySDK, StaticWebAssetsSDK Area-WasmSdk

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Fingerprinting client-side assets using the old school hosted approach

6 participants