Concepts

View Source

This page defines the words every other page uses, in the order you meet them. Read it once before the guides. Each term links to the page that explains it in more detail. If you are new to Erlang, the glossary at the end also defines the Erlang words, such as process, supervisor and atom.

Who runs what

Four words explain the rest:

wordwhat it is
hostErlang/OTP: your application, which provides resources and permissions
guestthe WebAssembly code: the program that runs inside the host
modulea packaged program: validated code, plus the list of what it imports and exports
instancea running copy: one module with its own memory and state

The host creates an instance from a module and supplies the guest's imports.

your application (the host)
  |
  +-- module          loaded once, shared, never changes
        |
        +-- instance  one running copy: its own memory, globals, tables
              |
              +-- guest code, calling back into the host through imports

Four steps from bytes to a result

decode        validate        instantiate                 run
bytes ------> module -------> checked code + imports ---> state ---> result
  1. Decode turns bytes into a module.
  2. Validate checks the module's types and structure before anything runs.
  3. Instantiate builds the instance's state and connects its imports.
  4. Run: a call runs one of the instance's exported functions.

wasm:load/1 does the first two steps once per node and keeps the result in the module cache. So load a module when your application starts, not for each request: the cache refuses new modules past a load rate and a resident cap (see the glossary). See Getting started and Modules are loaded once.

The guest asks, Erlang decides

An export is a guest function that the host can call.

An import is an operation that the host provides. The guest names the operation, and the host supplies the code that does it. If the host does not supply an import, the guest cannot do that operation at all. So an import is a capability: a permission that the host grants by supplying the import. See Host functions.

WASI is a standard set of imports for files, clocks, random data and networking. You grant each one by name, for example a directory or a network address. Anything you do not grant does not exist for the guest. See WASI preview 1.

Linear memory is the guest's byte array. The guest can make it larger while it runs. Numbers pass directly as call arguments. Strings and binaries pass through memory. See Pass bytes.

Guest errors are returned as values

Nothing a guest does makes a call raise an exception. A malformed binary, a module that fails validation, a trap and a limit that runs out all come back as {error, Error}. So a guest that fails never crashes the process that called it. Error is a map with four keys:

keywhat it holds
classone of five atoms: malformed, invalid, link, trap, exhaustion
kindan atom that names this failure, such as out_of_fuel; your code matches on it
msgthe message the WebAssembly specification gives, as a binary
ctxa map of details for diagnosis, such as the index of the function

This is what a call that ran out of fuel returns:

