wisp: Running WebAssembly Under containerd

A containerd shim usually does something unremarkable: it takes a few RPCs from containerd, forks a Linux process to run the container, reports the exit code and exits. wisp is a shim that doesn’t fork. When containerd starts a container with the io.containerd.wisp.v1 runtime, wisp loads the image’s payload as a WebAssembly module and runs it in a Wasmtime instance. To containerd, it’s just another runtime next to runc and runsc, handling image pull, lifecycle and stdio the same way. To the workload, there’s no Linux at all: no syscalls, no kernel, no namespaces, only a WASM guest and the small set of WASI functions it’s allowed to call.

This is the fifth small sandbox in this series, and like the others it asks where to draw the isolation boundary:

wisp is the odd one out: it removes one side of the boundary. A Linux container asks the kernel to keep the workload inside a line. A userspace kernel intercepts at the line and emulates what’s on the other side. A microVM gives the guest its own kernel and has hardware keep the two apart. wisp does none of that. WASM is a stack machine with linear memory, deterministic semantics and no concept of syscalls, so there’s no kernel inside the guest to escape to. The isolation comes from the structure of the format, not from enforcement.

Wiring this up against real containerd was easier than I expected in some places and much harder in others. This post covers both.

The shim and the engine

containerd’s shim v2 ABI is a small protocol with a lot of corners. The shim is a binary. containerd runs it once with a start subcommand to spawn a long-running server, then connects over a Unix socket and sends TTRPC calls for the rest of the container’s life: Create, Start, State, Wait, Kill, Delete, Shutdown, and a few others that don’t seem important until they bite you. Under shim v1 each container had its own shim process; v2 lets one shim serve several containers. The shim translates these calls into whatever the runtime underneath understands: runc invocations for a Linux container, runsc for gVisor, a Wasmtime instance here.

Wasmtime takes module bytes, a WASI context (env vars, args, preopened files, stdio) and a function name. It instantiates the module, calls the function, and returns a clean exit, a trap or a host-side error. A proc_exit(n) inside the guest comes back as a specific kind of trap the host can downcast to read n. A division by zero, out-of-bounds load or unreachable instruction comes back as a different kind of trap. All of these have to be mapped to containerd’s (exit_code, exited_at) shape, and the shim is where that mapping happens.

I wrote the shim against containerd-shim 0.11 (the Rust crate from containerd’s rust-extensions project, which runwasi also builds on) and wasmtime 44. The engine trait is small:

pub trait WasmEngine: Send + Sync {
    fn create(&self, cfg: &ContainerConfig) -> Result<()>;
    fn start(&self) -> Result<()>;
    fn wait(&self, timeout: Option<Duration>) -> Result<Option<ExitStatus>>;
    fn kill(&self) -> Result<Option<ExitStatus>>;
}

The first implementation, NoopEngine, sleeps for five seconds and reports exit 0. The second, WasmtimeEngine, actually runs the guest. Both sit behind the same trait, so the shim doesn’t know which one it has. After some back and forth over traps, I settled on this exit-code convention:

guest behaviour                          exit code
─────────────────────────────────────────────────
_start returns cleanly                   0
proc_exit(n) (downcast I32Exit)          n
trap (OOB, div0, unreachable, …)         1
epoch interruption from kill()           137

The last row is the interesting one. WASM has no signals, so “kill” doesn’t mean what it does in Linux. Wasmtime’s mechanism for it is epoch interruption: the engine has a counter, each store can ask to trap when the counter passes a deadline, and Engine::increment_epoch() is the only way to move it. I set the deadline to 1 when the store is created, never advance it during normal execution, and call increment_epoch() from kill. The guest then traps simply because I asked. An epoch trap looks like any other trap, so the run thread post-processes: if the engine was killed and the exit code would otherwise be 1, it becomes 137. The table stays tidy and the kill mechanism doesn’t leak into the trap path.

That was enough to run a hand-written (module (func (export "_start") (i32.const 0) (drop))) to a clean exit, and to interrupt an infinite-loop module in under five seconds. The unit tests passed, and I thought I was mostly done.

First contact with containerd

The integration test for any containerd runtime is ctr run. I installed the binary as /usr/local/bin/containerd-shim-wisp-v1 (the name containerd derives from the runtime ID by swapping the dots and turning the version suffix into a -vN tag). I built a hello-world module from a five-line Rust crate that does println!("hello"), compiled for wasm32-wasip1, and packaged it as an OCI image archive: a tar with oci-layout, an index.json and a blobs/sha256/... tree. The manifest declared os=wasi, architecture=wasm. Then:

sudo ctr -n default image import /tmp/wisp-hello.tar
sudo ctr -n default run --rm \
    --runtime io.containerd.wisp.v1 \
    wisp.local/hello-wasm:latest hello

