wasm_script_worker (wasm v0.16.0)

View Source

A worker kernel: processes, deadlines, bounded streams, and an adapter.

It runs many small untrusted guest modules, one tenant's code per request. What it knows about is modules, imports, invocations, deadlines and bounded channels. It does not know about WASI, or JSON, or an entry point called main. Those belong to an adapter, which is what makes a language the kernel has never heard of expressible without changing anything here.

{ok, W} = wasm_script_worker:start_link(my_adapter, #{}),
{ok, R} = wasm_script_worker:run(W, MyRequest).

What it supports, stated exactly

Not "any language":

Any language runtime packaged as a WebAssembly module that an adapter can express as a finite sequence of calls over supported imports.

Long-lived event loops, threads, native extensions, browser ABIs and component-model guests are outside the guarantee.

What is supported API

These are covered by compatibility and the release notes:

modulewhat it is
wasm_script_workerthis module: start, run, submit, await, cancel, stop, and the operator view (cleanup_stats/0, cleanup_requests/0)
wasm_worker_adapterthe behaviour an adapter implements, and every type its callbacks name
wasm_worker_errorthe errors a worker answers with, and the constructors an adapter builds its own with
wasm_javascript, wasm_javascript_command, wasm_python, wasm_python_command, wasm_luathe shipped adapters
wasm_adapter_conformancethe kit that checks an adapter keeps the contract
wasm_instance_workerthe simple worker: one instance, one process, a deadline

So are the option keys this module takes (root, timeout, trusted, limits, capture_timeout, runner_min_heap_words, capture_min_heap_words, restore_ahead, compiled, and the limits keys docs/worker-reference.md lists), the wasm application settings scratch_roots and reaper_options, and the error shapes: a running worker answers {error, wasm_worker_error:worker_error()}, and start_link/2,3 fails with a gen_server start reason, one of {missing_option, Key}, {bad_option, Key, Why}, {unknown_root, Root, Known}, {unknown_reaper_option, Keys} or the adapter's own wasm_worker_error().

wasm_worker_reaper, wasm_worker_sup, wasm_script_v1, wasm_worker_fs and the cleanup modules (wasm_cleanup_manager, wasm_cleanup_steward, wasm_cleanup_steward_sup) are internal: they may change in any release.

Where things are

The worker, the guardian, the runner and, with restore_ahead, the ahead runner each have their own entry and loop. "The process shape" below draws them.

you wantlook at
starting a worker, and capturing its image oncestart_link/2, init/1, capture_image/3
running a request from the caller's siderun/2, submit/2, await/3, cancel/2
the worker (gen_server): accepting a request, never blockinghandle_call/3, do_submit/3, handle_info/2
the guardian: its entry and its deadline loopguardian/1, loop/1
the guardian starting and killing the runnerstart_runner/4, spawn_runner/1, kill_runner/2
the guardian ending a request and handing cleanup onfinish/3, hand_off/1
the runner: requirements, mounts, instantiate, invoke, decoderunner/2, request/2, execute/3, invoke_loop/5
the ahead runner: restoring the next instance earlystart_ahead/1, ahead_runner/2, ahead_loop/2, restore_next/1
a request taking the instance restored aheadtake_ahead/2
mounts and staged filesmake_mounts/2, do_stage/4
bounded output channelsnew_channel/2, channel_write/2, channel_read/1
what a request is allowed to ask forpolicy/2
calling an adapter callback without raisingcall_back/3

The execution model is the one every other runtime has

Stripped of processes and bounds, the whole job is three lines:

{ok, Inst} = wasm:instantiate(Module, Imports, Limits),
Result     = wasm:call(Inst, Export, Args, Limits),
ok         = wasm:destroy(Inst).

Assemble an import set, instantiate, call an export, release. That is Wasmtime's Linker and Store, Wasmer's Imports and exports.get_function, wasm3's lookup_function and call. WASI is something an adapter puts into the imports, exactly as those runtimes make it a library you attach rather than a mode the engine is in.

There is no {start} invocation, because there could not be one without this module knowing what _start means, and a {start} it translated would be WASI knowledge smuggled into a type. An adapter that wants a command writes {call, ~"_start", []} itself. That is the only reason a reactor and a command are the same code path: they are the same call, chosen by different adapters.

One instance per request

Three constraints point at it and a persistent interpreter fails all three. docs/worker.md is unambiguous that untrusted code gets fresh, and replacing a language's globals resets neither imported modules nor native interpreter state. Fuel and max_host_calls open once at the outermost invocation, so a guest blocked in a read never leaves it and its budgets accumulate over the worker's life instead of resetting. And the compiled tier asks after a call returns, so a _start guest that never returns never asks.

The process shape

worker (gen_server)     never blocks; holds at most one request
  |  spawn_monitor           worker learns of guardian death  (DOWN)
  |  <- guardian monitors    guardian learns of worker death  (DOWN)
guardian                traps exits; owns the mounts and the deadline;
  |  spawn_opt [link,monitor]   runs no guest code, always responsive
runner                  instantiate -> invoke -> decode -> destroy

Monitors are one-way, so both directions are set up explicitly. The worker monitors the guardian, which tells the worker when the guardian dies and tells the guardian nothing, so the guardian monitors the worker back.

The runner is spawned [link, monitor] deliberately: the monitor delivers the DOWN carrying the exit reason the guardian reads, and the link kills the runner if the guardian dies abnormally. The guardian traps exits, so the link arrives as an EXIT it ignores, and it acts on the DOWN.

Restore ahead

With restore_ahead => true and an image, the runner is the worker's rather than the request's. It restores the next instance while the worker waits, and each request is sent to it instead of spawning one. The instance is restored with a forwarding function per import, and a request installs the bindings its adapter's wasm_worker_adapter:prepare/3 built before the guest runs, so the preopens, sinks and host calls are that request's. The runner is linked to the guardian for the request and let go when the request answers; a deadline, a cancellation or a crash kills it as before, and the worker starts another. Every request still gets an instance restored from the image and used once.

Failures are values

Nothing a guest supplies makes a worker call raise, which is the runtime's promise (Failures are values at the guest boundary) applied to this layer. It also covers the worker itself: gen_server:call on a dead process exits, so run/2, submit/2, await/3 and cancel/2 catch that and answer {error, WorkerError}. The kinds they can produce are in wasm_worker_error. stop/1 is plain gen_server:stop/1, so on a worker that has already exited it exits with noproc.

Summary

Functions

Wait for an outcome.

Stop a request. This is what ends a tenant's code; await/3 is not.

The same, for the process a capture runs in.

Write to a channel, and stop the guest if that passed the bound.

Every request whose cleanup is still owned, with the guardian holding it.

Counts per state of the cleanup that follows requests, node-wide. capacity is how many reservations are held now; when it reaches max_cleanup_jobs + cleanup_queue_len from reaper_options, submit answers cleanup_saturated.

Acknowledge an outcome, which is what releases it.

The ceilings a worker starts with, over wasm_limits:untrusted/0.

Submit and wait for ever.

Run Source with Context and wait for the answer: run/2 with the request every shipped adapter takes, #{source => Source, context => Context}.

How much heap a request runner starts with, and what happened to the number.

Start a worker for one adapter.

Accept a request, and reply once the guardian is ready.

submit/2 with #{source => Source, context => Context}, as run/3.

Release the waiter slot after a finite await/3 gave up, and settle the race.

Types

adapter_state()

-type adapter_state() :: wasm_worker_adapter:adapter_state().

artifact()

-type artifact() :: wasm_worker_adapter:artifact().

capabilities()

-type capabilities() :: wasm_worker_adapter:capabilities().

capture()

-type capture() :: wasm_worker_adapter:capture().

channel()

-type channel() :: wasm_worker_adapter:channel().

cleanup_cap()

-type cleanup_cap() :: wasm_worker_adapter:cleanup_cap().

compatibility_key()

-type compatibility_key() :: wasm_worker_adapter:compatibility_key().

env()

-type env() :: wasm_worker_adapter:env().

execution_result()

-type execution_result() :: wasm_worker_adapter:execution_result().

execution_spec()

-type execution_spec() :: wasm_worker_adapter:execution_spec().

fixtures()

-type fixtures() :: wasm_worker_adapter:fixtures().

heap_note()

-type heap_note() :: ok | {bad, term()} | {no_room, pos_integer()}.

hook()

-type hook() :: wasm_worker_adapter:hook().

import_set()

-type import_set() :: wasm_worker_adapter:import_set().

import_value()

-type import_value() :: wasm_worker_adapter:import_value().

invocation_result()

-type invocation_result() :: wasm_worker_adapter:invocation_result().

mount()

-type mount() :: wasm_worker_adapter:mount().

mount_name()

-type mount_name() :: wasm_worker_adapter:mount_name().

outcome()

-type outcome() :: wasm_worker_adapter:outcome().

portable()

-type portable() :: wasm_worker_adapter:portable().

request()

-type request() :: wasm_worker_adapter:request().

requirements()

-type requirements() :: wasm_worker_adapter:requirements().

restore_ctx()

-type restore_ctx() :: wasm_worker_adapter:restore_ctx().

result()

-type result() :: wasm_worker_adapter:result().

snapshot_cap()

-type snapshot_cap() :: wasm_worker_adapter:snapshot_cap().

stop_class()

-type stop_class() :: wasm_worker_adapter:stop_class().

Functions

await(W, Ref, AwaitTimeout)

Wait for an outcome.

AwaitTimeout bounds your wait and nothing else. The request keeps running under its own deadline and {error, still_running} says so, because a caller who stopped waiting has not decided the tenant's code should die. cancel/2 is what decides that.

cancel(W, Ref)

-spec cancel(gen_server:server_ref(), reference()) -> ok | {error, wasm_worker_error:worker_error()}.

Stop a request. This is what ends a tenant's code; await/3 is not.

capture_heap_words(Opts, Limits)

-spec capture_heap_words(map(), map()) -> {non_neg_integer(), heap_note()}.

The same, for the process a capture runs in.

A separate setting because it is a different process doing different work: the capturer runs the guest's init() once and the runner answers a request, and the two want numbers that are nothing like each other. CPython's capture takes 2,000,000 words to a request's 1,000,000, and a guest with no capture at all wants only the first.

The effect is larger here than anywhere else in this module. test/audit/PERF.md has it at 5x on a CPython worker start.

channel_write/2

-spec channel_write(channel(), iodata()) -> ok.

Write to a channel, and stop the guest if that passed the bound.

atomics:add_get/3 hands back the new total, so the offset before the write is the key: ordering is decided by the same atomic operation that decided the bound, with no sequence number to keep in step.

exit/2, never exit/1, and the runner must not trap exits. The sink runs inside wasm:call, which wraps execution in wasm_error:capture/2, and that ends in a catch-all Class:Reason:Stack clause. exit/1 raises a catchable exception, so capture swallows it and reports #{kind => internal} while the runner sails on into decode/2. exit/2 sends a signal, which no try can intercept.

cleanup_requests()

-spec cleanup_requests() ->
                          [#{id := binary(),
                             state := atom(),
                             guardian := pid(),
                             delivered := boolean(),
                             actions := non_neg_integer()}].

