Repository navigation
[wasm] Fix fingerprinting client-side assets for publish using the old school hosted approach - #55907
Conversation
Co-authored-by: maraf <[email protected]>
Co-authored-by: maraf <[email protected]>
Co-authored-by: maraf <[email protected]>
Co-authored-by: maraf <[email protected]>
|
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
|
Thanks for your PR, @copilot. |
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
Reverted the
|
| 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:Buildwith no publish at all — lostobj/Debug/$(Tfm)/compressed/file.txt.gzentirely.PublishProjectWithReferences_DifferentBuildAndPublish_LibraryInitializers— lostAnotherClassLib.lib.module.js.gz, anAssetKind=Publishcompressed 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.
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
|
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. |
There was a problem hiding this comment.
🔵 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 asAssetKind=Build. - Rebuild the publish HTML candidate set from non-build
.htmlstatic web assets rather than relying on build-only_HtmlStaticWebAssets. - Exclude
AssetKind=Publishassets 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 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). |
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
AssetKind=Publishstatic web asset in the build manifest.Buildslot.Reconstruct the publish input
_HtmlStaticWebAssetsForPublish) instead of reusing_HtmlStaticWebAssets, which is only populated during build.Exclude publish-only assets from build compression
_CandidateAssetsForBuildnow filters on'%(AssetKind)' != 'Publish'.Scoping the re-tag to the placeholder source assets
The first iteration re-tagged the original HTML with
Update:Inside a target,
Update="@(items)"applies the metadata to the entireStaticWebAssetitem list, not just the referenced items. Every static web asset — including all 212WasmResourceassets — was flipped toAssetKind=Publishand persisted that way into the on-disk build manifest. At publish time those assets then matched dotnet/runtime's_WasmPublishAssetfilter (AssetKind != Build and AssetTraitName == WasmResource) in addition to the copy produced byProcessPublishFilesForWasm, soGenerateWasmBootJsonhit a duplicate dictionary key and failed the build withSystem.ArgumentException: An item with the same key has already been added.MatchOnMetadata/MatchOnMetadataOptionsdo not help here — they are matching controls forRemove, not a scoping mechanism forUpdate, and silently no-op. The fix builds a dedicated item list and doesRemove+Includeinstead:Why build compression filters on
AssetKindRe-tagging the placeholder source as
AssetKind=Publishmade it visible to build compression. That asset is intentionally endpoint-less during build (ResolveHtmlAssetPlaceholdersBuildStaticWebAssetsremoves its endpoints and creates them only for the generated replacement HTML), soApplyCompressionNegotiationfailed looking up endpoints for the related asset:An intermediate commit filtered on a bespoke
HtmlAssetPlaceholderSourcemetadata 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 theStaticWebAssetschema 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:
Identity,ContentRoot) and two endpoints (AssetFile), all gaining thepublish\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.DoesNotFailToCompress_TwoAssetsWith_TheSameContent.Build) genuinely drops oneAssetKind=Publishcompressed asset and its two endpoints — the intended fix, since a plain/t:Buildshould 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
NoBuild=truevariant 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.index.html.gz/index.html.brpayloads decompress to exactly the rewritten HTML, so compressed variants cannot go stale against the placeholder-replaced document.WasmResourceasset as aBuildasset and thatindex.htmlis the onlyPublishasset. This is a direct guard against the metadata leak described above.Build_DoesNotFailToCompress_TwoAssetsWith_TheSameContentto 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 toDoesNotFailToCompress_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 fromcompressed\publish. Inverting the publish-side compression filter fails the publish row and leaves the build row green, confirming the new coverage is load-bearing.