8. The Node.js shim as built (phase 2c)
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
run()validates (piscina's messages,config/options.ts), creates theTaskInfo('Piscina.Task'AsyncResource), and applies piscina's admission rules (pool/admission.ts).- The balancer chooses a worker. A slot is reserved; if none is free, the task goes back to the queue (COMPAT: 4096 in flight).
- 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. vortex_assignmarks the slotRunningfor 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 whenconcurrentTasksPerWorker > 1.- The worker pops the ticket, decodes, calls the handler, and writes the result into the
slot or onto the port. Then
vortex_finish_assignedmarks 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). - The
MSG_WAKEarrives (the main thread no longer also waits onDONE_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:
atomics: 'sync':vortex_idle_wait_assignedspins up to the adaptive budget, then blocks inmemory.atomic.wait32, as piscina blocks inAtomics.wait.'async'and'disabled': oneAtomics.waitAsyncon its futex word, usingvortex_prepare_wait/vortex_withdraw, the split form ofpark(loom modelan_asynchronously_waiting_worker_receives_every_assigned_task). The event loop keeps running.
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
- piscina 5.3.2 suite, unmodified,
--test-concurrency=4, Node.js 22.23.3: 149 pass, 5 skipped (by the suite's own conditions), 0 fail, in 15 consecutive runs. The reference piscina gives the same counts through the same harness. A control that corrupts lane-1 number decoding turns the suite red (actual: 43, expected: 42); after a byte-identical restore it is green again. js/test/(52 tests): defaults against piscina 5.3.2 for seven option shapes, lane 1 againststructuredClone, the binary limit reader, lane routing (200 primitive tasks send no task message), record recycling under repeated aborts, limits, version.- Core:
push.rs(5 tests),loom_push.rs(2 models), and everything from chapter 7.
| 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
- Run the suite on Node.js 24 (its two dispose tests run only there). It is green on 20.20.2, 22.23.3 and 25.1.0.
- Phase 2d: lane 2 (
v8.serialize) behind measurement. - Open defect: a terminated worker can keep running a
while (true)task (see 8.8). - Why the JS core falls behind the Rust core at 8 threads (chapter 9, two cores).
- The remaining per-task crossings of the Rust core (8.9 item 2).
8.8 Phase 3 fixes (measured in chapter 9)
- Each worker's balancer view is built once, not per dispatch.
- The idle spin reads the clock every 64 iterations (each read is an import call).
- Push prefetch: core state
Staged(slot_stage.rs), shimpool/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. - The per-task main-thread path keeps only what piscina's semantics need (frozen
default options read directly, last task name remembered,
maybeDrainscheduled without a per-call AsyncResource, abort listener only with a signal, no queue walk when no worker has room). - 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.
- Reproduced outside the test runner: one cold process per run of that test body, 8 busy loops for contention, 48 GB Mac, Node 22.23.3.
- Pre-existing: the s0 snapshot (before the Phase 3 fixes) hangs at the same rate. s0: 2/60 and 3/150; s5: 5/150 and 2/80.
- Needs source-map support plus the task's
eval, not tsx itself. With piscina'seval.jsfixture:--import=tsxhangs as above;--enable-source-mapsalone, 3/100; no flags, 0/100 (twice). With tsx and a plainwhile (true) {}fixture (noeval), 0/100.spin: false(2/100) andatomics: 'async'(6/100) do not avoid it. piscina itself: 0/150 with tsx and 0/100 with--enable-source-maps, same harness. NODE_DEBUG_NATIVE=worker: Node logsWorker 5 called Exit(1)for the survivor but neverExiting thread; the other three exit.sampleshows the survivor in JIT code:MessagePort::OnMessage→ microtask checkpoint → the task'sevalloop.- A shared stop flag set before
terminate()and checked before the handler never fired in a hung run, so the task had started beforeterminate()was called, and V8's termination request did not interrupt the running loop. - Not in either core: it recurs with the JS core (
core: 'js'), with the same stack signature (one hang in a local compat run, Node 22.23.2, passed on rerun). - Not yet known: why termination is lost. Pure-Node repros of the same shape (waitAsync or Atomics.wait wake, port callbacks, dynamic import, eval) did not hang in several thousand runs.
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:
- No imports on the hot path. The idle spin counts iterations of its work check;
spinsPerUsis calibrated per worker by timingvortex_spin_probefor 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. - 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, withrecordTiming(piscina's default), two histogram records on the main thread. - i32 signatures on the hot path (spec 10, section 10).
--trace-turbo-inliningshows 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):
- Main-thread lost wake-up (both cores, every earlier build). A worker advanced
DONE_SEQwith its done bits and swappedMAIN_WAITINGafterwards; a completion the main thread had already drained could advanceDONE_SEQbefore the next arm read it and swap after, so the arm's wake was spent and the next completion woke no one. Seen as obj cells hanging on c0 with the JS core (2 of 40 cold cells under 8 busy loops; in-process, stalls at runs 11, 18 and 102). A state dump showed every slot Done,MAIN_WAITING0 and the onewaitAsyncstill registered; a manual notify finished the run. Fix:DONE_SEQadvances only after the swap (loom_main_wait.rsdeadlocks before, passes after; c0 with the fix backported: no stall in 400 runs). - A
MSG_WAKEread off a port while a drain took port results was discarded. The main thread now wakes onMSG_WAKEalone (it arrived first anyway), and a drain that saw one wakes again when it ends. - With
atomics: 'disabled'the worker took a task already staged in its inbox in the same turn as the last result. piscina starts each task from a port message, so a timers phase usually comes between (not always: a message that arrives during the poll callback is taken in it). The next task now starts from an immediate queued by an immediate (a self-message is not enough: after awaitAsyncwake libuv delivers it in the same poll pass). Blocking mode keeps going at once, as piscina's atomics loop does. Disabled-mode echo fell from 266-287k to 125k tasks/s (piscina 117k; M3 Max, Node 22.23.2).
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.