{error, #{class => exhaustion, kind => out_of_fuel,
          msg => ~"out of fuel", ctx => #{func => 0}}}

wasm:format_error/1 turns the map into one line of text for your logs:

exhaustion: out of fuel (out_of_fuel) #{func => 0}

Match on class and kind, never on msg:

case wasm:call(Inst, ~"run", []) of
    {ok, Results} ->
        {done, Results};
    {error, #{kind := out_of_fuel}} ->
        too_much_work;
    {error, #{class := trap} = E} ->
        logger:warning("guest trapped: ~ts", [wasm:format_error(E)]),
        trapped;
    {error, E} ->
        {failed, wasm:format_error(E)}
end.

wasm_script_worker answers with the same map shape, with classes of its own (worker, adapter and runtime), listed in wasm_worker_error. A few mistakes in your own code do raise, such as a malformed network grant. Design principles lists them.

Limits, fuel and deadlines

Limits are the maximum values for one instance: fuel, call depth, memory pages, host calls, heap size and a deadline. Start from wasm_limits:untrusted/0. Configuration lists each one with its default.

Fuel is a budget of work, not of time: the guest stops after it has done that much work. A host function that blocks uses no fuel, and compiled code does not count it.

The BEAM shares the CPUs between processes by itself. Each scheduler, one thread per CPU core, runs a process for a fixed number of reductions (units of work the BEAM counts), then switches to another process. So a guest that loops forever does not stop your other processes, but nothing stops the guest either. A deadline does that. See Limit the work and the time.

Put an instance in its own process

An owner is the process responsible for cleanup. Put an instance in a process of its own, a worker, and a timeout can kill it. A call made directly runs in your own process, and nothing can interrupt it. A worker is not a second engine. It is an ordinary process that owns an instance. See Stop a runaway and Workers. A component that keeps its state between messages lives in a process of its own too, an actor, which a supervisor restarts with a fresh instance: see Actors.

Deadlines and cleanup stay outside the guest

To run code that arrives with a request, the worker kernel, wasm_script_worker, gives each request its own processes:

caller ---message---> worker (the API, one request at a time)
                        |
                        +-- guardian   enforces the deadline, owns the files
                        |     |
                        |     +-- runner   executes the one request
                        |
                        +-- reaper     node-wide: cleans up after requests

An adapter teaches the kernel one language: how to start it, how to give it a script, and how to read the result. The included adapters cover JavaScript, Python and Lua. To write one for another language, implement the behaviour wasm_worker_adapter. See Run JavaScript and The adapter contract.

A command is a guest that runs main once and exits. A reactor is a guest that exports functions and stays ready between calls. Snapshots and the fast language paths need a reactor.

Two execution modes

start by interpreting              compile hot code later
validated wasm --> Core Erlang --> loaded BEAM module

Every instance starts interpreted: the runtime reads the guest's instructions one by one and does what each says. The compiled tier is off by default. When you turn it on, it translates the functions that a module calls most into BEAM code. It does this through Core Erlang, an intermediate language that the Erlang compiler already reads. The compile takes time before the guest runs faster, and compiled code cannot count fuel. See Turn on the compiled tier.

Start once, restore a fresh copy per request

initialized instance --capture--> image --restore--> fresh instance
                                  (memory, globals, tables)

A snapshot is a saved copy of a guest after it has started, used as a template. Restoring it gives a fresh instance that does not need to start again. So an interpreter that takes seconds to start costs only milliseconds per request. A snapshot is not a paused process.

The image is what a snapshot saves: the guest's memory, globals and tables, kept in memory or in a file. A restore does not copy the image. Every instance restored from one image reads its pages in the image, and copies a 4 KiB page only when it writes to it. See Restore a snapshot and Snapshots.

Every restore starts from the same bytes. So a random seed or a clock time that the guest read before the capture is the same in every request. See Snapshots are deterministic.

Snapshots reduce the cost of starting a guest. The compiled tier reduces the cost of running it. They solve different problems, and you can use them together or apart.

The life of a request

acquire                       use                      release
accept, reserve capacity  --> call before a deadline --> cleanup must be proved

Each request goes through three steps. First it is accepted and its resources are reserved. Then the guest is called and must finish before a deadline. Last, everything the request used must be cleaned up, and the runtime keeps track of that cleanup until it is done. See Worker internals.

Glossary

Every term the other pages use, with the page that explains it. The Erlang terms come first, for readers new to Erlang. The words that only the internals pages use come last.

Erlang terms

termmeaningread
atoma named constant, such as ok or trap. The node keeps every atom forever and has a fixed maximum, so the runtime never turns guest data into atomsDesign principles
behaviouran Erlang interface: the list of callback functions a module must export to play a given roleWriting an adapter
BEAMthe Erlang virtual machine, which runs Erlang code; "BEAM code" is code compiled for itArchitecture
ETS tablean in-memory table that belongs to one process and is deleted when that process exitsHold modules and instances
heapthe memory of one Erlang process, where its data lives; each process has its ownTuning
link, trap exitsa link connects two processes so that when one exits, the other is told or exits too; a process that traps exits receives a message instead of exitingHold modules and instances
mailboxthe queue of messages a process has received; it handles them one at a timeUsing workers
NIFa "native implemented function": C code loaded into the BEAM and called like an Erlang functionDesign principles
nodeone running BEAM, with all its processesArchitecture
OTP applicationa packaged Erlang component that starts and stops as a unit; this runtime is the application wasmHold modules and instances
processa lightweight Erlang thread with its own memory and mailbox; it can be killed without affecting the othersUsing workers
reductionthe unit of work the BEAM counts to share the CPU: a process runs for a fixed number of reductions, then another process gets its turn. It is not a time limitLimits, fuel and deadlines
schedulerone BEAM thread that runs processes, usually one per CPU core; it switches between processes so that no process keeps a coreLimits, fuel and deadlines
supervisor, supervision treea process that starts other processes and restarts them when they crash; supervisors nested inside each other form a treeHold modules and instances
wordthe BEAM's unit of process memory: 8 bytes on a 64-bit systemThe compiled tier

Runtime terms

termmeaningread
actora process that owns one component instance for its whole life and handles typed messages one at a time; started with wasm_actor:start_link/2Actors
adaptera module that teaches the worker kernel one language, by implementing wasm_worker_adapterWriting an adapter
async ABIthe Canonical ABI's async func, stream and future; called with wasm_component:call_async/4Components
baseline, fullthe two compile levels: full code runs faster, baseline code compiles fasterThe compiled tier
Canonical ABIthe rules for how a component-level value (a string, a record, a handle) is stored in a core module's memory and read backComponents
capabilitya permission granted by supplying an import, such as a directory or an addressWASI preview 1
class, kindthe two fields that classify an error: one of five classes (malformed, invalid, link, trap, exhaustion) and a kind your code can match onabove
code cachecompiled BEAM modules saved on disk under code_cache_dir, so a restart does not compile them againThe compiled tier
command, reactora guest that runs main once and exits, compared with one that exports functions and stays readyProducing a guest module
compiled tiertranslating the functions a guest runs most into BEAM code, through Core ErlangThe compiled tier
componenta Component Model binary: core modules plus typed interfaces, instantiated with wasm_componentComponents
content hasha checksum of a module's bytes; two identical files have the same hash, so the runtime can reuse its workHold modules and instances
Core Erlangan intermediate language inside the Erlang compiler; the compiled tier generates itThe compiled tier
deadlinethe wall-clock time a call may take; the process that owns the instance kills it when the time passesUsing workers
export, importa guest function the host can call, and an operation the host supplies to the guestabove
fuela work budget: the guest stops after it has done that much work; compiled code does not count itabove
guardianthe process that owns one worker request: its deadline, its files and its runnerWorker internals
host, guestErlang, and the WebAssembly code it runsabove
imagewhat a snapshot saves: the guest's memory, globals and tables, in memory or in a file. A restore reads it without copying it, and workers with the same adapter and options share oneSnapshots
interpretedrun by the interpreter, which reads the guest's instructions one by oneThe compiled tier
lift, lowerfor a component: to lower is to turn an Erlang value into what the core code reads (numbers, and bytes in its memory); to lift is to turn the core code's result back into an Erlang value. wasm_component:call/4 does both, following the signature you give itComponents, Component internals
limitsthe maximum values for one instance: fuel, memory pages, call depth, host calls, heap and a deadline; start from wasm_limits:untrusted/0 or trusted/0Configuration
linear memorythe guest's byte array, which it can grow; measured in pages of 64 KiBMemory
load ratehow many new modules the module cache decodes in one second: 50 unless you set max_module_loads_per_second. Past it, wasm:load/1 answers {error, {load_rate_exceeded, 50}}. Loading bytes that are already in the cache is not countedModules are loaded once
module, instancevalidated code, and one running copy of it with its own stateabove
module cacheone decoded and validated copy of each module per node, found by its content hashHold modules and instances
ownerthe process responsible for an instance or an image; when it exits, what it holds is releasedHold modules and instances
pagea linear-memory page is 64 KiB; a snapshot image is copied in smaller pages of 4 KiBMemory
page budgetthe maximum number of linear-memory pages for the whole node, kept by wasm_engineMemory
preview 1, 0.2, 0.3the WASI versions: preview 1 for core modules, 0.2 and 0.3 for componentsWASI preview 1, WASI 0.3
profilethe profile option of wasm:instantiate/3: plugin or script, one name that sets the compile options for a kind of workload. Two other uses of the word are different things: script_v1 is the protocol the shipped adapters speak, and the relaxed SIMD "deterministic profile" is a term from the specificationThe compiled tier
reaperthe process, one per node, that removes what finished requests left on diskWorker configuration
resident capthe most the module cache holds at once: 256 modules (max_resident_modules) and 2 GiB (max_resident_module_bytes). Past it, a load answers {error, {too_many_modules, 256}} or {error, {module_cache_full, Bytes}}Configuration
resource, own, borrowa component-level object behind a handle; own gives it away, borrow lends it for one callComponents
resource_limitan option of wasm_component:instantiate/3: the most host resource handles a component may hold at once, and the most async calls it may have waiting. Past it, the call traps with resource_limit_reached. There is no limit unless you set oneComponent internals, WASI 0.3
restore aheada worker restoring the next request's instance while it waits for that requestTuning
runnerthe process that runs the guest for one requestWorker internals
snapshota saved copy of a guest after it started, restored as a fresh instance for each requestSnapshots
subtaskan async call from one component into another that waited before it returned: the caller goes on, and the subtask tells it later that it has returnedComponents
trapthe guest stopped on an error that the specification defines, such as unreachable; returned as a valueGetting started
WASIthe standard imports for files, clocks, random data and networkingWASI preview 1
worker, worker kernela process that owns an instance; wasm_script_worker runs one request at a time with a deadlineUsing workers

Words from the internals pages

You do not need these to use the runtime. They are here so that the internals pages read without surprises.

termmeaningread
ABI (generated code)the rules that compiled code and the interpreter both follow to work together; a code cache written under different rules is refusedThe compiled tier
arenawhere a restored memory keeps its own copies of the pages it wroteMemory
atomicsan OTP module for arrays of integers that can be changed in place; linear memory is built from themMemory
chunkone atomics array of linear memory; memory grows by adding chunksMemory
cleanup stewardthe process, one per request, that is responsible for that request's cleanup, together with the reaperWorker internals
keeper, holderwasm_keeper records which processes hold each memory, table or image (the holders), and frees it when the last holder is goneMemory
leasea word used in three internal places: an instance's hold on a slot of compiled code, a running call's shared hold on a garbage-collected object store, and the counters that let a snapshot capture prove that no call is running. You never take or give back a lease yourself; snapshotable => true only creates the last kindArchitecture, Garbage collection, Snapshots
page tablefor each restored memory, one entry per 4 KiB page, saying whether the page is still the image's or a copy in the arenaMemory
translation cachetwo entries in compiled code that remember where recently used memory pages are, so most memory accesses skip the page tableThe compiled tier

Read this next

Design principles to see why the API looks the way it does, Getting started to run a module, or Configuration for every setting.