The result: ctr: image not found. The import had succeeded and the image was immediately gone; ctr image ls didn’t show it. Re-importing with -v mentioned, in the middle of the output and without much emphasis, that the image might be filtered out. ctr image import filters by host platform by default, and a linux/amd64 host doesn’t match a wasi/wasm manifest. Adding --all-platforms fixed it. This was the first instance of a recurring theme: the common containerd tooling assumes a container looks a certain way, and a sandbox built on absence breaks a lot of those assumptions.

With the image in place, the next ctr run failed with failed to create TTRPC connection: unsupported protocol. That was the start of a long afternoon.

Two errors with one cause

A shim’s start subcommand has an unusual contract. containerd runs the shim with some flags and start; the shim must fork a long-running server, bind a Unix socket, and print the socket address on stdout. containerd reads that address from stdout, connects, and uses the connection for every later RPC. The format is one line, unix:///run/containerd/s/<hash>, with nothing before or after it. If anything else lands in containerd’s reader first, the URL parses as something else and the connection fails.

In containerd 2.x, the shim’s stderr goes into the same reader as its stdout during this start invocation. I don’t know if that’s deliberate or the abstraction has just loosened over time, but any byte written to fd 2 during start lands in the buffer containerd parses for the URL. One of the first things I’d put in main was env_logger::Builder::from_env(...).init(). Its diagnostic output, useful in development, ended up above the address line, so containerd’s parser saw something like [INFO wisp] invoked as io.containerd.wisp.v1: ...\nunix:///run/containerd/s/abc123, took the first URL-shaped thing (which wasn’t a URL), and reported unsupported protocol.

I removed the env_logger init. The next ctr run failed differently: dial unix /run/containerd/s/<hash>: connect: no such file or directory. The address was now right, but the socket didn’t exist. Same cause, different symptom.

Server mode, the long-running TTRPC mode after start, has its own logging. The containerd-shim crate’s bootstrap calls containerd_shim::logger::init, which calls log::set_boxed_logger with a writer connected to containerd’s per-container log FIFO. The log crate only allows set_boxed_logger once per process. Because I’d initialized env_logger in main before the crate’s bootstrap, the crate’s init returned SetLoggerError, bootstrap returned Err, the child died before binding its socket, and ctr dialed a path that never existed. The two failures looked nothing alike but were the same bug.

The fix was three lines:

// Don't call env_logger::init here. containerd 2.x merges stderr
// into stdout during `start` (corrupts the address), and in server
// mode the containerd-shim crate's logger::init fights us over
// log::set_boxed_logger (bootstrap fails before binding).
// Let the crate own logging.
shim::run::<WispShim>(RUNTIME_ID, None).await

I kept the clap CLI struct that describes the arguments as runnable documentation (it answers “what does containerd actually pass a shim binary?”), but main doesn’t call it. Unit tests exercise it so it can’t rot. main now hands off and stays quiet. The bug, in the end, was that I’d been too loud.

The method with a default that fails

The next run failed with Connect is not supported, before the guest got to run. This one wasn’t wiring; it was a missing method.

In containerd-shim 0.11, every method on the Task trait has a default implementation that returns Error::Unimplemented. That’s sensible: implement what you use, and the rest returns a polite “not supported” instead of crashing. The catch is that ctr run calls Task::connect right after Start, to attach to the task’s stdio before it produces output. With the default, the run aborts exactly when the guest is about to print.

wisp’s Task::connect is unremarkable:

async fn connect(
    &self,
    _ctx: &TtrpcContext,
    _req: api::ConnectRequest,
) -> TtrpcResult<api::ConnectResponse> {
    let mut resp = api::ConnectResponse::default();
    resp.shim_pid = std::process::id();
    resp.task_pid = std::process::id();
    resp.version = "wisp".to_string();
    Ok(resp)
}

There’s only one process, the shim, and the WASM guest has no PID in any sense Linux recognizes. Returning the shim’s PID for both fields is runwasi’s convention, and it’s what tools asking for the task’s PID will get.

The lesson: trait defaults can be traps. Rust wouldn’t let me forget a method with no default, and a default that calls unimplemented!() at least compiles honestly. A default of Err(Unimplemented) is friendlier and less safe. Whenever a library gives you a trait with default error implementations, check which methods the happy path actually calls.

Mounting the rootfs yourself

Now the shim spoke the protocol. The next ctr run reached WasmtimeEngine, which tried to load module.wasm from the rootfs path in the CreateTaskRequest: /run/containerd/io.containerd.runtime.v2.task/default/hello/rootfs. It was empty.

