Skip to content

ariadne_wasm: the gas pass, weighted counters natively and in the browser (G2, second part) - #1206

Merged
transfix merged 13 commits into
masterfrom
feat/wasm-weighted-gas
Nov 14, 2026
Merged

transfix merged 13 commits into
masterfrom
feat/wasm-weighted-gas

Conversation

@transfix

@transfix transfix commented Nov 13, 2026 •

Copy link
Copy Markdown
Owner

Builds on #1197 (G2's first part), and now targets master. Until #1197 merges, this diff includes its commits. #1197 merges first (its squash auto-merge is armed), and this one's squash then carries only G2's second part. Everything below was checked on sandipaws, on this branch with #1197's latest head (master with #1178 and #1199) merged in.

What it adds

G2's second part, the "weighted counters" that #1197 left for later (ARIADNE_SCRIPTING_HOSTS.md §8.5, "Gas"). A guest's work now counts the same on wasmtime and in the browser, and however a call is sliced.

  • The gas pass (meter.h, meter.cpp), in C++ in libcvc.
    • What it adds to a module. Each metered block's cost is charged up front against an exported mutable i64 global, ari_gas. The charge is inline: the guest calls the host, ari.gas(cost), only when the slice can't pay for the block.
    • Where a block starts: at a function's entry, and after each loop, if, else, end and conditional branch.
    • What an instruction costs: what wasmtime's fuel charges for it. That's nothing for nop, drop, block, loop, unreachable, return, else and end, and 1 for everything else.
    • Index shifts. The new import shifts every defined function's index, and the pass rewrites calls, ref.func, element segments, table and global initialisers, exports, the start function and the name section to match.
    • Start function. ari_gas starts at the start function's allowance (100 million), so no runtime has to reach the global before the instance exists.
    • What it refuses: GC types and instructions, the legacy exception handling, components, and code that names a global index the pass's own would take. A module that imports ari.gas already is left as it is.
    • Why not the Rust crates the roadmap named. It's C++ rather than paritytech/wasm-instrument. That crate and its parser, parity-wasm, haven't changed since 2022, and parity-wasm doesn't read the reference-types proposal, which LLVM 19 turns on by default for wasm32 (clang 19, rustc 1.82). So nothing needs Rust.
  • ari_wasm_meter (meter_main.cpp) is the pass as a command. Natively it's a host program; under Emscripten it runs in node (NODERAWFS), through the toolchain's emulator.
  • The transform (cvc_ariadne_wasm_transform) runs three commands in place of --log-execution:
    1. binaryen reads the guest;
    2. ari_wasm_meter meters it;
    3. wasm-opt --asyncify --pass-arg=asyncify-imports@ari.* -O1 makes every ari import, ari.gas among them, a point the guest can pause at.
  • wasmtime validates each module it compiles, then meters it.
    • A poll sets ari_gas to its slice. ari.gas is an async import whose continuation isn't ready until the next poll, so it ends the poll there.
    • When a charge ends a slice, the next slice is at least that block's cost, which the guest pays first.
    • Fuel stays on as a backstop: a poll ends after 16 units of fuel per unit of gas, and is charged at least that fuel's worth. A metered guest never reaches it, because a charge costs eight units of fuel.
    • A start function that runs past its allowance now traps. Before, with no fuel yield set at instantiation, it would never have ended.
  • The browser backend pauses the guest at ari.gas instead of counting log_execution checks.
    • Before each call the page sets ari_gas to the slice, and the gas the guest took from it is the call's.
    • The JS no longer makes a call per function entry, loop header and return, only one where a slice runs out. kFuelPerCheck is gone.
  • The interface: Call::poll(gas), gas_used() and Instance::run(..., gas, ...) replace the fuel names.

