---
title: "1. The interface vortex matches · vortex"
description: "vortex matches piscina 5.3.2 (npm latest on 2026-11-27; tag v5.3.2, commit 6c7e54630a8c28a96ce5c0625b463d849d21171c; engines.node >= 20). Source of truth for…"
canonical: "https://vortex.avarok.net/docs/design/01-interface/"
lastmod: "2026-11-27T16:33:32Z"
tokens: 3899
---

# 1\. The interface vortex matches

@avarok/vortex 0.1.0 · Updated 2026-11-27

## 1.1 Pinned reference

vortex matches **piscina 5.3.2** (npm `latest` on 2026-11-27; tag `v5.3.2`, commit `6c7e54630a8c28a96ce5c0625b463d849d21171c`; `engines.node >= 20`). Source of truth for this chapter is that tag's `src/` and the published `dist/*.d.ts` of the npm tarball, read without running any install script.

Not matched (yet): the `6.0.0-rc.5` line. Its delta, read from piscina `master` (`1afb9ca`), is: `recordTiming` and `workerHistogram` removed, the `histogram` getter removed, a `channels` static and six `diagnostics_channel` message types added (`PiscinaTaskSubmitMessage`, `…TaskStart…`, `…TaskDone…`, `…NewWorker…`, `…EvictWorker…`, `…Drain…`), Node >= 22. Supporting 6.x later is an additive layer (section 5, phase 6).

piscina `master` also carries about fifteen bug fixes made after 5.3.2 (e.g. "reject run() after the pool has been closed or destroyed", "enforce maxQueue for tasks submitted with an AbortSignal", "let close() finish when the last queued task is aborted", "keep replacing crashed workers after aborting a task on a starting worker"). Policy: vortex follows the **fixed** behaviour wherever no 5.3.2 test pins the buggy one, and lists each such divergence in `docs/COMPAT.md` (phase 2).

## 1.2 Module exports

CommonJS `module.exports = Piscina` (the class is the module), plus ESM wrapper re-exporting: `default`, `Piscina`, `ArrayTaskQueue`, `FixedQueue`, `isWorkerThread`, `move`, `queueOptionsSymbol`, `transferableSymbol`, `valueSymbol`, `version`, `workerData`. Type-only exports: `PiscinaTask`, `TaskQueue`. Package `exports` map: `types` / `import` (esm wrapper) / `require` (cjs main).

Three tests also deep-import internals: `dist/symbols` (`kQueueOptions`), `dist/common` (`getAvailableParallelism`, `isMovable`, `markMovable`…), `dist/worker_pool` (the `PiscinaWorker` type). vortex ships the same paths as thin re-exports so those tests run unmodified; they are not promised as public API.

## 1.3 Constructor options (`new Piscina(options?)`)

| Option                     | Type                                                                     | Default (5.3.2)                                               | Validation error                                      |
| -------------------------- | ------------------------------------------------------------------------ | ------------------------------------------------------------- | ----------------------------------------------------- |
| `filename`                 | `string \| null` (path or `file:` URL)                                   | `null`                                                        | TypeError `options.filename must be a string or null` |
| `name`                     | `string`                                                                 | `'default'`                                                   | TypeError `…name must be a string or null`            |
| `minThreads`               | number ≥ 0                                                               | `max(floor(P/2),1)`                                           | TypeError non-negative integer                        |
| `maxThreads`               | number ≥ 1                                                               | `P * 1.5` (not floored)                                       | TypeError positive integer                            |
| (both given, min > max)    |                                                                          |                                                               | RangeError `…must not conflict`                       |
| `idleTimeout`              | number ≥ 0, `Infinity` = never                                           | `0`                                                           | TypeError                                             |
| `maxQueue`                 | number ≥ 0 or `'auto'` (= `maxThreads ** 2`)                             | `Infinity`                                                    | TypeError                                             |
| `concurrentTasksPerWorker` | number ≥ 1                                                               | `1`                                                           | TypeError                                             |
| `atomics`                  | `'sync' \| 'async' \| 'disabled'`                                        | `'sync'`                                                      | TypeError                                             |
| `resourceLimits`           | object (Worker `resourceLimits`)                                         | none                                                          | TypeError                                             |
| `argv`, `execArgv`         | `string[]`                                                               | none                                                          | none                                                  |
| `env`                      | Worker `env` (incl. `SHARE_ENV`)                                         | none                                                          | none                                                  |
| `workerData`               | any (cloned once per worker)                                             | none                                                          | none                                                  |
| `taskQueue`                | object with `size`, `shift`, `remove`, `push` (`unshift` optional)       | `FixedQueue` (internal); `ArrayTaskQueue` in `options` view   | TypeError                                             |
| `niceIncrement`            | number (≥ 0 off Windows; uses optional `@napi-rs/nice`)                  | `0`                                                           | TypeError                                             |
| `trackUnmanagedFds`        | boolean                                                                  | `true`                                                        | TypeError                                             |
| `closeTimeout`             | number ≥ 0 ms                                                            | `30000`                                                       | TypeError                                             |
| `recordTiming`             | boolean                                                                  | `true`                                                        | none                                                  |
| `stricterFIFO`             | boolean                                                                  | `false`                                                       | TypeError                                             |
| `loadBalancer`             | `(task: PiscinaTask, workers: PiscinaWorker[]) => PiscinaWorker \| null` | `LeastBusyBalancer({maximumUsage: concurrentTasksPerWorker})` | TypeError                                             |
| `workerHistogram`          | boolean                                                                  | `false`                                                       | TypeError                                             |

`P` = `os.availableParallelism()`. Clamping quirks to reproduce: if only `maxThreads` is given and `minThreads >= maxThreads`, `minThreads = maxThreads`; if only `minThreads` is given and `maxThreads <= minThreads`, `maxThreads = minThreads`. Options are copied into a null-prototype object; unknown keys are ignored.

**PCND note.** A drop-in replacement must reproduce these defaults, so they cannot be removed. vortex keeps them in exactly one module (`js/defaults.ts`) that is the compatibility specification itself, with a test asserting each value against this table. Nothing else in vortex may default anything. The owner approved this exception (Q5, 2026-11-27).

## 1.4 `run(task, options?) → Promise<R>`

Options (null-prototype copy): `transferList?: TransferListItem[]`, `filename?: string|null`, `name?: string|null`, `signal?: AbortSignal | EventEmitter-with-'abort' | null`. Errors are returned as rejected promises, never thrown: `options must be an object`, `transferList argument must be an Array`, `filename argument must be a string`, `name argument must be a string`, `signal argument must be an object`, `filename must be provided to run() or in options object`.

Semantics to reproduce:

- `filename`/`name` fall back to the pool's; `file:` URLs are converted to paths.
- After `close()`/`destroy()` began, the task gets an already-aborted signal (reason `'queue is being terminated'`) and rejects with `AbortError`.
- An already-aborted signal rejects immediately with `AbortError(reason)` (name `'AbortError'`, message `'The task has been aborted'`, `cause` = reason).
- Abort while queued removes the task; abort while running **terminates that worker** and replaces it (`_ensureMinimumWorkers`).
- Abortable tasks never share a worker (`currentUsage` reports `Infinity`).
- Queue admission: if the queue is non-empty and `queue.size >= maxQueue + pendingCapacity` reject `Task queue is at limit` (or `No task queue available and all Workers are busy` when `maxQueue === 0`); else enqueue and eagerly spawn up to `maxThreads`. If the queue is empty, try the balancer; if refused, spawn if possible; with `maxQueue <= 0` and no pending capacity, reject.
- `stricterFIFO`: a task the balancer refuses goes back to the queue head instead of the tail; abortable refused tasks go to a separate `skipQueue` drained first.
- Each task is an `AsyncResource` of type `'Piscina.Task'`; the result callback runs inside it (pinned by `async-context.test.ts`).
- The pool is an `EventEmitterAsyncResource` named `'Piscina'`.

## 1.5 `close({force?})`, `destroy()`, disposal

- `close()`: marks closing; with `force: true` rejects every not-yet-started task with `AbortError` (message `The task has been aborted`, `cause` `'pool is closed'`); waits for running tasks, racing `closeTimeout` (on timeout emits `'error'` with `Close operation timed out`); then `destroy()`, emits `'close'`. Bad `force` → rejected TypeError.
- `destroy()`: rejects queued tasks with `Error('Terminating worker thread')`, terminates every worker, resolves after all `'exit'` events settle.
- `[Symbol.dispose]()` calls `close()` without awaiting; `[Symbol.asyncDispose]()` returns `close()`.

## 1.6 Events (`EventEmitter`)

`'workerCreate'(PiscinaWorker)` (for initial workers: next microtask, so listeners attached after the constructor see it), `'workerDestroy'(PiscinaWorker)`, `'message'(any)` (anything a worker posts on `parentPort` other than the internal ready message), `'error'(Error)` (worker error with no task to blame; close timeout; unexpected response), `'drain'`, `'needsDrain'` (both emitted in a microtask when `currentUsage` crosses `maxThreads * concurrentTasksPerWorker`), `'close'`.

## 1.7 Instance properties (all read-only getters)

