Skip to content

ariadne wasm: WASI preview 1 stubs for every guest (G6, first part) - #1199

Merged
transfix merged 5 commits into
masterfrom
feat/ox-wasi
Nov 14, 2026
Merged

transfix merged 5 commits into
masterfrom
feat/ox-wasi

Conversation

@transfix

Copy link
Copy Markdown
Owner

Phase G6, first part, of docs/roadmap/ARIADNE_SCRIPTING_HOSTS.md (section 8.6.1): WASI preview 1 stubs for every wasm: guest in arix and ariglx.

What it adds

A module built for wasm32-wasip1 or with wasi-sdk imports wasi_snapshot_preview1 whether or not it uses it, so until now such a guest didn't even instantiate ("unknown import"). Every wasm: guest now links all 46 preview-1 functions, as backend-neutral stubs on the runtime interface (src/ariadne_wasm/wasi_preview1.cpp):

  • The clocks, random_get, sched_yield and proc_exit work.
  • argv is the module's file name, then the block's wasi: args. The environment is empty.
  • stdin is at its end. stdout and stderr take every byte and drop it. All three are character devices to fd_fdstat_get and fd_filestat_get.
  • fd_prestat_get and fd_prestat_dir_name return EBADF for every fd, so wasi-libc's preopen scan ends cleanly.
  • poll_oneoff takes clock subscriptions, and each one fires at once. So usleep, nanosleep and Rust's thread::sleep return at once and never block the loop. A poll on an fd stays ENOTCAPABLE.
  • Every other file, directory, socket, poll and signal call returns ENOTCAPABLE. A pointer outside the guest's memory is EFAULT, not a trap.
  • Host work is bounded:
    • Each WASI call is charged a step, plus a step per kDataNodeBytes it moves, against the activation's caps.
    • fd_write and fd_read take at most 1024 iovecs (wasi-libc's IOV_MAX); more is EINVAL. The iovec records they read are charged too.
    • random_get's index is 64-bit, so a fill near the top of a 4 GiB memory ends.
  • proc_exit ends the guest, never the host:
    • Status 0 returns nil. Any other status raises a WasmError with exit.
    • Every later call is a WasmError with exited until the document reloads.
    • An _initialize or ari_init that exits fails the load. The exception is a reactor _initialize that ends with proc_exit(0), which counts as a finished setup.
  • The block's new wasi: key is parsed: args, dirs ([{host, guest, mode: ro|rw}]) and env.
    • No host grants a directory or a variable yet; arisrvx's --wasi-dir and --wasi-env are the next part. So a request for either fails the load and names the missing grant.
    • An unknown wasi: key warns.
  • The runtime interface gains Import::module and Import::returns_i32. The wasmtime backend defines each import under its own module.
  • docs/ARIADNE.md's wasm: section gets a WASI bullet. The roadmap's as-built note lists every difference from the stub list.

How it was tested (Windows, static Release tree)

  • ctest-ox-wasi.bat, ctest regex Wasm|wasm|wasi|Wasi|AriadneRequires|ScriptEngine: 91 passed, 0 failed. This includes arix_wasi_stubs, arix_wasm_block, ari_wasm_needs_arix and all of ariadne_wasm_test.
  • ariadne_wasm_test --gtest_filter=WasmWasiTest.*: 11 passed, 0 failed.
  • ctest -R 'arix_|ari_wasm': 5 passed, 2 failed. The 2 failures are arix_python_block and arix_python_program, which need pycvc, and this tree doesn't build pycvc.
  • Review probes on build-ox-wasi's arix.exe test: burn1.ari, exitprobe2.ari and nap.ari, 3 passed, 0 failed.
    • The iovec burn takes 0.0003 s, down from 1.02 s.
    • Calls after an exit are refused.
    • usleep and nanosleep return 0.
  • clang-format 18.1.8 (git-clang-format --diff against a5fbd47): no changes.
  • git merge-tree --write-tree against origin/feat/wasm-policy-pure (8b3d1d3) and against origin/master: both clean.

A C reactor built with wasi-sdk 33 (printf, time, getenv, fopen, clock_gettime, exit) runs in arix on these stubs. It isn't committed because CI has no wasi-sdk, so the tests are WAT.

arix_wasi_stubs runs only where arix is built with wasmtime. That is this box, not CI: package-linux has wasmtime but builds no arix, and pycvc-linux and sanitizers build arix without wasmtime. In PR CI, WasmWasiTest in package-linux covers the change.

Left out

  • Finding 6's CI change: install wasmtime in pycvc-linux and add its prefix to CMAKE_PREFIX_PATH, so arix_wasm_block and arix_wasi_stubs run in CI. The finding asks for this as a separate change.
  • Finding 3's optional bulk random fill: this would use BCryptGenRandom or getrandom instead of one random_device call per 4 bytes. Only the 64-bit index fix is done. The fill is charged at n/256 steps, as the data calls are.
  • Re-instantiating after a trap or fail(): the instance still takes the next call, as G1 has it, and TrapsAndFailuresAreWasmErrors relies on this. A C guest's shadow stack still loses the trapped frames each time. The commit body notes this as a separate change.
  • Continuation::i32 (the async half of returns_i32): kept, and noted in the commit body as untested, because every WASI import is sync.
  • Finding 2's re-instantiation option: later calls are refused instead. That avoids re-running ari_init outside the init: lane and doing re-instantiation work that isn't charged.

Merging waits on Joe's review.

#1159 (O7c) kept the last source sea_surface found in a thread_local, so
the velocity a fluid field reads after a cell's height at the same point
and time did not invert the sideways move again. A thread_local that
keeps state between calls is a static cache, which libcvc's no-singletons
rule forbids (VOLROVER-LIBRARY-PORTS-ROADMAP.md 1.3,
tools/singleton_scan). #1159's release-grpc job, where the scan runs, was
cancelled, so the scan never judged it; the next PR that merges master
would fail that lane on it.

The memo now belongs to the caller:

- sea_surface::source_memo, and height() / velocity() overloads that take
  one. The plain reads share nothing.
- fluid_surface::height_with / velocity_with and a surface_memo the
  caller owns; the defaults ignore it. ocean_surface passes it to the sea.
- field_set::apply keeps one memo per cell, for the cell's height and its
  velocity at the same clipped centre.

The memo is keyed on the point, the time and the digest as before, so
every value is unchanged.
A module built for wasm32-wasip1 or with wasi-sdk imports
wasi_snapshot_preview1 whether or not it uses it, so until now such a
guest didn't even instantiate in arix or ariglx ("unknown import").
Every wasm: guest now links all 46 preview-1 functions, as our own
backend-neutral stubs on the runtime interface
(src/ariadne_wasm/wasi_preview1.cpp; roadmap section 8.6.1):

- the clocks, random_get, sched_yield and proc_exit work;
- argv is the module's file name, then the block's wasi: args, and the
  environment is empty;
- stdin is at its end, and stdout and stderr take every byte and drop
  it; the three are character devices to fd_fdstat_get and
  fd_filestat_get;
- fd_prestat_get and fd_prestat_dir_name return EBADF for every fd, so
  wasi-libc's scan of the preopens ends cleanly (any other errno makes
  it exit 71 at startup);