How it was tested (Windows, sandipaws)

  • Native, static core tree (build-wasmguest-static, with -DCVC_WASM_OPT set to emsdk's binaryen):
  • The new cases:
    • A module that names functions everywhere an index can appear runs as it did. A trap's backtrace still says boom. A probe that skipped the name-section shift made that case fail.
    • count(1000) costs exactly 8001 gas in slices of 1, 7, 8, 100 and 4096, and in one slice. In slices of 1 it takes 1002 polls.
    • A module is metered once, and the runtime counts it the same as one it metered itself.
    • What the pass can't read is refused, with what it found. Every prefix of a module is read or refused, never read past.
    • An endless start function is refused at instantiation in 38 ms.
    • WasmTransformed.ASpinCountsTheSameOnBothBackends runs the transformed guest's spin through the runtime interface. It costs exactly 24,000,001 gas in one slice, and in 376 slices of 64,000, on wasmtime and in the browser.
  • Browser, under emsdk's node 22.16 (build-wasmgas-web): ariadne_wasm_browser_test passed 23/23 (WasmBinary 4, WasmTransformed 15, WasmBrowser 4). That includes ariadne_wasm: run guests in the browser under Asyncify (G2, first part) #1197's WASI guest case, now metered and then put through Asyncify. The build ran ari_wasm_meter under node, and its metered guests are byte-for-byte the native tool's.
  • Hosts: arix and ari rebuilt, and the arix_wasm_block, arix_wasi_stubs and ari_wasm_needs_arix ctests passed. arix_wasm_block is a .wat guest, metered when it's compiled.
  • Real modules. ari_wasm_meter metered five emscripten builds on sandipaws (the browser test, bunny_shadow, cyprty, arigl and ariglx, 9 to 89 MB) in 0.3 to 2 s each. V8's WebAssembly.validate accepted every original and every output.
  • clang-format 18.1.8 on the changed lines: clean.

What is left out

  • Code size. The inline charge is about 20 bytes a block, so those five apps grew by 58 to 109%. A charge through a helper function (two instructions a block) would be smaller and slower. Guests are much smaller than those apps, so I kept the faster one.
  • Native speed of the charges against fuel. Not measured.
  • A forged module. A module that declares ari.gas and never charges isn't caught in the browser, as ariadne_wasm: run guests in the browser under Asyncify (G2, first part) #1197's log_execution wasn't. Natively the fuel backstop bounds it. The Worker backstop (G4) is the roadmap's answer for untrusted guests in the page.
  • Still left for G2: the ariglx-web wiring with a headless-Chrome smoke, and measuring JSPI against Asyncify.

Joe said "merge 1206": it squash-merges after #1197 lands, once its own required checks are green.

A browser backend for guest_runtime.h, and an install-time transform that needs no Rust, so a
document's WebAssembly guests get the same slices, limits, access and hooks in a single-threaded
page as natively (ARIADNE_SCRIPTING_HOSTS.md 8.5). Natively nothing changes, and wasmtime runs the
same transformed guests.

- cvc_ariadne_wasm_transform (ariadne_wasm.cmake) runs emsdk's binaryen: wasm-opt
  --log-execution=ari --asyncify --pass-arg=asyncify-imports@ari.* -O1. Every function entry,
  loop header and return calls ari.log_execution, the gas check, and every ari import is a point
  the guest may pause at. cvc_find_wasm_opt finds wasm-opt beside emcc, under $EMSDK, on PATH, or
  at -DCVC_WASM_OPT.
- browser_runtime.cpp (Emscripten): a guest is a WebAssembly.Instance beside the host's module,
  made in EM_JS with a trampoline per Import into cvc_ari_wasm_import. Its JS state lives in
  Module.cvcWasmGuests[<the instance>], with no C++ statics. A check costs kFuelPerCheck (16) units
  of fuel. The guest pauses at the check that spends its slice, or in an import that waits:
  Asyncify unwinds it into 16 KiB from its own ari_alloc, and the next poll rewinds it. Setup
  (run(), a start function) can't pause, so there a spent slice or a wait traps. A .wat module and
  an untransformed guest are refused, naming the transform.
- wasm_binary.{h,cpp}: cap_memory lowers a module's memory maximum to wasm_max_memory (or gives it
  one), so the page refuses a memory.grow past it, as wasmtime's store limiter does. It refuses an
  imported, shared or 64-bit memory and a minimum above the cap.