Every request whose cleanup is still owned, with the guardian holding it.

A reservation that ends in held stays there until a late answer or a DOWN, on purpose, since deleting a running request's mounts cannot be undone. This is how an operator finds which guardian holds it, to kill that guardian if it really is stuck.

cleanup_stats()

-spec cleanup_stats() -> map().

Counts per state of the cleanup that follows requests, node-wide. capacity is how many reservations are held now; when it reaches max_cleanup_jobs + cleanup_queue_len from reaper_options, submit answers cleanup_saturated.

Served from the cleanup manager, which holds the view the reaper pushes it, so it answers even while the reaper is busy in journal I/O.

consumed(W, Ref, Token)

-spec consumed(gen_server:server_ref(), reference(), reference()) ->
                  ok | {error, wasm_worker_error:worker_error()}.

Acknowledge an outcome, which is what releases it.

Sending is not consuming. A reply the worker put on the wire may never be received, which is the whole reason the abandoning caller has to ask, so the outcome is retained until acknowledged rather than until sent.

default_limits()

-spec default_limits() -> map().

The ceilings a worker starts with, over wasm_limits:untrusted/0.

Exported so that docs/worker-reference.md can be held to listing every one of them: a default nobody can find is a default nobody can change.

handle_call/3

handle_cast/2