- every other file, directory, socket, poll and signal call returns
  ENOTCAPABLE, and a pointer outside the guest's memory is EFAULT, not
  a trap.

Each WASI call is charged a step, plus a step per kDataNodeBytes it
moves, against the activation's caps. proc_exit ends the activation,
never the host: status 0 returns nil, any other raises a WasmError with
`exit`, and the instance takes the next call. A reactor's _initialize
that ends with proc_exit(0) is a finished setup.

The runtime interface gains Import::module and Import::returns_i32 (an
i32 result, WASI's errno), and the wasmtime backend defines each import
under its own module.

The block's new wasi: key is parsed: args (a list of strings), dirs
([{host, guest, mode: ro|rw}]) and env (names). No host grants a
directory or a variable yet (arisrvx's --wasi-dir and --wasi-env are
the next part), so a request for either fails the load, naming the
request and the missing grant: a guest never runs without the data it
asked for. An unknown wasi: key warns.

A C reactor built with wasi-sdk 33 (printf, time, getenv, fopen,
clock_gettime, exit) runs in arix on these stubs; it isn't committed,
as CI has no wasi-sdk, so the tests are WAT.

Tests: WasmWasiTest (AGuestBuiltForWasiLoadsWhereNothingIsGranted,
ClocksAndRandomNumbersWork, ArgsAreTheBlocksAndTheEnvironmentIsEmpty,
FileCallsAreNotCapable, StdoutIsASinkAndStdinIsEmpty,
ProcExitEndsTheActivationNotTheHost, AWasiCallIsChargedAStep,
ARequestOutsideTheGrantFailsTheLoad, AMistypedWasiImportFailsTheLoad);
the arix_wasi_stubs ctest; the rest of ariadne_wasm_test,
ariadne_script_engine_test, AriadneRequires, arix_wasm_block and
ari_wasm_needs_arix still pass (89/89 on a static Windows tree).
…t ends the guest

Review fixes on G6's first part.

- fd_write and fd_read take at most 1024 iovecs a call (wasi-libc's
  IOV_MAX), and more is EINVAL, as writev has it. A step per call
  couldn't bound the walk: 2^25 zero-length iovecs cost the guest next
  to nothing and the host 0.75 s a call, inside one slice. The walk
  also reads the memory once, not once per iovec, and its 8 bytes per
  iovec are charged with the bytes moved, whatever the call returns.
- poll_oneoff takes clock subscriptions: each fires at once (userdata,
  no error, the clock's type), so usleep, nanosleep and Rust's
  thread::sleep return at once, never blocking the loop. A poll on an
  fd stays ENOTCAPABLE; no subscription, more than 1024, an unknown
  type or clock is EINVAL. The records it reads and writes are charged.
- proc_exit ends the guest. wasi-libc's exit has run the atexit
  handlers and static destructors, and the trap leaves the shadow stack
  where the exit was (32 bytes lost per exit in a wasi-sdk probe), so
  the instance goes, with the objects it held. The call still returns
  nil for status 0 and raises a WasmError with `exit` for any other;
  every later call is a WasmError with `exited` until the document
  reloads. An _initialize or ari_init that exits, whatever its status,
  fails the load.
- random_get's index is 64-bit: a u32 one wrapped past 0xfffffffc on a
  full 4 GiB memory, and the loop never ended.

A trap or fail() still leaves the instance for the next call, as G1
has it (TrapsAndFailuresAreWasmErrors). A C guest's shadow stack loses
the trapped frames each time; re-instantiating after a trap is a
separate change. Continuation::i32, the async half of returns_i32, is
still untested: every WASI import is sync.

The WASI tests move ahead of the state-import tests, and the file
header's WASI sentence is a paragraph of its own, so this merges with
the pure-exports branch (feat/wasm-policy-pure) without a conflict.
ARIADNE.md's wasm: section gets a WASI bullet; the roadmap's as-built
note lists every difference from the stub list.

arix_wasi_stubs runs only where arix is built with wasmtime: here, not
in CI (package-linux has wasmtime but builds no arix; pycvc-linux and
sanitizers build arix without wasmtime). In PR CI the change is
covered by WasmWasiTest in package-linux.

Tests: WasmWasiTest gains ASleepReturnsAtOnce and
TheIovecsACallWalksAreCharged; ProcExitEndsTheGuestNotTheHost (was
...TheActivation...) checks the refused later calls, the reload, and
the setups that exit; StdoutIsASinkAndStdinIsEmpty checks
fd_filestat_get(1) (errno 0, filetype 2 at offset 16, size 0) and the
1024/1025 iovec edge; wasi_block.ari and wasi_guest.wat match. 91/91
of the wasm, wasi, AriadneRequires and ScriptEngine ctests pass on a
static Windows tree, arix_wasm_block and arix_wasi_stubs among them.
@transfix transfix changed the title ariadne wasm: WASI stubs bound their host work, sleep works, proc_exit ends the guest ariadne wasm: WASI preview 1 stubs for every guest (G6, first part) Nov 12, 2026
@transfix
transfix enabled auto-merge (squash) November 13, 2026 03:54
@transfix
transfix merged commit 712af28 into master Nov 14, 2026
29 of 33 checks passed
@transfix
transfix deleted the feat/ox-wasi branch November 14, 2026 01:27
transfix added a commit that referenced this pull request Nov 14, 2026
…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.
transfix added a commit that referenced this pull request Nov 14, 2026
- 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.
transfix added a commit that referenced this pull request Nov 14, 2026
…#1177, #1167) into perf/threaded-s1b

The one conflict is the sanitizers' SAN_CXX_TESTS list in ci.yml: this branch added
stream_test, net_ws_client_test and ariadne_host_test, and #1167 added skeleton_test. The
list keeps all four.
transfix added a commit that referenced this pull request Nov 14, 2026
…t) (#1197)

G2's first part (ARIADNE_SCRIPTING_HOSTS.md §8.5, "Gas"; §10 row G2): WebAssembly guests run in a
single-threaded browser page with the same slices, limits, access and hooks they get natively.

- cvc_ariadne_wasm_transform (ariadne_wasm.cmake): the install-time transform, emsdk's binaryen
  (wasm-opt --log-execution=ari --asyncify --pass-arg=asyncify-imports@ari.* -O1): a gas check
  at every function entry, loop header and return, and every ari import a point the guest can
  pause at. cvc_find_wasm_opt finds wasm-opt beside emcc, under $EMSDK, on PATH or at
  -DCVC_WASM_OPT.
- browser_runtime.cpp (Emscripten only): a guest is a WebAssembly.Instance beside the host's
  module, its JS state in Module.cvcWasmGuests. A guest pauses at the check that spends its
  slice, or in an import that waits; Asyncify unwinds it into a room from its own ari_alloc
  (ariadne.limits.wasm_unwind_bytes, 32 KiB), and the next poll rewinds it. A stack past the room
  traps with the setting's name, and the guest refuses later calls. Setup can't pause. A .wat
  module and an untransformed guest are refused, naming the transform. The guest's ari imports
  are checked against the host's (function_imports), as wasmtime's linker does. A module
  compiles once per memory cap.
- wasm_binary.{h,cpp}: cap_memory lowers a module's memory maximum to wasm_max_memory, so the page
  refuses a memory.grow past the cap; an imported, shared or 64-bit memory is refused.
- GuestMemory copies in and out (size, read, write, and map where the memory is the host's).
- wasmtime defines ari.log_execution as nothing, so transformed guests run natively too.
- WASI guests (#1199's stubs) run in the browser too: each import is bound under its own
  module, an i32 result (WASI's errno) crosses as a Number, and the stubs reach the guest's
  memory by copies. The transform passes binaryen the features wasmtime and the browsers run
  (CVC_WASM_GUEST_FEATURES: bulk memory, sign extension, multi-value, reference types, SIMD).
- Tests: ariadne_wasm_browser_test under node (CVC_BUILD_WASM_GUEST_TESTS, the transformed guests
  embedded at /guests), and natively the same file as ariadne_wasm_transform_test; ci.yml's
  wasm-guests (wasm, node) job.
transfix added a commit that referenced this pull request Nov 14, 2026
…wser (G2, second part) (#1206)

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.
- The WASI guest (#1199) is metered and Asyncified in the transform too, and
  the transform passes binaryen CVC_WASM_GUEST_FEATURES on both runs.
- The branch also carries the compile fixes for #1203's API change that
  #1225 and #1229 bring to master (cmd_trace, the rich-text tests'
  load_string, the browser test's fixture), which master may have first.
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