- GuestMemory is copies in and out (size, read, write; map where the memory is the host's), since
  no host pointer reaches the page's guest memory. Instance::memory() returns it. The engine's
  memory sites moved to it with no change in behaviour: the data calls stage their output in
  GuestOut and their input in GuestIn, which map the memory natively.
- wasmtime defines ari.log_execution as a no-op, so transformed guests instantiate there; its fuel
  still meters them.
- CVC_BUILD_WASM_GUEST_TESTS builds ariadne_wasm_browser_test in an Emscripten tree with the tests
  off (googletest from source, the transformed guests embedded at /guests). Natively the same file
  is ariadne_wasm_transform_test, whose transformed cases run where wasm-opt is found.
- ci.yml: a path-filtered wasm-guests (wasm, node) job builds a plain-wasm, single-threaded
  libcvc and runs ariadne_wasm_browser_test under the emsdk's node.

Left for G2: the weighted counters through cvcpkg's Rust crates, wiring guests into ariglx-web
with a headless-Chrome smoke, and JSPI measured against Asyncify.

Tests: WasmBinary.{CapsTheMemoryMaximum,LowersAnExistingMaximumOnly,RefusesWhatItCantCap},
WasmTransformed.* (exports, parked calls, a yield, a spin sliced at its gas checks and killed by a
step cap, a deep stack paused and resumed, traps and fail(), state imports resumed in the slice, a
grow past memory_mb, a volume read into the guest's memory, a frame hook) and
WasmBrowser.{AWatModuleIsRefused,AnUntransformedGuestIsRefused}: 16/16 under node 22.16
(ariadne_wasm_browser_test) and natively on wasmtime (ariadne_wasm_transform_test);
ariadne_wasm_test, ariadne_script_engine_test, arix_wasm_block and ari_wasm_needs_arix unchanged
and green.
… its unwind room breaks it

Review fixes to G2's first part (browser_runtime.cpp, ARIADNE_SCRIPTING_HOSTS.md 8.5).

- JS checks no import's signature, so a guest declaring `ari.call (param i32 i32)` ran, and the
  host's side read parameters past its span. wasm_binary's function_imports reads the guest's
  type and import sections, and the browser refuses an `ari` import whose parameters (an i64
  where Import::wide marks one) or result differ from the host's, or one the host doesn't
  define, before it instantiates the module, as wasmtime's linker does natively. dispatch()
  also traps when the arguments it gets aren't the import's count.
- Asyncify writes a paused stack unchecked and checks only in asyncify_stop_unwind, after it
  has written past the room. cvc_wasm_call reads the room's header first: a stack past it traps
  with what it took and the setting's name, and the guest refuses every later call, since its
  memory after the room is gone. The room is ariadne.limits.wasm_unwind_bytes
  (InstanceLimits::unwind_bytes), 32 KiB by default (it was a fixed 16 KiB).
- A module is compiled once for each memory cap it runs under and kept with its BrModule
  (Module.cvcWasmModules), not on every instantiate. A compile that fails past 8 MiB names
  Chrome's limit on the page's thread; the asynchronous compile is left for the ariglx-web
  wiring.
- tests/CMakeLists.txt builds ariadne_wasm_test and ariadne_wasm_transform_test natively only:
  under Emscripten the find macro finds the browser backend, which compiles no .wat.
  CVC_BUILD_WASM_GUEST_TESTS with CVC_BUILD_TESTS on now warns that it is ignored.
- ci.yml: the wasm-guests path filter also covers the CMake, the libcvc recipe and the
  AppRuntime and state code the test drives. Its comment and the roadmap's Tests bullet no
  longer claim the package lanes run the transformed cases natively: no package lane has a
  wasm-opt, so there only the cases that need no transformed guest run.

Tests: WasmBinary.ReadsTheImportsTypes, WasmTransformed.AnImportOfAnotherTypeIsRefused and
WasmTransformed.AModuleServesEveryDocument on both backends;
WasmBrowser.AStackPastTheUnwindRoomBreaksTheGuest and WasmBrowser.TheUnwindRoomIsASetting
under node. 21/21 under node 22.16 (ariadne_wasm_browser_test); natively ariadne_wasm_test,
ariadne_wasm_transform_test, ariadne_script_engine_test, arix_wasm_block and
ari_wasm_needs_arix green (76/76).
…wser (G2, second part)

A guest's work now counts the same on wasmtime and in the browser, and
however a call is sliced.

- meter.h/.cpp: the gas pass, in C++. It reads a core module, charges each
  metered block's cost against a new exported i64 global, ari_gas, inline,
  and calls a new import, ari.gas(cost), only when the slice can't pay for
  the block. A block starts at a function's entry and after loop, if, else,
  end and the conditional branches. An instruction costs what wasmtime's
  fuel charges. The new import shifts every defined function's index, in
  calls, ref.func, element segments, exports, the start function and the
  name section. ari_gas starts at the start function's allowance.
  - It refuses GC types and instructions, the legacy exception handling,
    components, and code that names a global index the pass's own would
    take. A module that imports ari.gas already is left as it is.
  - It's C++ rather than paritytech/wasm-instrument, which the roadmap
    named: that crate and its parser, parity-wasm, haven't changed since
    2022, and parity-wasm doesn't read reference types, which LLVM 19 turns
    on by default for wasm32.
- meter_main.cpp: ari_wasm_meter, the pass as a command. Under Emscripten
  it runs in node.
- cvc_ariadne_wasm_transform: binaryen reads the guest, ari_wasm_meter
  meters it, then wasm-opt --asyncify --pass-arg=asyncify-imports@ari.* -O1.
  This replaces --log-execution.
- wasmtime validates and meters each module it compiles. A poll sets
  ari_gas to its slice; ari.gas is an async import that ends the poll.
  When a charge ends a slice, the next slice is at least that block's cost.
  Fuel stays on as a backstop (16 units per unit of gas). A start function
  past its allowance traps instead of hanging.
- browser_runtime.cpp pauses at ari.gas instead of counting log_execution
  checks. The page sets ari_gas before each call, and the gas the guest
  took is the call's. kFuelPerCheck is gone.
- Call::poll(gas), gas_used() and Instance::run(..., gas, ...) replace the
  fuel names.
- Tests: WasmGasTest (ariadne_wasm_test). A module naming functions
  everywhere runs as it did. count(1000) costs 8001 in slices of
  1, 7, 8, 100, 4096 and in one. A module is metered once. What the pass
  can't read is refused, and every prefix of a module is read or refused.
  A start function that never ends is refused.
  WasmTransformed.ASpinCountsTheSameOnBothBackends: the transformed guest's
  spin costs 24,000,001 in one slice and in 376 of 64,000, on wasmtime and
  in the browser.
@transfix
transfix changed the base branch from feat/ox-browser-guests to master November 13, 2026 03:54
# Conflicts:
#	docs/roadmap/ARIADNE_SCRIPTING_HOSTS.md
#	src/cvc/tests/ariadne_wasm_test.cpp
…I bound in the browser

#1199's WASI preview 1 stubs reached the guest's memory through
GuestMemory::bytes(), which this branch replaced with copies (size, read,
write, map), because no host pointer reaches the page's guest memory.

- wasi_preview1.cpp reads and writes by copies: inside() checks a range,
  store_u32/store_u64 write a value, and the iovecs and poll records are
  read in before they're walked. random_get fills in 4 KiB chunks, so a
  large request never takes a host buffer its size. The errnos are as
  before (EFAULT outside the memory).
- browser_runtime.cpp binds each import under its own module (the spec
  is "module:name:returns;"), so a WASI guest's wasi_snapshot_preview1
  imports are there in the page, and gives an i32 result (WASI's errno)
  as a Number, an i64 as a BigInt. imports_match checks every module's
  imports against the host's, the i32 results among them.
- ariadne_wasm.cmake: wasi_preview1.cpp joins the common sources, since
  wasm_engine.cpp calls wasi_imports() on both backends.
- cvc_ariadne_wasm_transform passes binaryen CVC_WASM_GUEST_FEATURES (bulk
  memory, sign extension, multi-value, reference types, SIMD, extended
  constants, tail calls): it reads only the MVP otherwise, and a guest from
  clang or rustc, or the WASI test guest, uses more.
- The test guests include wasi_guest.wat, transformed, and
  WasmTransformed.AWasiGuestRunsOnTheStubs runs its clocks, random
  numbers, args, stdout and a sleep on both backends.
- The transform keeps its three steps, with #1197's CVC_WASM_GUEST_FEATURES
  on both wasm-opt runs (the WASI test guest's bulk memory).
- meter.cpp and wasi_preview1.cpp are both common sources.
- wasm_engine.cpp: #1199's _initialize message, on kSetupGas.
- wasmtime_runtime.cpp: #1199's set_result; the log_execution no-op stays gone.
- browser_runtime.cpp: the imports bound under their own modules, with ari.gas
  the gas pass's import, checked as (param i64).
- Tests: the spin's count and the WASI guest on both backends, side by side.
…app (master builds again)

#1197's ariadne_wasm_browser_test.cpp (built natively as ariadne_wasm_transform_test wherever
wasmtime is found, and in the wasm-guests node job) still called register_script_engine(engine)
and unregister_script_engine("wasm"), which #1203 replaced with the (app, ...) forms. #1197's CI ran
before #1203 landed, so master at accadc3 doesn't compile it.

As #1203 did for ariadne_wasm_test.cpp: SetUp no longer registers the engine, and the TearDown
that unregistered it goes. Each of the file's 18 AppRuntimes already calls
use_script_engine(engine), which registers it on that runtime's app.
… app

#1203 gives every cvc command its app as an argument, removes cvc_app() and
makes cvc::ariadne::load_string take the app. It merged after #1168 and #1180,
whose new code still used the old forms, so master does not build:
- src/cvc-cli/main.cpp: cmd_trace (#1168) takes cvc::app & like the other
  commands and replays on it, not cvc_app().
- src/cvc/tests/ariadne_runtime_test.cpp: #1180's three AriadneRichText
  tests pass their app to load_string; each already makes one.
…ted-gas

#1197 is in master as its squash, so the conflicts were #1197's own lines
against this branch's changes to them: this branch's are kept.

Two compile breaks on master, fixed here as #1203 fixed its own callers:
- ariadne_wasm_browser_test.cpp (#1197) called register_script_engine(engine)
  and unregister_script_engine("wasm"), which #1203 removed: the fixture
  registers nothing, as each test's AppRuntime calls use_script_engine.
- ariadne_runtime_test.cpp (#1180) called load_string(yaml), which #1203
  made load_string(app, yaml): the three calls pass the test's app.
@transfix
transfix enabled auto-merge (squash) November 14, 2026 09:07
…e browser test's fixture) into feat/wasm-weighted-gas
@transfix
transfix disabled auto-merge November 14, 2026 09:10
@transfix
transfix enabled auto-merge (squash) November 14, 2026 09:10
@transfix
transfix merged commit c585ffe into master Nov 14, 2026
28 checks passed
@transfix
transfix deleted the feat/wasm-weighted-gas branch November 14, 2026 14:03
transfix added a commit that referenced this pull request Nov 14, 2026
…#1222-#1225, #1229)

Master's #1190 (file-pick and http-upload) was written for a single async host; this branch runs
an isolated document's programs on its own group's host, on a pool worker in an `any` group.

- net_intrinsics.cpp: StartedRequest takes master's deliver()/on_outcome, settling through the
  host's finisher. http-upload is its own provider, `any` as the requests are: it parks on the
  calling program's host (ictx.host), takes its progress path from ictx.root_path (no tree walk
  on a worker), and a started upload (a browser page) keeps the host's finisher, not the host.
- ariadne.cpp: file-pick, file-info and file-forget bind into the program's env as they are, in
  every group (install_backend_verbs), not through the backend verbs' host_proxied wrapper, which
  cannot park an async verb. file-pick parks on the program's own host, claims the Runtime's
  picker hub under its lock where it is called, and opens the picker on the host thread
  (exec_pool::run_on_host; inline when called there). Its answer goes through the host's
  finisher, as the host may be gone by then.
- ci.yml: the sanitizer list keeps this branch's tests and master's point_classes_test.
- STATE_EXEC_THREADED.md: rows for http-upload, the file verbs, and the contours and
  point-classes providers. The last two are registered without a kind, so they are host_only, and
  an isolated document in an app that installs them goes to a host-affinity group.
- New test: AriadneIsolatedDocs.FilePickOpensItsPickerOnTheFramesThread.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant