vortex

8. The Node.js shim as built (phase 2c)

@avarok/vortex 0.1.0 · Updated

The shim is strict TypeScript in js/src/, compiled to CommonJS in dist/ (as piscina ships), plus a generated dist/esm-wrapper.mjs. It passes piscina 5.3.2's suite unmodified; COMPAT.md lists every behaviour difference.

8.1 One decision changed from chapter 2: placement is push, always

Chapter 2.4 planned pull scheduling for the default balancer: workers claim tasks from the shared ring, and the ring prefetches queued tasks. Phase 2c ships push placement for every pool. The balancer, the default LeastBusyBalancer or a custom one, picks the worker for each task, exactly as in piscina. The main thread then writes the slot and hands the ticket to that worker's inbox, a single-producer single-consumer ring in shared memory (crates/vortex-core/src/inbox.rs). It wakes the worker only if it is parked.

Why: piscina's observable semantics are defined by its push model. That covers currentUsage, isRunningAbortableTask, the skip queue for abortable tasks, stricterFIFO, eager spawning, abort of a started task by terminating its worker, and close({ force }) sparing started tasks. Reproducing them on top of pull means re-deriving each one from slot states. Push makes them exact by construction. It also removes two items from the chapter 7.4 gaps: the abortable-head Ineligible gap does not arise (the main thread never offers an abortable task to a busy worker), and run time is recorded at piscina's points.

What push costs: a worker with concurrentTasksPerWorker = 1 waits for the main thread between tasks, as in piscina. Pull prefetch removes that round trip. It stays in the core, still tested (dispatch.rs, the loom models, smoke.mjs), and becomes a phase 4 ablation: it is kept only if the benchmark shows it wins, and only for pools whose semantics it cannot change (default balancer, default queue).

