wasm_worker_reaper (wasm v0.16.0)

View Source

Who cleans up after a request when the process that owned it is gone.

Internal. The wasm application runs one per node, under wasm_worker_sup, which says where it keeps its files; wasm_script_worker refuses a request when none is running. wasm_script_worker:cleanup_stats/0 and wasm_script_worker:cleanup_requests/0 are the supported way to look at it.

Where things are

you wantlook at
starting, and sweeping what a previous run leftstart_link/1, init/1, sweep/1, sweep_root/3
reserving a request before anything existsreserve/4
registering, withdrawing and handing over cleanupregister/2, withdraw/2, transfer/3, finish/1
a guardian, owner or steward going downguardian_down/2, owner_down/3, steward_down/2
queueing cleanup jobs within capacityschedule/2, pump/1, start_job/2
what a cleanup job runs, and its time boundjob/4, run_cleanup/3, run_bounded/2
whether a job may still act on a requestauthorise/2, generation/0
writing and removing journal recordsjournal/3, writer/1, encode_record/2
reading a record back at a restartdecode_record/3, adopt_or_orphan/3
asking a live guardian whether it still owns a requestask/1, retry_handshake/2
a cleanup callback that will not finishquarantine/2
the operator viewstats/0, requests/0

Why a process and not a table

A worker's guardian owns the request's directories and its registered cleanup actions, and the guardian can die. An ETS table with the worker as heir is the wrong shape twice over: heir fires when the owner dies, so a worker-owned table survives exactly the failure it is not needed for and does nothing about the guardian's. And deferring the sweep to the worker's next request leaks for as long as that worker is idle, which for a lightly used tenant has no bound.

So the reaper outlives both. It holds the registry, it monitors every guardian, and on a DOWN with work outstanding it spawns a job and goes straight back to its loop. It never runs a cleanup callback itself: it is a singleton, and an adapter whose wasm_worker_adapter:cleanup/1 hangs would otherwise stop registration and recovery for every worker on the node.

Surviving its own death

The registry is memory, so it also writes a journal, one directory per root, one record per live request. Three properties of that journal are load-bearing and each is the smallest honest option rather than the strongest-sounding one:

what it iswhat it is not
durabilityBEAM-crash: the record is written and renamed before the reservation is acknowledgedhost-crash durability: the record is not synced, and a start removes every request directory no record names
what is durableownership and recovery intentthe cleanup lifecycle, which would put a filesystem write on every state transition
identitya minted binary request idan Erlang reference() written down

The record is a header plus operations:

v1 <incarnation-hex> <generation> <guardian-pid> <request-id-hex>
remove_tree <root-id> <escaped-relative-path>

It holds allowlisted operations, never code. A manifest of {M, F, A} is a file naming host functions to call, sitting one directory-permission mistake away from a guest. And it is deliberately not binary_to_term/1: that materialises atoms before any structural check can reject the record, which is a node-wide unreclaimable leak, and the file sits exactly where an attacker who got that far would plant one. Every field here is a number, a hex string, a pid literal or a verb from a fixed table, so decoding yields an atom that already existed or fails.

Nothing slow happens in this process

Every request on the node goes through here, so the reaper does no file I/O of its own. Records are written, renamed and removed by a few journal writers, chosen by request id so one request's writes stay in order; the writer answers the reservation once its record is in place. A cleanup job reports in its exit reason whether everything it named is gone. A DOWN is one lookup, and the operator view is rebuilt at most every 50 ms rather than on every message.

Recovery asks before it acts

A replacement reaper that simply replayed what it found would delete the directories out from under a request that is still running. So each record names its owner, and a restart sorts what it finds:

meaningaction
incarnation differsthe node restarted, no pid means anythingorphan, replay
matches, pid deadthe guardian died with the reaperorphan, replay
matches, pid alive, handshake confirmsstill runningadopt, replay nothing
matches, pid alive, handshake deniesa reused pidorphan, replay
matches, pid alive, no answerunknownpending: monitor, retry, never replay