containerd doesn’t populate <bundle>/rootfs/ for the shim. The CreateTaskRequest carries a Vec<Mount> (it did in containerd 1.x too), and the shim is expected to either mount(2) each one itself or read directly from the snapshot’s underlying source. That’s reasonable decoupling, since different runtimes want different views of the layers, but every example I’d read assumed the directory was already populated.

The clean answer is to call nix::mount::mount on the overlay spec containerd sends. I took a shortcut first: containerd’s overlay mount has a lowerdir= option, and for a single-layer WASM image the layer with module.wasm is the only lowerdir entry. So resolve_rootfs parsed the options string, pulled out the lowerdir, and read module.wasm from there. Proper mount handling replaced it later (it’s in the current repo), but the shortcut got the next ctr run to find the module, and the rest of the matrix was more pressing.

The lesson from this and the previous two sections: a sandbox runtime is mostly not sandbox code, it’s glue. The Wasmtime side of wisp, the part that runs WebAssembly, is a tidy module of about 200 lines that calls maybe eight Wasmtime functions. The containerd side is nearly three times as big, and almost all the bugs were in it.

Hello

After the rootfs change:

$ sudo ctr -n default run --rm \
    --runtime io.containerd.wisp.v1 \
    wisp.local/hello-wasm:latest hello
hello
$

A WebAssembly module compiled from five lines of Rust, packaged as an OCI image, imported by containerd, handed to a shim that doesn’t fork, run in a Wasmtime instance with no concept of Linux, with stdout going through a FIFO that containerd attached to ctr’s terminal. Five separate systems agreeing on one word.

There were smaller surprises along the way (snapshot leftovers from a half-failed run that I had to clean up by hand, and fifteen minutes chasing the wrong error after mixing up a container name and an image tag), but the main thing is that the integration test finally passed.

Testing the exit-code matrix

One hello proved the wiring worked. The next several days were about making sure it held up. Each row of the exit-code table needed a probe: a WASM module that triggers that outcome so I could see what containerd reported. I turned the hello-world crate into a multi-mode probe whose first argument picks the behavior:

  • proc_exit 42 calls WASI proc_exit(42); ctr should report 42.
  • trap traps deliberately.
  • loop spins forever so I can kill it from another shell.
  • print-stderr writes to fd 2; read-stdin echoes a line.

Three of these taught lessons that apply beyond wisp.

ctr replaces the command, it doesn’t append

The image’s Entrypoint was /module.wasm. I assumed ctr run --runtime io.containerd.wisp.v1 wisp.local/probe:latest myname trap would give the guest ["/module.wasm", "trap"], with the entrypoint at argv[0] and my argument at argv[1], so the probe read its mode from args.get(1). Every mode just printed hello, through several careful rebuilds.

ctr run actually replaces the OCI Entrypoint+Cmd with the trailing arguments; it doesn’t append to them. ctr consumes myname as the container ID, so the guest’s argv was ["trap"], the mode sat in args[0], and the probe found nothing at args.get(1) and fell through to the default. Reading args.first() instead was a one-character fix. The fifteen minutes I spent looking for a bug in the WASI argv plumbing came from assuming ctr works like docker.

The optimizer deleted my trap

The probe’s trap mode was:

"trap" => unsafe { std::hint::unreachable_unchecked() },

unreachable_unchecked tells the compiler a code path never runs. It’s unsafe because if it does run, you’re in undefined behavior. In a debug build it becomes a panic; in a release build it becomes whatever the compiler finds most useful, usually a trap instruction. I was building release with link-time optimization, so I expected an unreachable opcode in the WASM and a Trap::UnreachableCodeReached from Wasmtime. I got hello.

The compiler took the hint more seriously than I had. unreachable_unchecked isn’t an instruction; it’s a promise to the optimizer that this point is never reached. LTO took me at my word, proved the match arm containing it was dead (no caller could reach it without breaking my promise), and removed the whole arm. The match no longer had a "trap" case, so it fell through to the default and printed hello. Nothing was wrong with Wasmtime; I’d told the compiler not to emit the trap, and it believed me.

The fix was to use an actual instruction instead of a UB hint:

"trap" => core::arch::wasm32::unreachable(),

core::arch::wasm32::unreachable emits a real unreachable opcode at any optimization level, so there’s nothing for the optimizer to remove. Now the trap mode traps, Wasmtime reports Trap::UnreachableCodeReached, the engine maps it to 1, and ctr reports 1.

This is the same pattern as the ABIInternal wrapper in the signals post. In both cases the compiler did something helpful that turned out to be the bug: the Go toolchain wrapped my signal handler in a frame-management prologue I didn’t write, and Rust’s optimizer took my unreachable_unchecked hint literally. Wherever the host language meets a low-level contract (signal entry, syscall trampolines, FFI, the WASM ABI), assume the compiler is doing something helpful you may have to undo.