`maxThreads`, `minThreads`, `options` (filled options, null-prototype), `threads: Worker[]` (the real `worker_threads.Worker` objects), `idleThreads`, `queueSize` (= `max(queue + skipQueue − pendingCapacity, 0)`), `completed`, `histogram` (`{runTime, waitTime, resetRunTime(), resetWaitTime()}`; summaries have `average, mean, stddev, min, max, p0_001, p0_01, p0_1, p1, p2_5, p10, p25, p50, p75, p90, p97_5, p99, p99_9, p99_99, p99_999`, recorded as µs integers (min 1) and reported in ms), `utilization` (`mean_runtime_ms × count / (duration × maxThreads)`, 0 without timing), `duration` (ms since construction), `needsDrain`.

`PiscinaWorker` (given to balancers and events): `id` (= `threadId`), `currentUsage`, `isRunningAbortableTask`, `histogram` (summary or `null`), `terminating`, `destroyed`, plus an internal symbol link. `PiscinaTask` (to balancers and queues): `taskId`, `filename`, `name`, `created`, `isAbortable`, `[kQueueOptions]`.

Note: piscina's README still documents top-level `runTime`/`waitTime`; the 5.x code moved them under `histogram`. vortex follows the code.

## 1.8 Statics

`Piscina.isWorkerThread`, `Piscina.workerData`, `Piscina.version` (vortex reports its own version, plus a vortex static `compatibleWith = '5.3.2'`; Q6), `Piscina.Piscina`, `Piscina.FixedQueue`, `Piscina.ArrayTaskQueue`, `Piscina.move(value)` (wraps ArrayBuffer / ArrayBufferView / MessagePort / Transferable in a movable marker; primitives returned as is), `transferableSymbol`, `valueSymbol`, `queueOptionsSymbol` (symbols must be the **same** symbol objects across the main and worker module instances of the package, which piscina gets by plain module identity).

## 1.9 Worker-side conventions

- Handler lookup per `(filename, name)`, cached (≤ 1000 entries): `require()`/ `import()` the file; if the module itself is a function use it, else `module[name]` (default name `'default'`); if CJS loading fails or yields no function, retry as ESM `import(fileURL)`. The export may be a **Promise** resolving to the handler: the worker is not "ready" until it resolves.
- Missing handler → task rejects `No handler function exported from <filename>`.
- The handler may be sync or async; its return value is awaited. A `move()`d return value is transferred.
- Thrown values are structured-cloned back as the rejection.
- Inside a worker `isWorkerThread === true` and `workerData` is the pool's `workerData`; user code may use `parentPort.postMessage` (surfaces as `'message'`).
- With atomics on, the idle worker blocks in `Atomics.wait`, so un-awaited async work started by a task stalls until the next task (documented piscina limitation, kept).
- Before replying in sync-atomics mode the worker flushes pending stdout/stderr (`console-log.test.ts`).
- Env switches honoured by piscina's worker: `PISCINA_DISABLE_ATOMICS=1`, `PISCINA_ENABLE_ASYNC_ATOMICS=1`. vortex honours the same names.

## 1.10 Error messages

`Terminating worker thread`, `filename must be provided to run() or in options object`, `Task queue is at limit`, `No task queue available and all Workers are busy`, `Close operation timed out`, `worker exited with code: N`, `The task has been aborted` (AbortError; the reason, e.g. `'pool is closed'`, is its `cause`). Tests compare these strings, so they are part of the contract and live in one module (`js/errors.ts`).

```json
{
  "@context": "https://schema.org",
  "@graph": [
    {
      "@id": "https://thomaspbraun.com/#person",
      "@type": "Person",
      "name": "Thomas Braun",
      "sameAs": [
        "https://github.com/tbraun96"
      ],
      "url": "https://thomaspbraun.com",
      "worksFor": {
        "@type": "Organization",
        "name": "Avarok",
        "url": "https://avarok.net"
      }
    },
    {
      "@id": "https://vortex.avarok.net/docs/design/01-interface/",
      "@type": "WebPage",
      "author": {
        "@id": "https://thomaspbraun.com/#person"
      },
      "dateModified": "2026-11-27T16:33:32Z",
      "description": "vortex matches piscina 5.3.2 (npm latest on 2026-11-27; tag v5.3.2, commit 6c7e54630a8c28a96ce5c0625b463d849d21171c; engines.node >= 20). Source of truth for…",
      "inLanguage": "en",
      "isPartOf": {
        "@id": "https://vortex.avarok.net/#website",
        "@type": "WebSite",
        "name": "vortex",
        "url": "https://vortex.avarok.net/"
      },
      "name": "1. The interface vortex matches · vortex",
      "url": "https://vortex.avarok.net/docs/design/01-interface/"
    }
  ]
}
```
