vortex

2. Architecture

@avarok/vortex 0.1.0 · Updated

2.1 Shape

 main thread (JS shim + Rust core)                 worker N (JS shim + Rust core)
 ───────────────────────────────────               ─────────────────────────────────
 Piscina API, events, AsyncResource                handler lookup + call (user JS)
 pending queue (piscina TaskQueue semantics)       arg decode / result encode
 arg encode ──► [slot arena]  ◄───────────────────  result encode
 dispatch push ─► [dispatch ring  MPMC] ─────────►  pull (spin, then park in Rust)
 completion drain ◄─ [completion ring MPSC] ◄─────  push completion
 Atomics.waitAsync on completion seq               histograms / counters (Rust, atomics)
                 └──────── one shared WebAssembly.Memory (SharedArrayBuffer) ───────┘

One WebAssembly.Memory({shared: true}) is created by the main thread, passed to each worker once at startup (the only per-worker postMessage in steady state besides fallbacks), and every thread instantiates the same compiled WebAssembly.Module against it. The Rust core owns the layout of that memory and every concurrent algorithm on it. JS owns everything that touches JS objects.

2.2 What is Rust (wasm32-unknown-unknown, shared memory)

Component Notes
Region layout Header, per-worker records, slot table, arenas, rings, histograms; sized at pool construction from maxThreads × concurrentTasksPerWorker, grown only by the main thread.
Slot table One state word per slot, [generation:16][worker:12][state:4]: a single CAS claims a task and records its owner. Slots are allocated and released only by the main thread (a plain stack in shared memory), each allocation advancing the generation.
Dispatch queue One producer (main), many consumers. A consumer never reserves a cell: it claims the task with one CAS on the slot word, then helps advance head with a CAS anyone may finish, so a consumer dying at any instruction blocks nothing. Tickets carry the generation, so entries of cancelled or recycled slots are skipped. Ring capacity is twice the slot count. (A sequence-number ring was rejected: a consumer dying between reserving and releasing a cell would block every producer.)
Completion set Two-level bitmap instead of a ring: a worker sets the slot's bit with one atomic OR, the main thread drains whole words in batches. The slot's Done word is the truth, so a worker dying mid-way loses nothing.
Per-worker push rings SPSC, used only in custom-loadBalancer mode (2.5). Not built yet.
Park / unpark Time-based adaptive spin (budget follows the observed gap between tasks, capped, decays to zero), then memory.atomic.wait32 (no JS) on the worker's own futex word. Parked workers are bits in a mask; the producer notifies only when a bit is set, preferring the lowest index. Each store-then-load handshake is fenced with fence(SeqCst) (chapter 7).
Worker accounting In-flight count, abortable flag, parked flag, current slot ids (for recovery when a worker dies), idle-since timestamp for idleTimeout.
Backpressure counters currentUsage, capacity, needs-drain edge detection (events are fired by JS when Rust reports an edge).
Timing HDR-style log-linear histograms (runTime, waitTime, per-worker) with atomic bucket increments, recorded in the worker with no message; summaries computed in Rust on read.
Task id / counters completed, task id generator.

Build: pinned nightly via rust-toolchain.toml, -Z build-std=core,panic_abort, -C target-feature=+atomics,+bulk-memory,+mutable-globals, linker --shared-memory --import-memory --max-memory=<cap> --export=__stack_pointer. The precompiled core for this target is built without atomics, so build-std is required (lld refuses --shared-memory otherwise). lld makes data segments passive and emits __wasm_init_memory guarded by a flag, so a second instantiation does not clobber memory. The installed nightly currently lacks the wasm32-unknown-unknown target and rust-src; adding them is a phase-2 step.

#![no_std], no allocator, no thread_local!. This is a correctness requirement, not a style choice: piscina semantics terminate workers at arbitrary instructions (abort of a running task, resourceLimits OOM, process.exit() in a task, destroy()). A worker killed while holding a shared allocator lock (e.g. dlmalloc in wasm-bindgen's threads setup) would deadlock every thread forever. So:

2.3 What must stay JS, and why