An empty loop hung the whole host

For the kill test I needed a probe with an unbounded loop that I could ctr task kill from another shell and check for exit 137. The simplest loop is an empty one:

"loop" => loop { std::hint::black_box(()); },

black_box stops the optimizer from removing the loop body, so the loop stays in the WASM. I built it, ran it, killed it from another shell, and the whole host froze. ctr task delete blocked, the shell that sent the kill stopped responding, and Ctrl-C did nothing, because the shell was waiting on an RPC that was waiting on a wait that was waiting on a guest that would never exit.

Epoch interruption evidently doesn’t work on every loop a module can contain. The epoch pass instruments loop back-edges with a check against the engine’s epoch counter. My hypothesis (only a hypothesis) is that the empty loop { black_box(()) } compiled to a WASM loop with no back-edge the pass hooks into. As far as I can tell, increment_epoch() did its job, but nothing trapped, and the entire host hung on a single uninterruptible loop opcode. Giving the loop body something to do, loop { i = i.wrapping_add(1); std::hint::black_box(i); }, made the kill test work. Freezing a whole Linux box with loop {}, even briefly, is the kind of thing you leave a careful comment about.

Where wisp fits

The five sandboxes in this series each answer the same question differently:

  • ironbox: boundary at the kernel. The container shares the host kernel with everything else. Namespaces make each container think it has its own PID space, network and mounts; cgroups meter its resources. Every syscall is a real syscall against the real kernel, so a kernel bug in, say, setsockopt affects every container on the box.
  • The gVisor posts: boundary at the syscall. The guest’s syscalls are intercepted in userspace (by ptrace or seccomp-unotify) and emulated, so they never reach the host kernel. A setsockopt bug in the host kernel no longer matters because the host isn’t running setsockopt; my Go code is. The cost is that the userspace kernel is real software with its own bugs.
  • mini-firecracker: boundary at the CPU. The guest runs its own kernel inside a KVM VM, and hardware keeps the host kernel away from the guest’s syscalls. The cost is a second kernel, in memory and boot time, and two kernels to keep patched.
  • sandprint: same boundary, smaller. Observation-based seccomp profiles give a tighter syscall allowlist than anyone writes by hand. The boundary stays at the syscall; its surface shrinks.
  • wisp: no boundary to draw. A WASM guest has no syscalls, because WASM isn’t a syscall-oriented machine. It executes stack operations, loads and stores against its linear memory, and calls host functions whose signatures are declared in advance. There’s no setsockopt to intercept or delegate. If the host hasn’t declared a function for something, the guest can’t ask for it.

That’s a different kind of safety from the other four. ironbox depends on the kernel being correct. mini-sentry depends on the userspace kernel being correct. The microVM depends on the hardware and host kernel. wisp depends on Wasmtime executing WASM bytecode correctly, which is a smaller claim with a smaller attack surface. It’s also far more restrictive: most existing software can’t run in a WASM guest at all and has to be compiled for a target that doesn’t assume an operating system. wisp removes a class of attacks by removing the surface they’d use, and a lot of useful software goes with it.

What I learned

  1. A runtime is mostly glue. The Wasmtime part of wisp, which actually runs WebAssembly, is short and gave me no trouble. The containerd part, which translates between containerd and the engine, is nearly three times the size and had every bug in this post. Writing a runtime mostly means writing a translation layer between two existing systems. I suspect that’s true in general.
  2. Tools fail politely, which hides the failure. Task::connect defaulted to Unimplemented, so ctr run aborted right when my code was about to print. Rust’s optimizer, given unreachable_unchecked() in a release build with LTO, deleted the match arm containing it, so my trap probe printed hello. In both cases some piece of machinery around the language, a default trait method or an optimization pass, did something reasonable that turned out to be the bug. Wherever a contract’s failure mode is a courtesy rather than a crash, check which courtesies apply on your happy path.
  3. Choose where the boundary goes before choosing anything else. The five options are the kernel, the syscall, the hardware, the syscall tightened by observation, and removing the ABI altogether. Each has a cost the others don’t: ironbox shares a kernel, mini-sentry implements one, the microVM runs two, sandprint needs an observation pass before it has a policy, and wisp can’t run most existing software. For a real workload the question isn’t which sandbox is best but which cost you’d rather pay. These five posts try to put the options side by side so that question can be asked properly.

The source is at github.com/mtclinton/wisp. The shim’s TTRPC service is in src/shim.rs, the Wasmtime engine in src/wasmtime_engine.rs, and the ctr run smoke procedure for the full exit-code matrix, with the lessons recorded as I found them, in TESTING.md.