Skip to content

[browser][coreclr] Support WasmRunWasmOpt for ReadyToRun images - #136772

Merged
lewing merged 3 commits into
mainfrom
lewing-r2r-wasm-opt-prototype
Nov 10, 2026
Merged

lewing merged 3 commits into
mainfrom
lewing-r2r-wasm-opt-prototype

Conversation

@lewing

@lewing lewing commented Nov 1, 2026 •

Copy link
Copy Markdown
Member

Stacked on #136771 (opt-in WasmRunWasmOpt for the CoreCLR native relink). Review only the two commits below; the base commit belongs to #136771.

When WasmRunWasmOpt=true, run wasm-opt over the per-app browser CoreCLR ReadyToRun images after crossgen2 and before webcil staging and fingerprinting. The option stays opt-in: per #136075, wasm-opt shouldn't be on by default while codegen is changing.

Commits

94c0c69 — Support WasmRunWasmOpt for ReadyToRun images

  • The pass lives in the workload's BrowserWasmApp.CoreCLR.targets, where the Emscripten SDK provides wasm-opt.
    • _WasmCoreClrConfigureR2RWasmOpt builds the wasm-opt arguments.
    • _WasmCoreClrOptimizeR2RImages (AfterTargets _CreateR2RImages) rewrites the images in obj/R2R in place: each per-assembly image, or just the composite. Component stubs are skipped.
  • The wasm-opt settings are added to the SDK pack's R2R state stamp, so toggling them or changing their arguments recompiles every image.
  • Each optimized image gets a *.wasm-opt.stamp file:
    • A recompiled image is optimized again, and an up-to-date one isn't optimized twice.
    • wasm-opt writes to a temporary file, so a failed run leaves the crossgen2 output in place and the next build retries it.
  • The SDK pack warns when WasmRunWasmOpt and PublishReadyToRun are set but the workload targets aren't imported.
  • The wasm features come from [browser][coreclr] Support WasmRunWasmOpt in the native relink #136771's shared @(_WasmOptFeatureFlag) (the native.wasm.targets baseline plus relaxed SIMD); crossgen2's images carry no target_features section either. Sign-ext and mutable-globals are binaryen defaults, so they aren't passed.
  • --skip-pass=memory-packing keeps the data segments intact. Passive segment 0 holds the payload and table sizes that AttachWebcilSizes reads for the boot config.
  • The default is -O2; the relink in [browser][coreclr] Support WasmRunWasmOpt in the native relink #136771 defaults to -Oz. On R2R images -O2 produced smaller Brotli output than both -Oz and -O3. An -O level in WasmOptConfigurationFlags overrides it.
  • Adds a dedicated R2R wasm-opt test; the third commit folds it into the wasm-opt lane.

d643105 — Keep R2R Webcil payload aligned after wasm-opt

b487e93 — Address review: shared wasm-opt resolution, workload requirement, lane tests

  • The R2R pass resolves wasm-opt through [browser][coreclr] Support WasmRunWasmOpt in the native relink #136771's _CoreCLRResolveWasmOpt ($(_WasmOptPath)) instead of a second lookup.
  • The workload manifest now requires the browser workload when WasmRunWasmOpt=true for CoreCLR (_WasmNativeWorkloadNeeded). Mono is unchanged. The SDK pack warning stays as a fallback for builds that still lack the workload targets, for example with UsingBrowserRuntimeWorkload=false.
  • R2R wasm-opt coverage now runs in [browser][coreclr] Support WasmRunWasmOpt in the native relink #136771's wasm-opt lane, following its pattern of conditional asserts:
    • AssertReadyToRunWasmOpt checks stamps and payload alignment when the lane enables WasmRunWasmOpt, and that nothing was optimized otherwise.
    • Per-assembly: NativeLibraryTests.ProjectWithNativeReference_ReadyToRun, now tagged wasm-opt.
    • Composite: PublishRunAllPagesWasmOpt is replaced by ReadyToRunTests.PublishRunAllPagesCompositeWithWorkload. No existing workload-mode test publishes a composite; the other R2R publish tests are no-workload, which the lane excludes. PInvokeTableGeneratorTests.UnusedQCallsAreTrimmed is tagged wasm-opt but doesn't set PublishReadyToRun, so it doesn't crossgen.

Size (BlazorBasicTestApp, trimmed Release, Brotli bytes, wasm-opt off → on)