8.2 Per-task path

  1. run() validates (piscina's messages, config/options.ts), creates the TaskInfo ('Piscina.Task' AsyncResource), and applies piscina's admission rules (pool/admission.ts).
  2. The balancer chooses a worker. A slot is reserved; if none is free, the task goes back to the queue (COMPAT: 4096 in flight).
  3. The argument goes into the slot (lane 1, wasm/codec.ts) or, failing that, onto the worker's port (lane 3, with the transfer list). A (filename, name) pair is sent once per worker as a numeric id.
  4. vortex_assign marks the slot Running for that worker, pushes the ticket into its inbox, and wakes the worker if its parked bit is set. A worker that already has tasks in flight is not parked, so it gets a one-word nudge on its port. This is the only per-task message in steady state, and only when concurrentTasksPerWorker > 1.
  5. The worker pops the ticket, decodes, calls the handler, and writes the result into the slot or onto the port. Then vortex_finish_assigned marks it done and notifies the main thread, but only if the main thread is waiting; in that case the worker also posts a one-word wake on its port (MSG_WAKE).
  6. The MSG_WAKE arrives (the main thread no longer also waits on DONE_SEQ, 8.9). It drains every completed ticket (pool/transport.ts), reads each result, releases every drained slot in one call, then settles the promises in their async scopes. Then it marks itself waiting again.

8.3 Workers

worker/runtime.ts runs one loop. It starts every task in its inbox. If none are in flight, it waits:

A blocking wait and an asynchronous wait are never outstanding together on the same word. A notify could wake the wrong one, and the blocked thread would sleep through its work.

8.4 Worker records

A record is a worker index: wasm shadow stack, inbox, futex word, parked bit, and optional histogram. A terminated worker keeps its record until its 'exit' event, because until then it may still pop from its inbox or write into a slot. At exit, vortex_recover returns the slots it still held. Running slots are released; Done slots stay in the completion set and drain frees them. Then the inbox is reset and the record returns to the free list. Records number twice ceil(maxThreads). If none is free, a new worker's startup waits for the next exit (js/test/records.test.mjs).

A late result from a written-off worker is refused by generation (SlotTable::complete), so it can never land in a reused slot (push.rs, control C13).

8.5 Files

Path Role
config/defaults.ts The only implicit defaults (Q5, Q7), tested against piscina 5.3.2
config/tuning.ts Sizing constants (slot bytes, stack bytes, spin cap, records per thread, in-flight cap)
config/options.ts Validation (piscina's messages and order) and filling
wasm/{module,binary,exports,codec}.ts Compile once, size memory from the binary's own limits, typed FFI, lane 1
pool/{thread_pool,admission,shutdown}.ts piscina's ThreadPool semantics
pool/{worker_info,resource,balancer,histogram,transport}.ts Worker records, readiness, balancer, histograms, region
queue/* FixedQueue, ArrayTaskQueue, TaskInfo
worker.ts, worker/* Worker entry, handler lookup, port, task loop

The shim is 35 files and about 1 930 lines of code (2 360 with comments and blank lines), against the under-1 000 that chapter 2.3 targeted. Most of the difference is piscina's own semantics, kept rule for rule.

8.6 Verification record

Control Break Guard Red reason
C10 no fence in targeted wake loom_push blocked model deadlock
C11 no fence in prepare loom_push async model deadlock
C12 recovery keeps the inbox push recovery test stale ticket still queued
C13 completion ignores generation push stale-ticket test stale ticket accepted
C14 a piscina default drifts (idleTimeout) defaults.test.mjs option idleTimeout mismatch
C15 every task forced onto the port lanes.test.mjs 200 task messages instead of 0
C16 records never released at exit records.test.mjs pool stranded, promise pending at loop exit
C17 lone surrogates accepted by lane 1 codec.test.mjs decline test fails
C18 reader skips past the end binary.test.mjs truncation misreported

Each control was restored with sha256 checked identical, the file touched, and its guard rerun green.

Phase 3 fixes (8.8) add: stage.rs (4 tests), one model in loom_push.rs (claim racing withdrawal), one test in push.rs (completion reports a woken main thread), and js/test/prefetch.test.mjs (6 tests: exactly once when a worker with staged tasks dies, slot and port lanes; queueSize and destroy() compared with piscina; steal-back; a task that cannot be staged leaves no count). JS tests: 58.

Control Break Guard Red reason
C19 withdrawal always loses to the worker prefetch exactly-once tests staged tasks rejected with the exit error
C20 queued ignores staged tasks prefetch queueSize test 2 instead of piscina's 3
C21 destroy() does not unstage first prefetch destroy test outcomes differ from piscina
C22 steal-back disabled prefetch steal-back test order short, long, next
C23 queue-walk shortcut always taken piscina suite suite hangs (400 s bound)
C24 staged count incremented on a failed stage prefetch count test queueSize 1, expected 0
C25 notify never reports a wake push completion test main_woken false, expected true
C26 JS core sets the wrong summary bit core conformance regions differ at a finish
C27 JS core doubles the inbox size core conformance sizes and offsets differ
C28 JS core claims a staged task while busy core conformance next results differ
C29 JS core files a value in the wrong bucket core conformance regions differ at a hist

8.7 Open items

8.8 Phase 3 fixes (measured in chapter 9)

  1. Each worker's balancer view is built once, not per dispatch.
  2. The idle spin reads the clock every 64 iterations (each read is an import call).
  3. Push prefetch: core state Staged (slot_stage.rs), shim pool/prefetch.ts; see COMPAT "Prefetch". A pull mode was measured against it and not added: on the CPU-bound workload push with prefetch reaches 95 % of ideal against 97 % for pull, and pull would bypass a custom balancer.
  4. The per-task main-thread path keeps only what piscina's semantics need (frozen default options read directly, last task name remembered, maybeDrain scheduled without a per-call AsyncResource, abort listener only with a signal, no queue walk when no worker has room).
  5. Hybrid completion wake (step 5 of 8.2). A port wake of the worker was measured and rejected: it made a round trip slower (22 µs against 14.6 µs).

The hang (open defect). In piscina's thread-count first test (five while (true) tasks, minThreads 2, maxThreads 4, destroy() once four workers exist) one worker occasionally survives terminate() and spins forever, so destroy() never settles.

8.9 Two cores (owner decisions of 2026-11-27, measured in chapter 9)

The shim talks to the region only through CoreApi; core: 'js' (default) or core: 'rust' picks the implementation (chapter 10 is the spec both follow). Making the Rust core cheap to call:

  1. No imports on the hot path. The idle spin counts iterations of its work check; spinsPerUs is calibrated per worker by timing vortex_spin_probe for 2 ms and keeping the fastest rate (a single probe ran before V8 tiered the wasm up and read 980 iterations/µs against 2,400 after). The sleep's first wait is bounded by the cap. The wasm module's only import is now its memory.
  2. Fewer crossings. vortex_release_drained(n) releases a whole drain in one call. Still one call per task each: reserve, assign/stage, next, finish_assigned, and, with recordTiming (piscina's default), two histogram records on the main thread.
  3. i32 signatures on the hot path (spec 10, section 10). --trace-turbo-inlining shows V8 inlining the JS-to-wasm wrapper for every hot export ("Considering wasm function ... for inlining"); the bodies themselves are not inlined (248 bytes and up against a 30-byte limit). f64 exports were considered too, so the change did not move any call off the generic wrapper.

Three defects found while measuring (the third while chasing a CI failure):

Not a defect: CI's test-is-buffer-transferred failures (PR #1). The suite ran 4 files on a 2-CPU runner (run queue near 12); piscina 5.3.2 itself failed it in 5 of 16 runs there, vortex in 10 of 32. The load comes from the suite's pools, so it follows files in flight, not CPUs: on the 4-vCPU runners (public repo) 4 files still failed it, piscina 4 of 24, vortex 4 of 39. At 2 files: 0 of 180 for all three, Node 20 and 22.