From dd37830a19de06c22e058181f0130227d121172c Mon Sep 17 00:00:00 2001 From: "shaoding.zw" Date: Thu, 26 Nov 2026 03:35:47 +0000 Subject: [PATCH 1/3] perf(compiler): compile small WASI entries on demand --- .../README.md | 16 ++++++++++ docs/modules/compiler/spec.md | 9 ++++++ src/compiler/compiler.cpp | 30 +++++++++++++++---- src/compiler/compiler.h | 3 ++ src/tests/CMakeLists.txt | 9 ++++++ src/tests/lazy_jit_greedy_ondemand_tests.cpp | 30 +++++++++++++++++++ tests/wast/multipass/lazy_wasi_entry.wast | 20 +++++++++++++ 7 files changed, 111 insertions(+), 6 deletions(-) create mode 100644 docs/changes/2026-11-26-lazy-wasi-entry-on-demand/README.md create mode 100644 tests/wast/multipass/lazy_wasi_entry.wast diff --git a/docs/changes/2026-11-26-lazy-wasi-entry-on-demand/README.md b/docs/changes/2026-11-26-lazy-wasi-entry-on-demand/README.md new file mode 100644 index 000000000..fbde2b119 --- /dev/null +++ b/docs/changes/2026-11-26-lazy-wasi-entry-on-demand/README.md @@ -0,0 +1,16 @@ +# Compile small WASI entries on demand in Lazy Multipass + +- **Status**: Proposed +- **Date**: 2026-11-26 +- **Tier**: Light + +Background compilation can start building a WASI entry just before its first +foreground call. This can compile the same small function twice during CLI +startup. In a module with one internal function export and no WebAssembly +start section, defer `_start` with the WASI signature and a body +of at most 512 bytes to the foreground. + +Use the configured allocator for the entry and publish through the same path +as serial lazy. Private promotion remains available to eligible callees. +Other entry scheduling follows the +[compiler specification](../../modules/compiler/spec.md). diff --git a/docs/modules/compiler/spec.md b/docs/modules/compiler/spec.md index a9910799e..ac928ff95 100644 --- a/docs/modules/compiler/spec.md +++ b/docs/modules/compiler/spec.md @@ -236,6 +236,15 @@ loading, guest execution and background compilation; admitted/concurrent work can overrun. It is not a first-call deadline. Unlimited mode reads no budget clock. Eager, serial, one-function and background configured choices are exempt. +### On-demand WASI entry + +Lazy Multipass normally queues the module start function and exported +functions for background compilation. If there is no module start function +and the sole internal function export is `_start` with signature +`() -> ()`, a body of at most 512 bytes compiles on demand with the +configured allocator. Its stub publishes directly through the serial lazy +path. The thread pool remains available for opt-in private promotion. + ### Opt-in private loop tiering `EnableLazyPrivateTiering` permits demand-compiled private WASM helpers to diff --git a/src/compiler/compiler.cpp b/src/compiler/compiler.cpp index 814e21f55..796603564 100644 --- a/src/compiler/compiler.cpp +++ b/src/compiler/compiler.cpp @@ -762,6 +762,23 @@ void LazyJITCompiler::dispatchEntryCompileTasks(WasmFrontendContext &Ctx) { } } +uint32_t LazyJITCompiler::findDeferredWasiEntry() const { + if (WasmMod->getStartFuncIdx() != -1u || + WasmMod->getExportedFuncIdxs().size() != 1) + return -1u; + + uint32_t Entry; + if (!WasmMod->getExportFunc("_start", Entry)) + return -1u; + const auto *Code = WasmMod->getCodeEntry(Entry); + const auto *Type = WasmMod->getFunctionType(Entry); + constexpr uint32_t MaxDeferredEntryBytes = 512; + if (!Code || Code->CodeSize > MaxDeferredEntryBytes || Type->NumParams || + Type->NumReturns) + return -1u; + return Entry - WasmMod->getNumImportFunctions(); +} + void LazyJITCompiler::precompile() { LazyInitialRAPolicy::Timer BudgetTimer(InitialRAPolicy, true); auto Timer = @@ -774,8 +791,10 @@ void LazyJITCompiler::precompile() { } StubBuilder.finalizeStubs(); if (ThreadPool) { - ThreadPool->pushTask( - [this](WasmFrontendContext *Ctx) { dispatchEntryCompileTasks(*Ctx); }); + DeferredWasiEntry = findDeferredWasiEntry(); + if (DeferredWasiEntry == -1u) + ThreadPool->pushTask( + [this](WasmFrontendContext *Ctx) { dispatchEntryCompileTasks(*Ctx); }); } uint32_t NumImportFunctions = WasmMod->getNumImportFunctions(); for (uint32_t I = 0; I < NumInternalFunctions; ++I) { @@ -856,10 +875,9 @@ uint8_t *LazyJITCompiler::compileFunctionOnRequest(uint8_t *FuncStubCodePtr) { ForegroundGuard = std::unique_lock(ForegroundMutex); if (PrivateFunctions && PrivateFunctions[FuncIdx].OriginalFast) return handlePrivateEntry(FuncIdx); - if (!ThreadPool) { - // Single-thread lazy, or single-internal-function modules (no FastRA - // FG / Greedy BG split). Configured allocator on-demand (Greedy unless - // DisableMultipassGreedyRA); unconditional stub publish. + if (!ThreadPool || FuncIdx == DeferredWasiEntry) { + // A deferred entry has no background compiler. Use the configured + // allocator on demand and publish directly, as in serial lazy. // Attempt/start count: entered the no-pool on-request compile path. ForegroundCompileCount.fetch_add(1, std::memory_order_relaxed); auto Timer = Stats.startRecord(utils::StatisticPhase::JITLazyFgCompilation); diff --git a/src/compiler/compiler.h b/src/compiler/compiler.h index 32073510a..bd1199546 100644 --- a/src/compiler/compiler.h +++ b/src/compiler/compiler.h @@ -143,6 +143,8 @@ class LazyJITCompiler final : public WasmJITCompiler { uint64_t getObservedLoopHeat(uint32_t FuncIdx) const; private: + uint32_t findDeferredWasiEntry() const; + enum class CompileStatus : uint8_t { None, Pending, @@ -210,6 +212,7 @@ class LazyJITCompiler final : public WasmJITCompiler { // workloads (a large one-fn module can still theoretically benefit from // FastRA-first tiering). std::vector AuxContexts; + uint32_t DeferredWasiEntry = -1u; // must be declared before ThreadPool std::unique_ptr[]> CompileStatuses; // must be declared before ThreadPool diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index ef78e3e76..e87aed008 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -597,11 +597,20 @@ if(ZEN_ENABLE_SPEC_TEST) add_custom_target(lazy_entry_seeds_wasm DEPENDS ${LAZY_ENTRY_SEEDS_WASM}) add_dependencies(lazyJitGreedyOndemandTests fib_iter_lazy_wasm) add_dependencies(lazyJitGreedyOndemandTests lazy_entry_seeds_wasm) + set(LAZY_WASI_ENTRY_SPEC_DIR + "${CMAKE_BINARY_DIR}/wast/multipass/lazy_wasi_entry" + ) + add_custom_target( + lazy_wasi_entry_wasm + DEPENDS "${LAZY_WASI_ENTRY_SPEC_DIR}/lazy_wasi_entry.json" + ) + add_dependencies(lazyJitGreedyOndemandTests lazy_wasi_entry_wasm) target_compile_definitions( lazyJitGreedyOndemandTests PRIVATE FIB_ITER_ONEFN_WASM_PATH="${FIB_ITER_ONEFN_WASM}" FIB_ITER_TWOFN_WASM_PATH="${FIB_ITER_TWOFN_WASM}" LAZY_ENTRY_SEEDS_WASM_PATH="${LAZY_ENTRY_SEEDS_WASM}" + LAZY_WASI_ENTRY_SPEC_DIR="${LAZY_WASI_ENTRY_SPEC_DIR}" ) if(ZEN_TEST_ENABLE_ASAN) target_compile_options( diff --git a/src/tests/lazy_jit_greedy_ondemand_tests.cpp b/src/tests/lazy_jit_greedy_ondemand_tests.cpp index 18c1fcff5..a376915fe 100644 --- a/src/tests/lazy_jit_greedy_ondemand_tests.cpp +++ b/src/tests/lazy_jit_greedy_ondemand_tests.cpp @@ -238,6 +238,36 @@ CompiledFib compileAndRunOneFn(bool Lazy, bool DisableGreedyRA, } // namespace +TEST(LazyJitGreedyOndemand, SmallWasiEntryCompilesOnDemand) { + for (const char *Path : { + LAZY_WASI_ENTRY_SPEC_DIR "/lazy_wasi_entry.0.wasm", + LAZY_WASI_ENTRY_SPEC_DIR "/lazy_wasi_entry.1.wasm", + }) { + auto LM = loadModule(loadWasmFile(Path), "wasi-entry", true, false, false); + ASSERT_TRUE(LM.Lazy->hasBackgroundCompilePool()); + ASSERT_TRUE(stubIsTrampoline(*LM.Mod, 1)); + std::vector Results; + ASSERT_TRUE(LM.RT->callWasmFunction(*LM.Inst, "_start", {}, Results)); + EXPECT_TRUE(Results.empty()); + const uint32_t Compiles = LM.Lazy->getForegroundCompileCount(); + EXPECT_GT(Compiles, 0u); + EXPECT_EQ(LM.Lazy->getBackgroundCompileCount(), 0u); + ASSERT_TRUE(LM.RT->callWasmFunction(*LM.Inst, "_start", {}, Results)); + EXPECT_EQ(LM.Lazy->getForegroundCompileCount(), Compiles); + } +} + +TEST(LazyJitGreedyOndemand, KeepsPrewarmForOtherStartFunctions) { + for (const char *Path : { + LAZY_WASI_ENTRY_SPEC_DIR "/lazy_wasi_entry.2.wasm", + LAZY_WASI_ENTRY_SPEC_DIR "/lazy_wasi_entry.3.wasm", + }) { + auto LM = loadModule(loadWasmFile(Path), "prewarmed-entry", true, false, + false, /*Instantiate=*/false); + ASSERT_TRUE(waitForBackgroundPublishes(*LM.Lazy, 1, 5000)) << Path; + } +} + TEST(LazyJitGreedyOndemand, FastRASpillsMoreThanGreedyOnFibLoop) { CompiledFib Fast = compileAndRunOneFn(/*Lazy=*/false, /*DisableGreedyRA=*/true, diff --git a/tests/wast/multipass/lazy_wasi_entry.wast b/tests/wast/multipass/lazy_wasi_entry.wast new file mode 100644 index 000000000..2dfd4d5cb --- /dev/null +++ b/tests/wast/multipass/lazy_wasi_entry.wast @@ -0,0 +1,20 @@ +(module + (func $helper (result i32) i32.const 7) + (func (export "_start") (call $helper) drop)) +(assert_return (invoke "_start")) + +(module + (func) + (func (export "_start") (loop nop))) +(assert_return (invoke "_start")) + +(module + (func $init) + (start $init) + (func (export "_start"))) +(assert_return (invoke "_start")) + +(module + (func) + (func (export "_start") (result i32) i32.const 7)) +(assert_return (invoke "_start") (i32.const 7)) From 257218be9d7405bfb1644766f71793b21b253338 Mon Sep 17 00:00:00 2001 From: "shaoding.zw" Date: Thu, 26 Nov 2026 03:52:02 +0000 Subject: [PATCH 2/3] docs(compiler): record lazy WASI entry benchmarks --- .../BENCHMARK.md | 210 ++++++++++++++++++ .../README.md | 3 + .../benchmark.py | 129 +++++++++++ 3 files changed, 342 insertions(+) create mode 100644 docs/changes/2026-11-26-lazy-wasi-entry-on-demand/BENCHMARK.md create mode 100644 docs/changes/2026-11-26-lazy-wasi-entry-on-demand/benchmark.py diff --git a/docs/changes/2026-11-26-lazy-wasi-entry-on-demand/BENCHMARK.md b/docs/changes/2026-11-26-lazy-wasi-entry-on-demand/BENCHMARK.md new file mode 100644 index 000000000..a322c8857 --- /dev/null +++ b/docs/changes/2026-11-26-lazy-wasi-entry-on-demand/BENCHMARK.md @@ -0,0 +1,210 @@ +# WASI entry scheduling benchmark + +The Wasm runtime baseline is upstream `5c93255` (#663). The branch +was rebased over `6afa74f` (#651), which changes EVM source and docs. +EVM was disabled in the timing build. DTVM was built in Release with GCC +14.2 and LLVM 15.0.6 on AMD EPYC 9V74. The comparator binaries are the +official Linux x86-64 Wasmtime 45.0.0 and 51.0.0 builds. The timed +candidate predates the rebase and the declaration's access-control and +comment edits. Its executable compiler changes match the branch. + +Each case uses the original paper Wasm and catalog inputs. CLI process wall +time includes startup, compilation, execution and shutdown. One warmup per +engine is discarded. Each round shuffles variant order. A one-core affinity +mask is used unless the cohort specifies two cores. The compilation cache is +disabled. Wasmtime 51 enables Preview 0 for modules that import `wasi_unstable`. +Every timed process checks guest stdout, stderr and exit status. + +Times are per-variant medians in milliseconds. Changes are medians of +paired ratios with pointwise bootstrap 95% intervals. A/A compares two +labels of the same baseline executable in each round. Three-round +controls are regression screens with limited precision. + +The paper inputs for `code-stock` and `ludcmp` each export three internal +functions, so their entries still follow the background compilation path. +The `dice` and `tpl` entries exceed the size cutoff. + + +## Lazy confirmation + +41 measured rounds per case. + +| Case | DTVM main | Candidate | 45 Cranelift | 45 Winch | 51 Cranelift | Candidate change | Main A/A | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| md5 | 21.01 | 19.70 | 37.36 | 10.99 | 39.63 | -7.30% [-8.47%, -6.35%] | +1.09% [-0.18%, +3.25%] | +| echo | 20.39 | 18.71 | 33.37 | 10.59 | 34.47 | -8.62% [-10.59%, -6.79%] | +1.51% [-1.18%, +2.94%] | +| figlet | 39.18 | 37.86 | 96.58 | 20.41 | 101.19 | -4.23% [-5.22%, -3.08%] | -0.51% [-1.35%, +1.28%] | +| qr2text | 41.40 | 40.54 | 114.06 | 31.15 | 120.44 | -0.51% [-1.62%, +0.59%] | -0.51% [-1.36%, +1.50%] | +| base64cli | 88.48 | 87.90 | 444.33 | 87.64 | 463.60 | -0.76% [-1.43%, +0.48%] | -0.49% [-1.15%, +0.07%] | +| bicg | 55.05 | 53.83 | 67.04 | 58.58 | 66.83 | -2.31% [-3.95%, -1.72%] | -1.19% [-2.05%, +2.75%] | +| atax | 46.63 | 46.06 | 57.89 | 60.71 | 58.46 | -1.69% [-3.44%, -0.71%] | +0.61% [-0.82%, +1.13%] | + +## Lazy WAPM controls + +9 measured rounds per case. + +| Case | DTVM main | Candidate | 45 Cranelift | 45 Winch | 51 Cranelift | Candidate change | Main A/A | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| chkfont | 33.61 | 32.02 | 72.28 | 16.68 | 74.04 | -2.98% [-59.51%, +1.61%] | -1.12% [-44.10%, +7.32%] | +| code-stock | 18.64 | 19.37 | 81.13 | 26.30 | 85.28 | +1.41% [-3.46%, +7.29%] | -4.21% [-5.29%, +0.43%] | +| cowsay | 94.62 | 95.28 | 376.05 | 79.20 | 402.54 | -0.09% [-1.52%, +1.93%] | +1.55% [-0.38%, +3.01%] | +| dice | 16.44 | 16.37 | 32.14 | 11.87 | 33.64 | -1.15% [-3.02%, +1.66%] | -0.71% [-9.42%, +4.31%] | +| suggest | 78.30 | 73.48 | 388.21 | 75.43 | 412.12 | -0.91% [-11.72%, +1.44%] | -1.10% [-9.96%, -0.31%] | +| pi | 20.83 | 19.58 | 36.58 | 10.82 | 37.06 | -6.41% [-8.85%, +0.55%] | -0.18% [-1.25%, +3.13%] | +| tpl | 227.90 | 220.34 | 730.90 | 243.80 | 771.28 | -1.37% [-7.74%, +0.07%] | +1.57% [-6.50%, +19.95%] | +| viu | 182.82 | 182.25 | 1231.60 | 215.32 | 1216.84 | -0.32% [-24.14%, +1.05%] | +0.21% [-23.43%, +3.36%] | + +## Lazy PolyBench controls + +3 measured rounds per case. + +| Case | DTVM main | Candidate | 45 Cranelift | 45 Winch | 51 Cranelift | Candidate change | Main A/A | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| syr2k | 3413.03 | 3206.04 | 4176.87 | 6563.66 | 4360.78 | -3.57% [-7.60%, -1.62%] | -1.22% [-6.16%, -0.70%] | +| 3mm | 3836.30 | 3648.64 | 4231.89 | 12522.16 | 4249.68 | -4.01% [-4.89%, -3.47%] | -2.03% [-3.84%, +0.89%] | + +## Lazy ludcmp control + +3 measured rounds per case. + +| Case | DTVM main | Candidate | 45 Cranelift | 45 Winch | 51 Cranelift | Candidate change | Main A/A | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| ludcmp | 11589.88 | 12085.61 | 12036.93 | 29682.84 | 11633.29 | +1.67% [-0.26%, +5.40%] | +0.08% [-3.72%, +3.00%] | + +## Singlepass controls + +9 measured rounds per case. + +| Case | DTVM main | Candidate | 45 Cranelift | 45 Winch | 51 Cranelift | Candidate change | Main A/A | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| md5 | 5.72 | 6.28 | 38.85 | 11.99 | 39.78 | +5.13% [-20.67%, +17.32%] | -6.66% [-17.81%, +22.10%] | +| echo | 6.08 | 6.07 | 34.82 | 10.82 | 35.91 | -1.70% [-5.21%, +319.54%] | -0.38% [-25.03%, +28.47%] | +| bicg | 79.18 | 76.40 | 68.90 | 61.68 | 69.97 | -3.59% [-8.24%, -0.28%] | -0.95% [-2.61%, +2.72%] | +| atax | 79.68 | 79.09 | 58.11 | 59.60 | 59.87 | -1.36% [-2.01%, +1.29%] | +0.38% [-2.82%, +9.25%] | + +## Serial Lazy FastRA controls + +9 measured rounds per case. + +| Case | DTVM main | Candidate | 45 Cranelift | 45 Winch | 51 Cranelift | Candidate change | Main A/A | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| md5 | 20.27 | 19.03 | 37.76 | 11.09 | 39.42 | -6.52% [-8.54%, -0.51%] | +0.54% [-5.55%, +3.63%] | +| echo | 19.13 | 19.00 | 33.58 | 10.64 | 34.83 | -2.15% [-8.21%, +2.88%] | +5.48% [-5.22%, +7.92%] | +| bicg | 54.93 | 54.89 | 67.55 | 58.77 | 70.10 | +2.50% [-1.56%, +6.65%] | -0.91% [-4.30%, +6.35%] | +| atax | 60.74 | 57.10 | 59.62 | 61.90 | 60.19 | -4.80% [-27.10%, +1.44%] | -4.50% [-22.57%, +0.70%] | + +## Eager Multipass controls + +9 measured rounds per case. + +| Case | DTVM main | Candidate | 45 Cranelift | 45 Winch | 51 Cranelift | Candidate change | Main A/A | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| md5 | 94.21 | 94.06 | 37.92 | 11.39 | 40.02 | -0.71% [-3.23%, +0.64%] | +1.55% [-1.96%, +12.93%] | +| echo | 85.17 | 85.14 | 34.42 | 10.83 | 34.95 | +1.39% [-5.43%, +7.40%] | -1.76% [-4.21%, +1.58%] | +| bicg | 118.88 | 122.22 | 67.18 | 58.16 | 68.48 | -0.37% [-2.04%, +5.92%] | -0.78% [-3.27%, +1.16%] | +| atax | 106.69 | 107.17 | 57.55 | 59.21 | 57.70 | -1.42% [-19.68%, +2.44%] | +0.05% [-12.60%, +5.87%] | + +## Lazy WAPM repeat + +41 measured rounds per case. + +| Case | DTVM main | Candidate | 45 Cranelift | 45 Winch | 51 Cranelift | Candidate change | Main A/A | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| code-stock | 17.70 | 17.73 | 80.00 | 25.45 | 83.60 | +0.96% [-2.31%, +3.22%] | -0.53% [-1.47%, +2.55%] | + +## Serial Lazy FastRA repeat + +31 measured rounds per case. + +| Case | DTVM main | Candidate | 45 Cranelift | 45 Winch | 51 Cranelift | Candidate change | Main A/A | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| md5 | 18.87 | 18.68 | 36.48 | 10.50 | 37.95 | -1.28% [-3.37%, +1.54%] | -0.81% [-3.25%, +1.83%] | +| bicg | 54.84 | 53.38 | 67.51 | 58.77 | 67.03 | -1.05% [-2.09%, +0.57%] | -0.90% [-1.75%, -0.14%] | + +## Lazy ludcmp repeat + +5 measured rounds per case. + +| Case | DTVM main | Candidate | 45 Cranelift | 45 Winch | 51 Cranelift | Candidate change | Main A/A | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| ludcmp | 11026.54 | 11041.74 | 11259.35 | 28654.55 | 11121.65 | -0.08% [-1.46%, +2.60%] | +1.08% [-3.78%, +3.99%] | + +## Lazy confirmation with two-core affinity + +41 measured rounds per case. + +| Case | DTVM main | Candidate | 45 Cranelift | 45 Winch | 51 Cranelift | Candidate change | Main A/A | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| md5 | 19.84 | 19.81 | 24.60 | 7.75 | 24.46 | +1.16% [-0.66%, +3.12%] | -0.46% [-3.71%, +1.07%] | +| echo | 19.04 | 18.66 | 22.54 | 7.32 | 23.41 | -1.92% [-6.65%, -0.31%] | +0.37% [-0.84%, +2.72%] | +| figlet | 38.82 | 38.61 | 52.82 | 13.64 | 55.93 | +0.10% [-2.34%, +1.15%] | -0.33% [-0.76%, +0.55%] | + +The one-core measurements confirm a startup improvement for `md5`, `echo` +and `figlet`. With two cores, `echo` shows a smaller improvement and the +intervals for `md5` and `figlet` cross zero. Winch remains faster on all three. +The repeat intervals for `code-stock`, `ludcmp` and the serial Lazy FastRA +cases cross zero. The large PolyBench controls have too few rounds to +establish a kernel speedup. + + +## Separate compiler statistics + +Eleven randomized pairs with `--enable-statistics`. Foreground and background +timers can overlap. These clocks are collected separately from process wall time. + +| Case | Foreground compiles | Background compiles | Foreground compile ms | Background compile ms | +| --- | ---: | ---: | ---: | ---: | +| md5 | 31 → 31 | 1 → 0 | 15.756 → 14.711 | 1.433 → 0.000 | +| echo | 30 → 30 | 1 → 0 | 14.774 → 13.812 | 1.426 → 0.000 | +| figlet | 113 → 113 | 1 → 0 | 31.443 → 30.771 | 0.681 → 0.000 | +| bicg | 35 → 35 | 1 → 0 | 18.006 → 17.142 | 0.771 → 0.000 | +| atax | 35 → 35 | 1 → 0 | 17.930 → 17.206 | 0.765 → 0.000 | + +With two cores, the background compile count also fell from one to zero +for these five inputs. Foreground compile time rose by 0.529 ms for `md5` +and 0.317 ms for `echo`. Background work can overlap with the foreground on +two cores, which limits the wall-time benefit of removing the duplicate work. + +The prototype skipped the entry queue while retaining the default foreground +choice. It improved `md5` by 7.00% and `echo` by 8.17% in a 31-round pilot. +An independently tested ELF symbol-scan bypass did not show this gain. +The release implementation uses the configured allocator for the deferred +entry, preserving the existing Greedy code generation for its argument loops. + +## Code generation experiments + +Combining 32-bit address addition through `lea` with spill-reload sinking +reduced the native BiCG loop from 22 instructions to 19 and SYR2K from 23 +to 20. Their Wasmtime 51 Cranelift equivalents contain 21 and 19 +instructions. The paired SYR2K process change was -1.45% [-6.23%, +2.88%]. +Adding VEX scalar load folding to the two changes improved the derived +ATAX warm kernel by 8.48% [7.12%, 10.87%]. The same experimental arm +increased matched CLI process time for `md5` by 2.05% and `echo` by 2.98%. +The branch contains the entry scheduling optimization. + +## Correctness + +All seven local Release CTest targets passed. The new entry fixture also +passed separately in interpreter, Singlepass, Eager Multipass and Lazy +Multipass. The lazy JIT unit tests check first-use compilation, subsequent +stub calls, and continued prewarming for a module-start function and for +`_start` with a different signature. + +## Reproduction + +From the repository root, use matching DTVM Release builds and the pinned +Wasmtime binaries. + +```bash +python3 docs/changes/2026-11-26-lazy-wasi-entry-on-demand/benchmark.py \ + --variant main=/path/to/main-dtvm --variant final=/path/to/candidate-dtvm \ + --wasmtime45 /path/to/wasmtime45 --wasmtime51 /path/to/wasmtime51 \ + --cpu 0 --rounds 41 --seed 6632611 \ + --cases md5,echo,figlet,qr2text,base64cli,bicg,atax --out /tmp/wasi-entry-confirm +``` + +Run the three startup cases with `--cpu-set 0,1` in place of `--cpu 0` +and seed `6632643` to repeat the two-core sample. + +The experiment archive `lazy-wasi-entry-evidence.tar.gz` contains +commands, hashes, paired samples, native excerpts and compiler counters. diff --git a/docs/changes/2026-11-26-lazy-wasi-entry-on-demand/README.md b/docs/changes/2026-11-26-lazy-wasi-entry-on-demand/README.md index fbde2b119..5b819c31b 100644 --- a/docs/changes/2026-11-26-lazy-wasi-entry-on-demand/README.md +++ b/docs/changes/2026-11-26-lazy-wasi-entry-on-demand/README.md @@ -14,3 +14,6 @@ Use the configured allocator for the entry and publish through the same path as serial lazy. Private promotion remains available to eligible callees. Other entry scheduling follows the [compiler specification](../../modules/compiler/spec.md). + +The [benchmark report](BENCHMARK.md) records matched timings, compiler +counters, code-generation experiments, and correctness checks. diff --git a/docs/changes/2026-11-26-lazy-wasi-entry-on-demand/benchmark.py b/docs/changes/2026-11-26-lazy-wasi-entry-on-demand/benchmark.py new file mode 100644 index 000000000..ec7cdc92b --- /dev/null +++ b/docs/changes/2026-11-26-lazy-wasi-entry-on-demand/benchmark.py @@ -0,0 +1,129 @@ +"""Paired process benchmarking of DTVM variants and three Wasmtime baselines.""" +import argparse +import gzip +import hashlib +import json +import os +from pathlib import Path +import random +import statistics +import struct +import subprocess +import sys +import time + +sys.path.insert(0, "benchmarks/paper/harness") +import run as harness + +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument("--variant", action="append", required=True, metavar="NAME=BINARY") +parser.add_argument("--wasmtime45", type=Path, required=True) +parser.add_argument("--wasmtime51", type=Path, required=True) +parser.add_argument("--cases", required=True) +parser.add_argument("--mode", default="lazy-G-MT") +parser.add_argument("--rounds", type=int, required=True) +parser.add_argument("--seed", type=int, required=True) +parser.add_argument("--out", type=Path, required=True) +affinity = parser.add_mutually_exclusive_group() +affinity.add_argument("--cpu", type=int, default=0) +affinity.add_argument("--cpu-set", type=lambda value: [int(cpu) for cpu in value.split(",")]) +parser.add_argument("--phase-inputs", type=Path) +args = parser.parse_args() +binaries = {label: Path(path).resolve() for label, path in + (variant.split("=", 1) for variant in args.variant)} +assert "main" in binaries and "aa" not in binaries +binaries["aa"] = binaries["main"] +peers = {"wt45-c": args.wasmtime45.resolve(), "wt45-winch": args.wasmtime45.resolve(), + "wt51-c": args.wasmtime51.resolve()} +os.sched_setaffinity(0, set(args.cpu_set or [args.cpu])) +args.out.mkdir(parents=True) +env = {**os.environ, "LC_ALL": "C", "WASMTIME_CACHE": "0"} +catalog = {c["id"]: c for c in harness.load_cases(harness.read_json(harness.CATALOG_PATH))} +rng = random.Random(args.seed) +manifest = dict(cpu=args.cpu, seed=args.seed, rounds=args.rounds, warmups=1, + wt_cache="disabled", mode=args.mode, cases={}, + binary_sha256={k: hashlib.sha256(v.read_bytes()).hexdigest() + for k, v in {**binaries, **peers}.items()}) +if args.cpu_set: + manifest["cpu_set"] = args.cpu_set + +def paired(samples, baseline): + ratios = [100 * (x / y - 1) for x, y in zip(samples, baseline)] + rs = random.Random(args.seed) + boot = sorted(statistics.median(rs.choices(ratios, k=len(ratios))) for _ in range(10000)) + return [statistics.median(ratios), boot[250], boot[9750]] + +summary = {} +phase_inputs = json.loads(args.phase_inputs.read_text()) if args.phase_inputs else None +with gzip.open(args.out / "samples.jsonl.gz", "wt", encoding="utf-8") as output: + for name in args.cases.split(","): + case = dict(catalog[name]) + if phase_inputs: + phase = phase_inputs[name + ":8"] + case["wasm"] = phase["wasm"] + wasm = harness.paper_join(case["wasm"]) + contents = wasm.read_bytes() + assert contents[:4] == b"\0asm", wasm + commands = {k: harness.dtvm_cmd(v, case, args.mode, False) + for k, v in binaries.items()} + for label, binary in peers.items(): + cmd = harness.wasmtime_cmd(binary, case) + if label == "wt45-winch": + cmd[2:2] = ["-C", "compiler=winch"] + if label == "wt51-c" and b"wasi_unstable" in contents: + cmd[2:2] = ["-S", "preview0=y"] + commands[label] = cmd + cwd = harness.case_cwd(case) + stdin = (case.get("stdin") or "").encode() + manifest["cases"][name] = dict(input_sha256=hashlib.sha256(contents).hexdigest(), + cwd=str(cwd), stdin=case.get("stdin"), commands=commands) + (args.out / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n") + timings = {k: [] for k in commands} + kernel_timings = {k: [] for k in commands} + first = None + for round_id in range(-1, args.rounds): + order = list(commands) + rng.shuffle(order) + for label in order: + start = time.perf_counter_ns() + result = subprocess.run(commands[label], cwd=cwd, input=stdin, env=env, + capture_output=True, timeout=600) + ms = (time.perf_counter_ns() - start) / 1e6 + pair = (hashlib.sha256(result.stdout).hexdigest(), + hashlib.sha256(result.stderr).hexdigest()) + kernel = None + if phase_inputs: + assert len(result.stdout) == 8 * 56, (name, label, result.returncode) + stamps = list(struct.iter_unpack("<7Q", result.stdout)) + assert all(tuple(sorted(packet)) == packet for packet in stamps) + kernel = statistics.median((packet[5] - packet[4]) / 1e6 + for packet in stamps[1:]) + pair = (None, pair[1]) + row = dict(case=name, round=round_id, variant=label, wall_ms=ms, + exit=result.returncode, stdout_sha256=pair[0], stderr_sha256=pair[1]) + if kernel is not None: + row["warm_kernel_ms"] = kernel + output.write(json.dumps(row) + "\n") + output.flush() + if first is None: + first = pair + if result.returncode or pair != first: + (args.out / f"{name}.{label}.stdout").write_bytes(result.stdout) + (args.out / f"{name}.{label}.stderr").write_bytes(result.stderr) + raise RuntimeError((name, label, row, first)) + if round_id >= 0: + timings[label].append(ms) + if kernel is not None: + kernel_timings[label].append(kernel) + summary[name] = dict( + median_ms={k: statistics.median(v) for k, v in timings.items()}, + vs_main_pct={k: paired(v, timings["main"]) for k, v in timings.items() if k != "main"}, + ) + if phase_inputs: + summary[name]["warm_kernel_ms"] = {k: statistics.median(v) + for k, v in kernel_timings.items()} + summary[name]["warm_kernel_vs_main_pct"] = { + k: paired(v, kernel_timings["main"]) for k, v in kernel_timings.items() if k != "main" + } + print(name, json.dumps(summary[name], sort_keys=True), flush=True) + (args.out / "summary.json").write_text(json.dumps(summary, indent=2) + "\n") From b83768dc5d6111b3248d6dbebf632498230b2156 Mon Sep 17 00:00:00 2001 From: "shaoding.zw" Date: Thu, 26 Nov 2026 08:43:56 +0000 Subject: [PATCH 3/3] style(compiler): format lazy entry task submission --- src/compiler/compiler.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/compiler/compiler.cpp b/src/compiler/compiler.cpp index 796603564..214415534 100644 --- a/src/compiler/compiler.cpp +++ b/src/compiler/compiler.cpp @@ -793,8 +793,9 @@ void LazyJITCompiler::precompile() { if (ThreadPool) { DeferredWasiEntry = findDeferredWasiEntry(); if (DeferredWasiEntry == -1u) - ThreadPool->pushTask( - [this](WasmFrontendContext *Ctx) { dispatchEntryCompileTasks(*Ctx); }); + ThreadPool->pushTask([this](WasmFrontendContext *Ctx) { + dispatchEntryCompileTasks(*Ctx); + }); } uint32_t NumImportFunctions = WasmMod->getNumImportFunctions(); for (uint32_t I = 0; I < NumInternalFunctions; ++I) {