Piece Why it cannot be Rust
Creating worker_threads.Worker / Worker, terminate(), 'exit'/'error' events Only the host API can create or kill an isolate thread; wasm has no thread-spawn instruction.
Importing the user module and calling the handler The handler is a JS function in that worker's isolate; wasm can call JS only through imports, which would add a boundary crossing and gain nothing.
Promise creation/resolution, AsyncResource, EventEmitter events These are JS-engine objects; the async-hooks contract ('Piscina.Task') is a Node API.
Encoding/decoding JS values to bytes Walking a JS object graph requires the engine. Doing it from Rust means one JS↔wasm call per property via JsValue, strictly slower than JS writing into a DataView, or than V8's own C++ serializer. Rust allocates and validates the byte range; JS fills it.
Transfer of ArrayBuffer/MessagePort, SharedArrayBuffer arguments, move() Only postMessage can detach/transfer or share a SAB by reference. These go through a per-worker MessageChannel side lane, keyed by slot id.
Main-thread waiting The main thread must never block; Atomics.waitAsync (JS) is the only non-blocking wait on shared memory.
Custom taskQueue and loadBalancer They are user JS callbacks by definition.
niceIncrement Uses the optional native @napi-rs/nice, as piscina does.

Target size of the JS shim: under 1 000 lines total, every file ≤ 250 lines.

2.4 Task lifecycle (default mode)

  1. run() validates (JS), creates the promise and AsyncResource, applies the piscina admission rules. If the dispatch ring has capacity and the pending queue is empty: Rust allocates a slot; JS encodes the argument into the slot's arena (codec, 2.6); Rust publishes the slot to the dispatch ring and, only if a worker is parked, notifies one. Otherwise the task waits in the JS pending queue, unencoded, exactly as in piscina (so custom queues, maxQueue, queueSize, stricterFIFO, abort-while-queued keep their semantics). With the default FIFO queue the dispatch ring also holds queued tasks (up to arena capacity) so a worker takes its next task without a main-thread round trip; those still count as queued, and abort is a slot CAS Queued → Cancelled. A custom taskQueue disables this prefetch (chapter 6.3).
  2. A worker that finished a task, or is spinning, pops the slot (no main-thread involvement), decodes, calls the handler, encodes the result into the same slot, records timing into the histograms, pushes the slot id onto the completion ring, and notifies the main thread only if the main thread armed its waiter.
  3. The main thread has at most one outstanding Atomics.waitAsync on the completion sequence while tasks are in flight. When it resolves, JS drains all available completions in one batch, settles each promise inside its AsyncResource, refills the dispatch ring from the pending queue, emits drain edges, re-arms.
  4. Worker death ('exit'/'error'/abort-terminate): JS asks Rust for the slots recorded in that worker's record, rejects those tasks with piscina's messages, reclaims the slots and stack, and replaces the worker per piscina rules.

Idle workers: a worker with nothing to do spins for a bounded, adaptive budget, then parks in memory.atomic.wait32. A worker running async tasks (concurrentTasksPerWorker > 1, or atomics: 'async') must keep its event loop alive, so it waits with Atomics.waitAsync instead of blocking; with atomics: 'disabled' it is woken by a port message instead, matching piscina's three modes.

2.5 Scheduling modes

2.6 Argument and result codec

Three lanes, chosen per value, all producing results indistinguishable from postMessage structured clone:

  1. Fast lane (JS writing into the slot arena): undefined, null, booleans, numbers (incl. -0, NaN), BigInt, strings, and small plain arrays/objects of those, without cycles or getters with side effects beyond what structured clone itself invokes.
  2. Serializer lane (Node): v8.serialize() bytes copied into the arena; covers Map/Set/Date/RegExp/typed arrays/Errors/cycles. Its exact differences from structured clone (host objects, Buffer subclass handling) are measured, and any type where they differ goes to lane 3.
  3. Side lane: postMessage on the worker's MessageChannel, used for transferList, move(), SharedArrayBuffer, MessagePort, values larger than the slot arena, and anything the first two lanes decline. Exactness is guaranteed because it is structured clone.

Which lanes ship is decided by measurement in phase 2 (it is possible lane 2 never beats lane 3 by enough to justify itself). A differential fuzz test compares each lane against structuredClone for every value it accepts.

2.7 Browsers (second target)

Same core and same memory layout; the shim differs: new Worker(url, {type: 'module'}), no resourceLimits/env/argv/niceIncrement/threads as worker_threads.Worker (documented divergences), no v8.serialize (lane 2 absent), and the page must be cross-origin isolated (Cross-Origin-Opener-Policy: same-origin