A timeout is not a denial. A guardian that is descheduled, mid-GC or behind a full mailbox is a live guardian that happens to be slow. Only an explicit denial or a DOWN proves orphaning; silence stays unknown, and an entry that is still alive and silent when the retries run out goes to held rather than being replayed. Leaking a directory is recoverable and deleting a running request's mounts is not, so ambiguity always resolves towards doing nothing.

What survives what

guardian dies, reaper livesreaper dies, guardian livesboth die
remove_treereaper's registryguardian's mirrorjournal
a fun actionreaper's registryguardian's mirrorlost
Adapter:cleanup/1reaper's registryguardian's mirrorlost

An adapter holding something it cannot afford to leak across a reaper crash expresses it as a recover_op(). Anything else is a best-effort release that a supervised reaper will almost always perform.

Summary

Functions

Whether a reaper is running.

Ask whether a job spawned under Gen may still act on Id.

Drop a request whose guardian completed cleanly and cleaned up itself.

This reaper's generation. Incremented by every start.

The node's incarnation, which outlives a reaper restart and not a node restart.

Register a cleanup action, LIFO, and say what happened if it could not be.

Every reservation this reaper holds, with the process that owns it.

Claim capacity and durably record the intent to clean up, before anything exists.

The root ids this reaper was started with.

Start the reaper, sweeping and reconstructing from whatever it finds.

Start the reaper with what only its supervisor may say.

Counts per state, for the conformance kit and for an operator.

Hand the adapter's state to the registry. Kernel-only.

What an operation answers when its reaper is gone, run in the caller.

Drop a registered action, for a caller that released the thing itself.

Types

action()

-type action() :: wasm_worker_adapter:action().

recover_op()

-type recover_op() :: wasm_worker_adapter:recover_op().

request_id()

-type request_id() :: wasm_worker_adapter:request_id().

root_id()

-type root_id() :: wasm_worker_adapter:root_id().

token()

-type token() :: wasm_worker_adapter:token().

Functions

alive()

-spec alive() -> boolean().

Whether a reaper is running.

wasm_script_worker checks this at every submit, not only when it starts: the reaper can die at any point afterwards, and a request whose cleanup would have no owner should not begin.

authorise(Id, Gen)

-spec authorise(request_id(), pos_integer()) -> ok | {error, stale}.

Ask whether a job spawned under Gen may still act on Id.

Links are not ordering: a supervisor can see the reaper's DOWN and start a replacement before the old jobs have processed their parent's exit signal. So acting on a record requires authorisation from the currently registered reaper, which checks a generation it holds in memory and answers serially. A stale job reaches the replacement, whose generation no longer matches, and is refused.

This narrows the window and does not close it: a job authorised just before its reaper died can still be descheduled and do its filesystem work afterwards. That is why every action is required to be concurrent-safe as well as idempotent.

finish(Id)

-spec finish(request_id()) -> ok.

Drop a request whose guardian completed cleanly and cleaned up itself.

generation()

-spec generation() -> pos_integer().

This reaper's generation. Incremented by every start.

handle_call(Msg, From, St0)

handle_cast(Msg, St0)

handle_info/2

incarnation()

-spec incarnation() -> binary().

The node's incarnation, which outlives a reaper restart and not a node restart.

It has to be exactly that lifetime, because it is what decides whether a pid in a record means anything. Generated per reaper start, a supervisor restart would make every live request look orphaned and get its directories deleted. So it is node-owned state in persistent_term, created by whichever reaper finds it absent and never rewritten.

init/1

register(Id, Action)

-spec register(request_id(), action()) ->
                  {ok, token()} | {error, wasm_worker_error:worker_error(), released | cleanup_failed}.

Register a cleanup action, LIFO, and say what happened if it could not be.

Three outcomes, and the caller can tell them apart:

meaning
{ok, Token}recorded; the registry owns it
{error, E, released}not recorded, but the action ran to completion
{error, E, cleanup_failed}not recorded, and the action hung or raised

The middle one exists because a register that returns an error having done neither leaks exactly the resource the caller allocated one line earlier. The last one is the honest case: nobody owns that resource now. It cannot be journaled either, because the reaper is the journal's only writer and this state is reached precisely when the reaper is unreachable, so it is logged and counted and that is all.

