wasm_keeper (wasm v0.16.0)
View SourceThe authority on who still holds a shared resource.
You do not call this. It is what makes wasm:destroy/1, wasm_memory:free/1
and a process exiting agree with one another about when a memory's pages go
back to the node.
Where things are
| you want | look at |
|---|---|
| reserve pages for a new memory, table or heap | reserve/4 |
| add, remove or move holders | acquire/3, release/2, release_all/1, transfer/3 |
| an instantiation that failed part way | discard/1 |
| per-holder page caps | set_limit/2, build_limit/2, total_of/1 |
| growing a memory in two stages | grow_begin/4, grow_commit/3, grow_abort/2 |
| extending a restored memory's arena | arena_begin/4, arena_commit/3, arena_abort/2, ack/2 |
| charging a GC heap for its tables | reconcile/2, reconcile/3 |
| snapshot images and their byte budget | image_reserve/3, image_live/1 |
| a holder's process dying | handle_info/2 |
| finishing or undoing a transaction after a restart | init/1, recover_transactions/1 |
| diagnostics | charge_of/1, holders_of/1, resources/0 |
Why a holder set and not a count
A count cannot tell two releases by one holder from releases by two. Destroy an instance twice, or destroy one that imported the same memory through two import slots, and a count goes down twice for one holder: the node's page counter fell below zero, wrapped to 2^64-1, and refused every allocation on the node for the rest of its life.
So a resource is keyed by a stable id and holds a set of holder tokens. Removing a token that is not there is a no-op, which is what makes a double release harmless, and the resource is reclaimed when the set empties.
| token | held by | removed by |
|---|---|---|
{instance, Id} | an instance that created or imported the memory, table or global | wasm:destroy/1, or its builder exiting |
{process, Pid} | a standalone resource | wasm_memory:free/1, or Pid exiting |
manual | a standalone thread-shared memory | wasm_memory:free/1 only |
{build, Ref} | an instantiation still in progress | transfer/3 on success, discard/1 on failure, or its builder exiting |
The manual token is what keeps the documented guarantee that a shared memory
outlives the process that made it: nothing about a process exiting removes it.
Why death and not only exceptions
A process killed with exit(Pid, kill) runs no cleanup, and that is the
documented behaviour of a worker timeout. So every token carries the process
whose death releases it, and the keeper monitors that process. Explicit release
stays the fast path; the monitor is what makes the model true when there is no
chance to be explicit.
Why the transaction
The node-wide page counter in wasm_engine is a fast unsynchronised read. It is
mutated only here, inside a call, together with the registry row that says who
the pages belong to. Reserving pages in the caller and registering the holder
afterwards is exactly how the counter and the registry come apart: die in
between and the pages are charged to nobody.
Growth, in two stages
Allocating chunks is not cheap and must not happen inside the serialised
callback, or one large growth would stall every release, every rollback and
every other memory's growth behind it. So the keeper validates and reserves,
the grower allocates, and the keeper commits the chunk tuple and the published
size together. Concurrent growers queue rather than being refused, because
memory.grow returning -1 is observable to the module and must mean the budget
really was exhausted.
The registry, not the caller's possibly stale handle, is the authority for how
many pages a resource has. That is why release/2 releases the size the memory is
now rather than the size the handle was made at.
One row, one write
Every change to what a memory owes is a single ets:insert of its row, and
the row carries the transaction in flight with it: a growth or an arena
extension, named by the operation id its caller made. A keeper killed between
two steps therefore leaves either the old row or the new one, and a restart
finishes or undoes the transaction from what the row says. The node counter
and the snapshot byte counter are caches of the rows, rebuilt at every start.
A memory owes two things. Its logical pages are what the guest sees, and
what max_memory_pages and the declared maximum bound. Its charged pages
are what is allocated: the page table of an image, its growth chunks and its
arena of private pages. The node budget counts the second.
Summary
Types
What reclaiming this resource means once the last holder is gone.
A resource's stable identity, minted here so it exists before the resource does. Reserving pages under an id the caller cannot yet have computed is what keeps the reservation and the registration in one transaction.
A holder of a resource. Removing one that is absent is a no-op.
Functions
Forget the outcome kept for the caller's operation OpId, now that it has
the answer. Kept until then so a caller retrying after a lost reply gets its
own result back, whatever has happened to the memory since.
Add a holder to a resource that already exists.
Give back arena extension OpId without publishing it.
Make sure the memory's arena has Target chunks, as operation OpId. The
caller names the published length it saw and the pages chunks from there to
Target cost. covered when another writer already published them,
{changed, Have} when the length moved and the cost has to be worked out
again, and {ok, Have} when the caller is to allocate chunks Have + 1..Target
and commit them.
Publish arena extension OpId. Never replaces a published tuple.
set_limit/2 for a build token, without a round trip of its own.
Pages currently reserved for a resource, or 0 if it is gone.
Release everything the calling process holds under Token.
Create the registry table if it is not there.
Give back growth OpId without publishing it. Always ok once answered.
Claim the right to grow Resource by Delta, up to Ceiling pages, as
operation OpId.
Publish growth OpId: the chunk tuple, then the size, then the end of the
transaction. Answers the size before the growth, or aborted when a restart
found the grower gone and gave the growth back, or stale when this memory
has no such operation.
The holders of a resource, for tests and diagnostics.
Whether an image is registered and not being reclaimed.
Charge an image's Bytes to the node's snapshot budget and register it, held
by Owner under {snapshot, Id}. The image is reclaimed, and its bytes given
back, when that holder has gone and no memory restored from it remains.
Charge a heap for what its tables currently hold.
As reconcile/2, refusing as though Extra words were already written.
Remove a holder. The resource goes when the set empties.
Remove several holders in one step, as release/2 does each of them.
Reserve Pages and register Token as the first holder, in one step.
How many resources are registered. Diagnostics.
Cap how many pages one holder may reach in total.
Start the supervised keeper, or adopt the one that is already there.
Pages a holder holds across every memory it can reach. Diagnostics.
Move every token From holds onto To, atomically.
Types
-type meta() :: {memory, undefined | reference(), undefined | atomics:atomics_ref(), undefined | reference(), undefined | resource(), {non_neg_integer(), pos_integer()}} | cell | {heap, ets:tid(), ets:tid()}.
What reclaiming this resource means once the last holder is gone.
cell is a row in the shared store keyed by the resource's own identity, which
is what a table's contents and a shared global's value are. Minting the
identity here and using it as the row key means there is one name for the
thing, not two that have to be kept in step.
-type resource() :: reference().
A resource's stable identity, minted here so it exists before the resource does. Reserving pages under an id the caller cannot yet have computed is what keeps the reservation and the registration in one transaction.
-type token() :: {instance, reference()} | {process, pid()} | {build, reference()} | {snapshot, reference()} | manual.
A holder of a resource. Removing one that is absent is a no-op.
Functions
Forget the outcome kept for the caller's operation OpId, now that it has
the answer. Kept until then so a caller retrying after a lost reply gets its
own result back, whatever has happened to the memory since.
-spec acquire(resource(), token(), pid() | none) -> ok | {error, gone | instance_limit | keeper_unavailable}.
Add a holder to a resource that already exists.
{error, gone} means the last holder released it before you got here, which an
importer has to treat as a link failure rather than as a memory it may use.
Give back arena extension OpId without publishing it.
-spec arena_begin(resource(), reference(), pos_integer(), {non_neg_integer(), non_neg_integer()}) -> covered | {ok, non_neg_integer()} | {changed, non_neg_integer()} | {done, term()} | {error, limit | gone | keeper_unavailable}.
Make sure the memory's arena has Target chunks, as operation OpId. The
caller names the published length it saw and the pages chunks from there to
Target cost. covered when another writer already published them,
{changed, Have} when the length moved and the cost has to be worked out
again, and {ok, Have} when the caller is to allocate chunks Have + 1..Target
and commit them.
-spec arena_commit(resource(), reference(), tuple()) -> ok | aborted | stale | {error, keeper_unavailable}.
Publish arena extension OpId. Never replaces a published tuple.
-spec build_limit(token(), non_neg_integer() | infinity) -> ok.
set_limit/2 for a build token, without a round trip of its own.
Kept in the calling process and carried by the next reserve/4 or acquire/3
under the same token, which is every way a build takes its first page, so the
ceiling is in place before anything it bounds. transfer/3 and discard/1
forget it. Only the process that builds may use it: the ceiling travels with
that process's own calls.
-spec charge_of(resource()) -> non_neg_integer().
Pages currently reserved for a resource, or 0 if it is gone.
-spec discard(token()) -> ok.
Release everything the calling process holds under Token.
What a build transaction is rolled back with. A ledger threaded through the build is lost the moment it throws, because the exception carries the error and not the newest value from the abandoned stack; the keeper holds it instead, so there is something left to roll back.
-spec ensure_table() -> ok.
Create the registry table if it is not there.
wasm_sup calls this so the table belongs to the supervisor rather than to the
keeper: a keeper restart then finds its state where it left it instead of
starting from an empty registry with every resource on the node unaccounted
for. The table is public so the keeper writes to it directly, which keeps the
supervisor off a path anything waits on.
Give back growth OpId without publishing it. Always ok once answered.
-spec grow_begin(resource(), reference(), non_neg_integer(), non_neg_integer()) -> {ok, non_neg_integer()} | {done, term()} | {error, exceeds_max | limit | instance_limit | gone | keeper_unavailable}.
Claim the right to grow Resource by Delta, up to Ceiling pages, as
operation OpId.
Answers the size before the growth. Every holder's ceiling and the node budget
are checked, and the chunks the growth needs are charged, before the answer.
Asking again with the same OpId answers the same: a caller that lost the
reply to a keeper restart resumes its own transaction rather than queueing
behind it. Concurrent growers of one memory queue rather than being refused.
-spec grow_commit(resource(), reference(), tuple()) -> {ok, non_neg_integer()} | aborted | stale | {error, keeper_unavailable}.
Publish growth OpId: the chunk tuple, then the size, then the end of the
transaction. Answers the size before the growth, or aborted when a restart
found the grower gone and gave the growth back, or stale when this memory
has no such operation.
The holders of a resource, for tests and diagnostics.
Whether an image is registered and not being reclaimed.
-spec image_reserve(non_neg_integer(), pid(), reference()) -> {ok, resource()} | {error, wasm_error:error()}.
Charge an image's Bytes to the node's snapshot budget and register it, held
by Owner under {snapshot, Id}. The image is reclaimed, and its bytes given
back, when that holder has gone and no memory restored from it remains.
-spec reconcile(resource(), non_neg_integer() | infinity) -> ok | {error, limit | instance_limit | exceeds_max | gone | keeper_unavailable}.
Charge a heap for what its tables currently hold.
The measurement happens here, inside the callback that applies it, because a caller that measures and then calls has already lost: two processes sharing a linked store can interleave so that an older, smaller sample lands after a newer, larger one and releases the pages of rows that still exist.
Answers {error, limit}, {error, instance_limit} or, for a finite Ceiling,
{error, exceeds_max} when what the store holds is past a ceiling. The charge
is still recorded: the rows exist whether or not a ceiling likes them, and
refusing to write down memory that has already been spent is how growth became
invisible. Recording it is a fact; the error is a decision about whether the
guest may continue.
-spec reconcile(resource(), non_neg_integer() | infinity, non_neg_integer()) -> ok | {error, limit | instance_limit | exceeds_max | gone | keeper_unavailable}.
As reconcile/2, refusing as though Extra words were already written.
What is recorded is still what the tables hold. Extra moves only the refusal,
so a caller about to write one very large row can be told no before the row
exists rather than after: a store is measured, and a measurement cannot see what
has not happened yet. One struct.new_default of a hundred thousand fields
walked through a one-page ceiling that way.
Remove a holder. The resource goes when the set empties.
Always ok: releasing a token that is not held, or a resource that is already
gone, is the case this exists to make harmless.
Remove several holders in one step, as release/2 does each of them.
What wasm:destroy/1 uses: an instance holds a memory, its tables and its
mutable globals, and releasing them one call at a time put that many round
trips through this process on every request a worker served.
-spec reserve(non_neg_integer(), meta(), token(), pid() | none) -> {ok, resource()} | {error, limit | instance_limit | gone | keeper_unavailable}.
Reserve Pages and register Token as the first holder, in one step.
The Owner is the process whose death releases the token, or none for a
manual token. You get back the resource's identity, which every later call
names it by. gone answers a memory to be laid over an image that is no
longer registered.
-spec resources() -> non_neg_integer().
How many resources are registered. Diagnostics.
-spec set_limit(token(), non_neg_integer() | infinity) -> ok.
Cap how many pages one holder may reach in total.
max_memory_pages was documented as a per-instance ceiling and enforced
nowhere: a module declaring three hundred pages instantiated under a limit of
two hundred and fifty-six. Checking it where a memory is created would not have
been enough either, because an imported memory is never created by the instance
that imports it.
So the ceiling belongs to the holder, and every way of becoming one goes through this module. A shared memory therefore grows only as far as its strictest holder allows, which is a consequence worth stating rather than a rule of its own: the alternative is one instance growing a memory past a limit another instance was promised.
Start the supervised keeper, or adopt the one that is already there.
A memory can be made before the application is started, so a keeper may already exist by the time the supervisor gets here. Replacing it would throw away the monitors that are the only record of who holds what, and the new keeper would come up believing the node held nothing. So it is adopted instead: linked into the supervision tree, and asked to name the supervisor as its table's heir so a later crash does not take the registry with it.
-spec total_of(token()) -> non_neg_integer().
Pages a holder holds across every memory it can reach. Diagnostics.
Move every token From holds onto To, atomically.
Used when a build succeeds: the entries a builder accumulated become the instance's, without a window in which they belong to neither.