handle_info/2

init/1

run(W, Request)

Submit and wait for ever.

No timeout argument, which removes a race rather than hiding one: the guardian already owns the execution deadline, so a second timer on the caller's side only creates the case where both expire together and the caller sees still_running an instant before the guardian publishes the real timeout.

With timeout => infinity this waits for ever, and that is what was asked for. Leave timeout finite unless something outside the worker is doing the bounding, or use await/3 and cancel/2.

run(W, Source, Context)

Run Source with Context and wait for the answer: run/2 with the request every shipped adapter takes, #{source => Source, context => Context}.

{ok, W} = wasm_script_worker:start_link(
            wasm_javascript_command, #{path => "test/fixtures/lang/qjs.wasm"}),
{ok, #{result := #{~"answer" := 42}}} =
    wasm_script_worker:run(W, <<"export function main(c)"
                                " { return {answer: c.value + 1}; }">>,
                           #{~"value" => 41}).

runner_heap_words(Opts, Limits)

-spec runner_heap_words(map(), map()) -> {non_neg_integer(), heap_note()}.

How much heap a request runner starts with, and what happened to the number.

runner_min_heap_words is a floor, not a bound: it says how much room to give a request, where every key in a limits map says what a guest may not exceed. The right value is a property of the guest and there is no number that suits all of them, so an unset one comes from the adapter's optional defaults/1, and is off for an adapter without one. The shipped adapters set the values test/audit/PERF.md measured; docs/tuning.md is how to find your own. This function reads only Opts: the worker merges the adapter's defaults under the caller's options before calling it.

Resolved once at start_link/2 and reported rather than applied silently, which is wasm_jit's resolve_max_heap_words arrangement and is here for the same reason: a setting nobody can read back is a setting nobody can tell is being used. Exported so the policy can be asserted without starting a worker.

Two ways a number comes back changed, and neither is an error:

  • {bad, Term} -- not a whole number of words between the emulator's own minimum and its undocumented maximum. Answers off.
  • {no_room, Ceiling} -- the floor does not fit under this worker's max_heap_words with the headroom the emulator's rounding needs. Answers off, because the alternative is a runner killed at spawn and a worker whose every request fails for a reason nothing names.

start_link(Adapter, Opts)

-spec start_link(module(), map()) -> {ok, pid()} | {error, term()}.

Start a worker for one adapter.

Opts takes root (a root id the reaper was started with, scratch when left out), timeout, trusted and a limits map merged over the defaults. Everything in it is also handed to Adapter:artifact/1.

start_link(Name, Adapter, Opts)

-spec start_link(gen_server:server_name(), module(), map()) -> {ok, pid()} | {error, term()}.

stop(W)

-spec stop(gen_server:server_ref()) -> ok.

submit(W, Request)

-spec submit(gen_server:server_ref(), request()) ->
                {ok, reference()} | {error, wasm_worker_error:worker_error()}.

Accept a request, and reply once the guardian is ready.

Ready means the durable record is written and the request directory exists, in that order: creating the directory first leaves a window where a worker and guardian death together leaves a directory no record names and no reaper will ever find. Intent before action, and it costs nothing extra because the record had to be written anyway.

submit(W, Source, Context)

-spec submit(gen_server:server_ref(), binary(), term()) ->
                {ok, reference()} | {error, wasm_worker_error:worker_error()}.

submit/2 with #{source => Source, context => Context}, as run/3.

terminate/2

withdraw_waiter(W, Ref, Token)

-spec withdraw_waiter(gen_server:server_ref(), reference(), reference()) ->
                         ok | {ok, outcome()} | {error, wasm_worker_error:worker_error()}.

Release the waiter slot after a finite await/3 gave up, and settle the race.

If the outcome was already sent to the abandoning caller this answers {ok, Outcome} and the caller takes it; otherwise the slot is simply free. A withdraw naming a token that is not the current waiter is ok and changes nothing.