requests()

-spec requests() ->
                  [#{id := request_id(),
                     state := atom(),
                     guardian := pid(),
                     delivered := boolean(),
                     actions := non_neg_integer()}] |
                  {error, wasm_worker_error:worker_error()}.

Every reservation this reaper holds, with the process that owns it.

Operator-facing rather than test-only: a reservation that ends in held stays there until a late answer or a DOWN, deliberately, and the way to resolve one is to look at what is holding it and kill that guardian if it really is stuck. delivered says whether the adapter's state has reached the registry yet, and so whether wasm_worker_adapter:cleanup/1 has an owner.

reserve(Id, Guardian, Root, RelPath)

-spec reserve(request_id(), pid(), root_id(), binary()) ->
                 {ok, file:filename_all()} | {error, wasm_worker_error:worker_error()}.

Claim capacity and durably record the intent to clean up, before anything exists.

Called by the guardian before it creates any directory. The record naming RelPath is written and renamed before this returns, so a crash immediately afterwards leaves a directory a replacement reaper can find. A remove_tree naming a path that was never created is a no-op, which is what idempotence already required, so the ordering costs nothing and closes the window completely.

Answers with the absolute directory the request owns, so the guardian does not have to be told separately where its root is and cannot disagree with the reaper about it.

Returns {error, cleanup_saturated} when live + pending + held + queued + running is at capacity. A host under load gets a refusal it can retry rather than a leak it cannot see.

roots()

-spec roots() -> [root_id()] | {error, wasm_worker_error:worker_error()}.

The root ids this reaper was started with.

setting/2

setting_keys()

start_link(Roots)

-spec start_link(#{root_id() => file:filename_all()}) -> {ok, pid()} | {error, term()}.

Start the reaper, sweeping and reconstructing from whatever it finds.

Roots maps a root id to a directory. A worker names one of those ids, and every path in the journal is relative to it, so a restarted reaper knows where to sweep without having to discover it. A record naming a root this reaper does not have configured is left alone and logged, never guessed at.

start_link(Roots, Opts)

-spec start_link(#{root_id() => file:filename_all()}, map()) -> {ok, pid()} | {error, term()}.

start_link(Roots, Opts, Internal)

-spec start_link(#{root_id() => file:filename_all()}, map(), #{generated => [root_id()]}) ->
                    {ok, pid()} | {error, term()}.

Start the reaper with what only its supervisor may say.

#{generated := Ids} names the roots this reaper was given a directory of its own for, which it removes at a clean shutdown when nothing is left in them. It is a separate argument, not a key in Opts, so that no configuration can mark a directory somebody else owns for deletion. wasm_worker_sup is the only caller.

stats()

-spec stats() -> map() | {error, wasm_worker_error:worker_error()}.

Counts per state, for the conformance kit and for an operator.

stop()

-spec stop() -> ok.

terminate/2

transfer(Id, Mod, AdapterState)

-spec transfer(request_id(), module(), term()) -> ok | {error, wasm_worker_error:worker_error()}.

Hand the adapter's state to the registry. Kernel-only.

Not exposed to adapters, and that is an ownership fix rather than a simplification. If an adapter could transfer and its runner then died before delivering an adapter_state(), the transferred actions would run only "if a state was delivered" and none ever was, so nothing would own them. The kernel transfers once, after the guardian holds the complete state, which makes "transferred" and "a state was delivered" the same event.

unreachable_operation/1

-spec unreachable_operation(wasm_cleanup_steward:operation()) ->
                               {error, wasm_worker_error:worker_error()} |
                               {error, wasm_worker_error:worker_error(), released | cleanup_failed}.

What an operation answers when its reaper is gone, run in the caller.

The steward calls this when a forwarded operation's reaper pid has died, so the answer is what the guardian would have got had it called the reaper directly and found it absent: a register runs the action bounded and reports released or cleanup_failed, and a withdraw or transfer names the missing owner.

withdraw(Id, Token)

-spec withdraw(request_id(), token()) -> ok | {error, wasm_worker_error:worker_error()}.

Drop a registered action, for a caller that released the thing itself.