Names kept (current crossgen2 default) Names stripped (--wasm-debug-info none, as in #136506)
Composite image 2,044,015 → 1,711,806 (−16.3%) 1,806,645 → 1,503,875 (−16.8%)
Per-assembly, 35 images 3,829,605 → 3,530,793 (−7.8%) 3,661,499 → 3,365,255 (−8.1%)

Raw sizes: CoreLib 7.79 MB → 6.69 MB; the composite 13.7 MB → 10.0 MB with names stripped. wasm-opt adds roughly 0–4 s per publish here, within run-to-run noise.

Validation

  • ./build.sh -os browser -s clr+libs+packs -c Release /p:InstallWorkloadForTesting=false /p:BuildCrossgen2HostPackForWorkloadTesting=true: succeeded.
  • ./dotnet.sh build src/tasks/WasmAppBuilder/WasmAppBuilder.csproj -c Release: succeeded, no warnings.
  • ./dotnet.sh build src/mono/wasm/Wasm.Build.Tests/Wasm.Build.Tests.csproj -c Release -t:Test -p:TargetOS=browser -p:TargetArchitecture=wasm -p:RuntimeFlavor=CoreCLR -p:TestUsingWorkloads=true -p:InstallWorkloadForTesting=false -p:XUnitMethodName=Wasm.Build.Tests.ReadyToRunTests.PublishRunAllPagesWasmOpt: passed 2/2.
  • After the review changes (re-run after rebasing onto [browser][coreclr] Support WasmRunWasmOpt in the native relink #136771 at 741a17b, itself rebased onto main), the local wasm-opt lane (./dotnet.sh build src/mono/wasm/Wasm.Build.Tests/Wasm.Build.Tests.csproj -c Release -t:Test -nodeReuse:false -p:TargetOS=browser -p:TargetArchitecture=wasm -p:RuntimeFlavor=CoreCLR -p:TestUsingWorkloads=true -p:InstallWorkloadForTesting=false -p:WasmRunWasmOpt=true) selected 16 tests and 15 passed. ProjectWithNativeReference_ReadyToRun optimized 16 per-assembly images; PublishRunAllPagesCompositeWithWorkload optimized the composite and logged Loaded R2rSuffixLibrary.r2r. The failure is the same environmental WasmSIMDTests.PublishRelaxedSimdCoreClr(relaxedSimd: False) described below.
    • Both R2R tests also passed outside the lane (no WasmRunWasmOpt), where the helper asserts nothing was optimized.
    • Evaluating a CoreCLR browser project with the workload marked unavailable: WasmRunWasmOpt=true gives _WasmNativeWorkloadNeeded=true and UsingBrowserRuntimeWorkload=true. Without it, or with UseMonoRuntime=true, both stay off.
    • The installed workload manifest was patched the same way for these runs and restored afterwards.
  • Earlier, after the first rebase onto [browser][coreclr] Support WasmRunWasmOpt in the native relink #136771, ran the local wasm-opt lane: ./dotnet.sh build src/mono/wasm/Wasm.Build.Tests/Wasm.Build.Tests.csproj -c Release -t:Test -nodeReuse:false -p:TargetOS=browser -p:TargetArchitecture=wasm -p:RuntimeFlavor=CoreCLR -p:TestUsingWorkloads=true -p:InstallWorkloadForTesting=false -p:WasmRunWasmOpt=true. It selected 16 tests and 15 passed, including both PublishRunAllPagesWasmOpt cases; their R2R arguments were --enable-exception-handling --enable-reference-types --enable-multivalue --enable-simd --enable-bulk-memory --enable-nontrapping-float-to-int --skip-pass=memory-packing -g -O2. The failure, WasmSIMDTests.PublishRelaxedSimdCoreClr(relaxedSimd: False), fails the same way outside the lane: locally it expects a 12.0.0-dev runtime pack under dotnet-latest/packs, which isn't installed.
    • Both runs went through all pages in Chrome via Playwright. The composite run logged Loaded R2rSuffixLibrary.r2r: 42.
    • The local workload install comes from a feed build, so the modified BrowserWasmApp.CoreCLR.targets, native.wasm.targets and WasmAppBuilder task assemblies were copied over the installed pack for these runs and restored afterwards.
  • Structure checks on every optimized image (35 per-assembly images × several wasm-opt settings, plus the composite):
    • The single active element segment, the table-slot count and the exports are unchanged.
    • Both data segments' contents are unchanged.
    • The payload starts on a 16-byte file boundary.
    • Every image passes wasm-tools validate.
    • wasm-opt may drop unused imports; the host provides a superset of imports, so that's harmless.
  • R2RDump --sc --header passes on every per-assembly image and on the composite.
  • Incremental behavior, per-assembly and composite:
    • WasmRunWasmOpt true → true → false → false → true: optimizes, doesn't rerun, recompiles unoptimized, doesn't rerun, optimizes again.
    • A bogus wasm-opt flag fails the build, leaves the crossgen2 output in place, and the next build retries.
  • In a no-workload ReadyToRun publish with WasmRunWasmOpt=true, the new warning fires.

Open risks

Fixes #134439

Note

This PR description was generated with GitHub Copilot.

@azure-pipelines

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

@lewing lewing added arch-wasm WebAssembly architecture os-browser Browser variant of arch-wasm labels Nov 1, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to 'arch-wasm': @lewing, @pavelsavara
See info in area-owners.md if you want to be subscribed.

@lewing
lewing requested a review from kotlarmilos November 1, 2026 02:52
@lewing

lewing commented Nov 1, 2026

Copy link
Copy Markdown
Member Author

/azp run runtime-coreclr outerloop

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).

@lewing
lewing force-pushed the lewing-r2r-wasm-opt-prototype branch from 0305e97 to 10309c2 Compare November 2, 2026 19:00
@lewing
lewing marked this pull request as ready for review November 3, 2026 15:26
@lewing
lewing force-pushed the lewing-r2r-wasm-opt-prototype branch from 10309c2 to d9f1d95 Compare November 4, 2026 16:56
lewing added a commit to dotnet/sdk that referenced this pull request Nov 6, 2026
CoreCLR browser runs wasm-opt from the workload's Emscripten SDK over the
relinked dotnet.native.wasm and over ReadyToRun images, so WasmRunWasmOpt=true
needs the wasm-tools workload. Port the runtime change from
dotnet/runtime#136772.

Co-authored-by: Copilot App <[email protected]>
@lewing
lewing force-pushed the lewing-r2r-wasm-opt-prototype branch from d9f1d95 to b487e93 Compare November 8, 2026 21:30
Base automatically changed from lewing-coreclr-wasm-run-wasm-opt to main November 10, 2026 09:30
lewing and others added 3 commits November 10, 2026 10:30
Run wasm-opt over the per-app ReadyToRun images (each per-assembly image, or
the composite) after crossgen2 and before webcil staging and fingerprinting,
when WasmRunWasmOpt=true. The option stays opt-in.

- The pass lives in the workload's BrowserWasmApp.CoreCLR.targets, which has
  the Emscripten SDK's wasm-opt. The SDK pack warns when WasmRunWasmOpt is set
  for a ReadyToRun publish without the workload targets.
- Pass the shared @(_WasmOptFeatureFlag) features; crossgen2 images carry no
  target_features section.
- Skip memory-packing so passive data segment 0 (payloadSize/tableSize read by
  AttachWebcilSizes) and the payload segment stay intact.
- Default to -O2, which compresses smaller than -Oz on R2R images; an -O level
  in WasmOptConfigurationFlags wins. Keep the name section only with
  WasmNativeDebugSymbols and without WasmNativeStrip.
- Fold the wasm-opt settings into the R2R state stamp so toggling them
  recompiles, and stamp each optimized image so up-to-date images are not
  optimized twice.
- Add PublishRunAllPagesWasmOpt (per-assembly and composite) to the wasm-opt
  Wasm.Build.Tests lane.

Contributes to #134439

Co-authored-by: Copilot App <[email protected]>
wasm-opt re-encodes ReadyToRun images and moves the Webcil payload off the
16-byte file alignment crossgen2 gives it. R2RDump reads the payload at its
file offset and rejects the NativeCuckooFilter section of an unaligned image.

- Add WebcilWasmPayloadAlignment to Microsoft.NET.WebAssembly.Webcil, which
  re-pads passive data segment 0 so the payload starts aligned again, keeping
  every segment's contents.
- Add the AlignWebcilPayload task and run it on each image after wasm-opt.
- Always pass -g so wasm-opt keeps whatever names crossgen2 emitted; crossgen2's
  wasm debug-info settings decide whether there are any.
- Document why -O2 is the default for R2R images.
- Assert the payload alignment in PublishRunAllPagesWasmOpt.

The padding costs at most 15 bytes per image. Relaxing the file-alignment rule
(#133139) instead would save about 0.003% of image size and has
no runtime effect, because the host aligns the payload in memory.

Co-authored-by: Copilot App <[email protected]>
…ad requirement, lane tests

- Resolve wasm-opt for ReadyToRun images through _CoreCLRResolveWasmOpt, shared
  with the relink, instead of a second lookup.
- Require the browser workload when WasmRunWasmOpt=true for CoreCLR, in the
  workload manifest. Keep the SDK pack warning for builds that still lack the
  workload targets, for example UsingBrowserRuntimeWorkload=false.
- Fold the dedicated ReadyToRun wasm-opt test into the wasm-opt lane:
  AssertReadyToRunWasmOpt checks the optimized images (stamps, payload
  alignment) only when the lane enables WasmRunWasmOpt, and that nothing was
  optimized otherwise. NativeLibraryTests.ProjectWithNativeReference_ReadyToRun
  covers per-assembly images; PublishRunAllPagesCompositeWithWorkload covers
  the composite, since no existing workload-mode test publishes one.

Co-authored-by: Copilot App <[email protected]>
@maraf
maraf force-pushed the lewing-r2r-wasm-opt-prototype branch from b487e93 to 3aa2d02 Compare November 10, 2026 09:31
@lewing
lewing enabled stacked auto-merge (squash) November 10, 2026 17:17
@lewing

lewing commented Nov 10, 2026

Copy link
Copy Markdown
Member Author

/ba-g windows wasm bad exit is known

@lewing
lewing merged commit 228e8fb into main Nov 10, 2026
53 of 55 checks passed
@lewing
lewing deleted the lewing-r2r-wasm-opt-prototype branch November 10, 2026 21:40
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 12.0-preview1 milestone Nov 11, 2026
maraf pushed a commit that referenced this pull request Nov 11, 2026
Removes `extraBuildArgs.Add("-v:diag");` from
`ReadyToRunTests.PublishCrossgen2ArgumentsReflectWasmDebugInfoProperties`.
The theory matrix and assertions are unchanged.

## Why

The Helix work item `WBT-NoWorkload-CLR-Wasm.Build.Tests` on
`windows.server2025.amd64.open` is dead-lettering on main and on PRs.
Examples: main build 1672437, and #136772 builds 1670137 and 1672543.
Each one fails with exit -1 after 0 s and no console log.

- Helix heartbeats show each attempt runs for exactly 90 min, which is
the `_workItemTimeout` of 01:30:00. The machine then reboots and the
item retries on another machine. After 3 attempts it dead-letters.
- The median Windows duration for this work item went from about 55 min
(Nov 3–4) to about 91 min (Nov 5 onward). That change lines up with
#136506 (b0643c8, merged Nov 5). It added 12
`[TestCategory("no-workload")]` cases of this test, and each one
publishes with `-v:diag`.
- In a passing slow run (Helix job
`a5e1304b-0299-470a-a3ce-9a2289a5b925`, from #137223), `testResults.xml`
was **1.47 GB**. In a run from before #136506 (job
`e197dfa2-77e6-46f3-8c6c-b0c6903841b1`) it was **504 KB**. Each of these
cases captured about 120 MB (~1M lines) of diag MSBuild output and took
about 121 s.

The test doesn't need diagnostic verbosity.
`GetCrossgen2ExtraCommandLineArgs(binlogPath)` reads the
`Crossgen2ExtraCommandLineArgs` parameter of the `RunReadyToRunCompiler`
task from the binlog, and the binary logger records task parameters at
any console verbosity.

## Validation

- `./dotnet.sh build
src/mono/wasm/Wasm.Build.Tests/Wasm.Build.Tests.csproj -c Release
-p:TargetOS=browser -p:TargetArchitecture=wasm -p:RuntimeFlavor=CoreCLR
-p:InstallWorkloadForTesting=false`: **passed** (0 warnings, 0 errors).
- Without `-p:InstallWorkloadForTesting=false`, the test assembly still
compiled. The build then failed in the testing-SDK provisioning step
(`workloads-browser.targets(122,5)`), because this worktree has no
locally built runtime packs.
- I did **not** run the test locally, since that needs a full
browser-wasm CoreCLR build. CI coverage of the Windows
`WBT-NoWorkload-CLR` work item is the real check.

> [!NOTE]
> This PR description was generated with GitHub Copilot.

Co-authored-by: Copilot App <[email protected]>
maraf added a commit that referenced this pull request Nov 25, 2026
<!-- -->

## Summary

Add focused WebAssembly review guidance based on recurring PR feedback,
without expanding global repository instructions.

- Put the general guide in the runtime-neutral
`docs/workflow/wasm-review.md`, covering SDK/workload/in-tree ownership,
configuration consumers, native build bridges, incremental outputs and
Static Web Assets.
- Extend the Wasm.Build.Tests README with scenario/output-helper reuse,
category selection, scoped binlog observations and coverage guidance.
- Add a Wasm-scoped instruction router and link the guide from the
existing Wasm documentation index.

Documentation only; no product code, test implementation or public API
changes.

## Independent historical-review validation

Four fresh sessions reviewed two merged PRs: one baseline and one
new-guidance reviewer per PR. Each reviewed the exact source head
attached to the original feedback, not the final merged code. Original
comments, expected findings and counterpart results were withheld from
reviewers; their first-pass responses were saved and hashed before
comparison.

| PR | Frozen pre-feedback head | Baseline agreement | New-guidance
agreement |
| --- | --- | --- | --- |
| [#136971](#136971) |
`1e6c03358c1575baaf29538bf630ab0647a16beb` | 1.5/4 | 4/4 |
| [#136772](#136772) |
`d9f1d954190aa89869e920bbf7b98f9324862240` | 0/3 | 2/3 |
| **Total** | | **1.5/7** | **6/7** |

Scoring criteria were fixed before launch: 1 for a specific actionable
equivalent to the original feedback, 0.5 for an incomplete equivalent,
and 0 for absent or generic advice. These measure feedback agreement,
not production-defect counts. Original feedback was published by the
reviewer's account; some comments explicitly disclose Copilot
assistance.

| Feedback criterion | Baseline | New guidance |
| --- | --- | --- |
| Direct MSBuild Publish default and coverage | 0 | 1 |
| Proper shared testasset/scenario | 0.5 | 1 |
| Standard test-output helper | 0 | 1 |
| CoreCLR runtime category | 1 | 1 |
| Synchronize the equivalent SDK workload-manifest condition | 0 | 0 |
| Share the literal CMake feature baseline | 0 | 1 |
| Respect the separate Mono CMake bridge and runtime-specific policy | 0
| 1 |

The baseline asset recommendation moved the program into a replacement
fixture; the guided recommendation used a shared application scenario,
matching the original follow-up more closely. Both arms missed the SDK
manifest synchronization. The relevant equivalent SDK gate was
subsequently verified in version-pinned source, not by executing the
historical SDK.

Both native reviews also found the supported DLL-named R2R output being
excluded by an extension filter and incomplete all-image stamp
assertions; these common findings are not credited as guidance uplift.
Guided output was not a strict superset: baseline-only advice included
preserving the first build's binlog and adding independent
alignment-rewriter regression tests.

### Limitations

This is a small retrospective comparison on two cases used to derive the
guidance, not a held-out, randomized or causal demonstration of general
improvement. The coordinator knew the treatment arms; inherited
instructions, temporally newer contributor docs, skill availability and
probe use were not fully controlled. Reviewers explicitly consumed the
new Markdown content, so automatic instruction-router activation was not
tested. No full historical SDK/browser/toolchain scenario was
reproduced, and no zero-false-positive rate is claimed.

## Validation

- `git diff --check` — passed.
- `npm exec --yes --package markdownlint-cli -- markdownlint
.github/instructions/wasm.instructions.md docs/workflow/wasm-review.md
src/mono/wasm/Wasm.Build.Tests/README.md
docs/workflow/wasm-documentation.md` — passed with repository
configuration.
- Session-local documentation validator — passed 18 relative link/anchor
checks, 14 existing positive and 8 negative routing examples,
frontmatter, final newlines and trailing whitespace. This checks the
explicit globs, not live Copilot routing.
- Runtime builds/browser tests were not run for these Markdown-only
changes. One baseline historical reviewer ran isolated MSBuild selection
and synthetic alignment probes using a newer host SDK; those are not
full historical-toolchain validation.

> [!NOTE]
> This PR description was generated with the assistance of GitHub
Copilot.

---------

Co-authored-by: Copilot App <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

arch-wasm WebAssembly architecture area-Build-mono os-browser Browser variant of arch-wasm

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[browser][R2R] use wasm-opt to optimize size of webCIL

2 participants