defuss-multicore 0.0.3 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -0
- package/README.md +234 -51
- package/dist/index-BxtfU1K8.cjs +952 -0
- package/dist/index-XVLcdKzC.mjs +938 -0
- package/dist/index.cjs +18 -619
- package/dist/index.d.cts +65 -103
- package/dist/index.d.mts +65 -103
- package/dist/index.mjs +2 -610
- package/dist/pool-browser-DkpTlaVd.mjs +41 -0
- package/dist/pool-browser-nGIRBxcR.cjs +43 -0
- package/dist/{pool-node-DUsc5lQk.cjs → pool-node-BQjchaw0.cjs} +6 -4
- package/dist/{pool-node-CmCaEceF.mjs → pool-node-D7dWSlZP.mjs} +5 -3
- package/dist/transfer-B05kHQLB.cjs +15 -0
- package/dist/transfer-DPiKlTfq.mjs +12 -0
- package/dist/worker-CneL12oi.d.cts +108 -0
- package/dist/worker-CneL12oi.d.mts +108 -0
- package/dist/worker.cjs +59 -0
- package/dist/worker.d.cts +2 -0
- package/dist/worker.d.mts +2 -0
- package/dist/worker.mjs +57 -0
- package/package.json +34 -10
- package/dist/pool-DhG3ybwo.mjs +0 -151
- package/dist/pool-DqNSYahJ.cjs +0 -153
- package/dist/pool-browser-BsBdOUwc.cjs +0 -43
- package/dist/pool-browser-IHMOtzRq.mjs +0 -41
package/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2019 - 2026 Aron Homberg
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
package/README.md
CHANGED
|
@@ -1,17 +1,73 @@
|
|
|
1
1
|
# defuss-multicore
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](LICENSE)
|
|
4
|
+
[](package.json)
|
|
5
|
+
[](tsconfig.base.json)
|
|
6
|
+
[](package.json)
|
|
4
7
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
8
|
+
**Multi**core for JavaScript: one `await` for every CPU core, zero dependencies.
|
|
9
|
+
|
|
10
|
+
Web Workers in the browser and `worker_threads` in Node.js behind the same API and the same types. Pure functions are auto-split across cores, typed module workers get a real task pool, and the vector/matrix kernels are JIT loop-unrolled on the caller thread.
|
|
11
|
+
|
|
12
|
+
## TL;DR
|
|
13
|
+
|
|
14
|
+
A JavaScript runtime gives your code one thread. Heavy compute blocks the UI or the event loop, and no amount of `Promise.all` buys a second core.
|
|
15
|
+
|
|
16
|
+
defuss-multicore moves compute to the cores you already have. It splits arrays and TypedArrays into compact partitions, runs each partition in a real worker, and hands the results back through one `await` — the same code in the browser and in Node.
|
|
17
|
+
|
|
18
|
+
- 🔁 **Isomorphic:** Web Workers (browser) and `worker_threads` (Node.js) behind one API
|
|
19
|
+
- ⚡ **Loop-unrolled kernels:** `matmul`, `dotProduct`, `matadd`, `matsub`, `matdiv` JIT-select 4x/8x/16x unroll factors
|
|
20
|
+
- 🧮 **Parallel array methods:** `map`, `filter`, `reduce` for any array, auto-partitioned across cores
|
|
21
|
+
- 🧩 **Typed module workers:** real ESM imports and module-local state, driven by an explicit task pool
|
|
22
|
+
- 🚏 **A pool with a contract:** bounded queue, stable priorities, per-task timeouts, cancellation that stops running work
|
|
23
|
+
- 🔒 **Explicit ownership:** `multicore()` transfers only internal partition copies — your buffers are never detached; pool transfers are opt-in and listed by you
|
|
24
|
+
- 🧯 **Predictable failure:** a crashed worker rejects only its own active job; nothing is retried silently
|
|
25
|
+
- 🪶 **Tiny:** zero runtime dependencies, ESM + CJS dual output, Node ≥ 18.17.1 and every modern browser
|
|
26
|
+
|
|
27
|
+
## How it works
|
|
28
|
+
|
|
29
|
+
```mermaid
|
|
30
|
+
flowchart LR
|
|
31
|
+
U(["🙋 you"]) -->|"array + pure function"| S
|
|
32
|
+
|
|
33
|
+
subgraph split ["🔀 multicore()"]
|
|
34
|
+
S["partition
|
|
35
|
+
auto-split arrays · broadcast scalars"]
|
|
36
|
+
S --> W1["worker 1"]
|
|
37
|
+
S --> W2["worker n"]
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
W1 --> R["reduce
|
|
41
|
+
partials → one value"]
|
|
42
|
+
W2 --> R
|
|
43
|
+
R --> U
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
For real application code — imports, module state, async handlers — the second path is a typed task pool:
|
|
47
|
+
|
|
48
|
+
```mermaid
|
|
49
|
+
flowchart LR
|
|
50
|
+
A["your app"] -->|"run · batch · stream"| Q["bounded queue
|
|
51
|
+
priority · timeout · signal"]
|
|
52
|
+
Q --> P["pool
|
|
53
|
+
warmup → ready workers"]
|
|
54
|
+
P --> W["worker module
|
|
55
|
+
expose(tasks) · init"]
|
|
56
|
+
W -->|"result · transfer(buffers)"| A
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
| API | When you reach for it | What it does |
|
|
60
|
+
|---|---|---|
|
|
61
|
+
| **`multicore(fn, options?)`** | batch data + a pure function | Wraps `fn` for parallel execution. Array/TypedArray args are auto-split across cores, scalars are broadcast to every worker, partial results are collected — or reduced to one value via `reduce`. Falls back to the main thread below `threshold`. |
|
|
62
|
+
| **`map` / `filter` / `reduce`** | big arrays, familiar semantics | Parallel counterparts of the `Array.prototype` methods; the reducer must be associative. Pools are cached per callback and released explicitly via `releaseArrayWorkers`. |
|
|
63
|
+
| **`createPool()` + `expose()`** | real application code | Typed module workers with normal ESM imports and module-local state: batching, streaming, priorities, timeouts, cancellation. Always worker execution — no size threshold, no silent main-thread fallback. |
|
|
64
|
+
| **`dotProduct`, `matmul`, `matadd`, …** | numeric kernels | JIT loop-unrolled (4x/8x/16x, auto-selected) vector/matrix math, synchronous on the caller thread. Combine with `multicore()` or a pool to move them into workers. |
|
|
10
65
|
|
|
11
66
|
## Install
|
|
12
67
|
|
|
13
68
|
```bash
|
|
14
69
|
bun add defuss-multicore
|
|
70
|
+
# or: npm install defuss-multicore
|
|
15
71
|
```
|
|
16
72
|
|
|
17
73
|
## Quick Start
|
|
@@ -47,13 +103,14 @@ for await (const r of parallel(data)) { ... } // stream as workers finish
|
|
|
47
103
|
|
|
48
104
|
- Array/TypedArray args are **auto-split** across cores
|
|
49
105
|
- Scalar args are **broadcast** to every worker
|
|
50
|
-
- Returns `ParallelResult<R>`
|
|
106
|
+
- Returns `ParallelResult<R>` — both `PromiseLike<R[]>` and `AsyncIterable<R>`
|
|
107
|
+
- The callable also exposes `warmup()`, `close()` and `terminate()`
|
|
51
108
|
|
|
52
109
|
#### `MulticoreOptions<R>`
|
|
53
110
|
|
|
54
111
|
| Option | Type | Default | Description |
|
|
55
112
|
|-------------|---------------------------|------------------------|-------------|
|
|
56
|
-
| `cores` | `number` |
|
|
113
|
+
| `cores` | `number` | available CPU cores | Number of worker threads |
|
|
57
114
|
| `threshold` | `number` | `1024` | Min array length before parallelizing (falls back to main thread below this) |
|
|
58
115
|
| `reduce` | `(a: R, b: R) => R` | - | Reduce partial results into a single value |
|
|
59
116
|
| `eager` | `boolean` | `false` | Pre-spawn workers immediately instead of on first call |
|
|
@@ -62,9 +119,13 @@ for await (const r of parallel(data)) { ... } // stream as workers finish
|
|
|
62
119
|
|
|
63
120
|
| Option | Type | Default | Description |
|
|
64
121
|
|------------|----------------|----------|-------------|
|
|
65
|
-
| `cores` | `number` | - | Override
|
|
122
|
+
| `cores` | `number` | - | Override partition count for this call (within the pool cap) |
|
|
66
123
|
| `signal` | `AbortSignal` | - | Cancel in-flight workers |
|
|
67
|
-
| `transfer` | `boolean` | `true` |
|
|
124
|
+
| `transfer` | `boolean` | `true` | Transfer the internally created partition buffers (see ownership note below) |
|
|
125
|
+
|
|
126
|
+
**Ownership note:** TypedArray inputs are copied into compact, independently owned partitions; only those internal copies are transferred — your caller-owned buffers are never detached. Disable with `{ transfer: false }`.
|
|
127
|
+
|
|
128
|
+
**Function constraints:** `fn` is serialized via `fn.toString()` — it must be self-contained: no captured closures, no imports, no DOM access. Async chunk functions are awaited. For application code with real imports and module-local state, use [module workers](#module-workers--task-pools) instead.
|
|
68
129
|
|
|
69
130
|
### `map(array, fn, options?)`
|
|
70
131
|
|
|
@@ -88,7 +149,7 @@ const evens = await filter(hugeArray, (x) => x % 2 === 0);
|
|
|
88
149
|
|
|
89
150
|
### `reduce(array, fn, initial, options?)`
|
|
90
151
|
|
|
91
|
-
Parallel `Array.prototype.reduce`. Each worker reduces its chunk, then partial results are reduced on the main thread.
|
|
152
|
+
Parallel `Array.prototype.reduce`. Each worker reduces its chunk, then partial results are reduced on the main thread. The reducer must be **associative** — regrouping can change floating-point rounding, so this is not a drop-in replacement for sequential `Array.reduce`.
|
|
92
153
|
|
|
93
154
|
```ts
|
|
94
155
|
import { reduce } from "defuss-multicore";
|
|
@@ -96,6 +157,85 @@ import { reduce } from "defuss-multicore";
|
|
|
96
157
|
const sum = await reduce(hugeArray, (a, b) => a + b, 0);
|
|
97
158
|
```
|
|
98
159
|
|
|
160
|
+
`map`/`filter`/`reduce` cache one pool per callback + core configuration. Use `releaseArrayWorkers(callback)` to release a cached pool explicitly; idle workers otherwise expire.
|
|
161
|
+
|
|
162
|
+
### Module workers & task pools
|
|
163
|
+
|
|
164
|
+
For real application code — normal ESM imports, module-local state, async handlers — define a typed worker module and drive it with an explicit task pool.
|
|
165
|
+
|
|
166
|
+
`worker.ts` — runs inside the worker:
|
|
167
|
+
|
|
168
|
+
```ts
|
|
169
|
+
import { expose, transfer } from "defuss-multicore/worker";
|
|
170
|
+
|
|
171
|
+
let calls = 0;
|
|
172
|
+
export const tasks = {
|
|
173
|
+
sum(values: Float64Array) {
|
|
174
|
+
let total = 0;
|
|
175
|
+
for (const value of values) total += value;
|
|
176
|
+
return total;
|
|
177
|
+
},
|
|
178
|
+
async counter(_: null) { return ++calls; },
|
|
179
|
+
double(values: Float64Array<ArrayBuffer>) {
|
|
180
|
+
for (let i = 0; i < values.length; i++) values[i] *= 2;
|
|
181
|
+
return transfer({ values }, [values.buffer]); // explicit zero-copy move
|
|
182
|
+
},
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
await expose(tasks, { init: async () => { calls = 0; } });
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
Application side (browser shown; Node.js is identical with `Worker` from `node:worker_threads`, and Bun takes either that one or its global `Worker`):
|
|
189
|
+
|
|
190
|
+
```ts
|
|
191
|
+
import { createPool } from "defuss-multicore";
|
|
192
|
+
import type { tasks } from "./worker.js";
|
|
193
|
+
|
|
194
|
+
const pool = createPool<typeof tasks>({
|
|
195
|
+
worker: () => new Worker(new URL("./worker.ts", import.meta.url), { type: "module" }),
|
|
196
|
+
maxWorkers: 2,
|
|
197
|
+
maxQueue: 32,
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
try {
|
|
201
|
+
await pool.warmup();
|
|
202
|
+
const input = new Float64Array([1, 2, 3]);
|
|
203
|
+
const result = await pool.run("double", input, { transfer: [input.buffer] });
|
|
204
|
+
console.log(result.values); // [2, 4, 6]; input.buffer is detached
|
|
205
|
+
} finally {
|
|
206
|
+
await pool.close();
|
|
207
|
+
}
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
Keep the `new Worker(new URL(..., import.meta.url), { type: "module" })` expression at the application call site so Vite can bundle the worker graph (use `worker.format: "es"` for top-level await). See [examples/node](examples/node) and [examples/vite](examples/vite).
|
|
211
|
+
|
|
212
|
+
#### Pool contract
|
|
213
|
+
|
|
214
|
+
| API | Behavior |
|
|
215
|
+
| --- | --- |
|
|
216
|
+
| `createPool<Tasks>(options)` | One explicit pool shared by all registered task names. Default workers: `max(1, min(4, cores - 1))`. |
|
|
217
|
+
| `run(name, payload, options?)` | Always worker execution — no size threshold or silent main-thread fallback. Awaits sync/async handlers. |
|
|
218
|
+
| `batch(name, jobs, options?)` | Ordered results. Default `chunkSize: 1`, `concurrency: maxWorkers`. Bounded outstanding chunks. |
|
|
219
|
+
| `stream(name, jobs, options?)` | Actual completion order across chunks; input order within each chunk. Yields `{ index, value }` with backpressure. |
|
|
220
|
+
| `warmup(count?)` | Spawn up to the pool cap and await module init/ready handshakes. |
|
|
221
|
+
| `close()` | Reject new submissions, drain accepted work, await termination. Idempotent. |
|
|
222
|
+
| `terminate()` | Reject pending/active jobs, stop workers, await shutdown. Idempotent. |
|
|
223
|
+
| `stats` | `workers`, `ready`, `active`, `queued`, lifecycle `state`, cumulative `completed`/`failed`/`cancelled`. |
|
|
224
|
+
|
|
225
|
+
Pool options: `maxWorkers`, `maxQueue` (default 128), `idleTimeoutMs` (30,000), `startupTimeoutMs` (10,000), `onTask(timing)`.
|
|
226
|
+
|
|
227
|
+
`run` options: `signal`, `transfer` (explicit list), `priority` (larger first; FIFO for ties; never preempts), `timeoutMs` (covers queue wait + execution).
|
|
228
|
+
|
|
229
|
+
`batch`/`stream` additionally accept `chunkSize`, `concurrency` and `transfer(payload, index)`. Each chunk invokes the single-item handler sequentially, amortizing one round trip across its items.
|
|
230
|
+
|
|
231
|
+
#### Lifecycle, errors and cancellation
|
|
232
|
+
|
|
233
|
+
`expose(tasks, { init })` awaits initialization before accepting tasks; every replacement worker re-initializes. Jobs execute sequentially per worker, and workers retain module-local caches between jobs — keep caches bounded and reconstructible.
|
|
234
|
+
|
|
235
|
+
Queued cancellation removes the job immediately. Cancelling or timing out a *running* job terminates its worker (**hard cancellation** — `finally` blocks are not guaranteed) and reschedules waiting work on surviving/replacement workers. Worker crashes reject only that worker's active job; tasks are never retried automatically.
|
|
236
|
+
|
|
237
|
+
Payloads and results are structured-cloned by default. `transfer(value, list)` moves listed buffers (including nested ones) — this detaches the sender's *entire* backing buffer, aliases included, and cancellation does not restore moved inputs. `SharedArrayBuffer` is never transferred; shared-memory synchronization is the caller's responsibility.
|
|
238
|
+
|
|
99
239
|
### `dotProduct(as, bs)`
|
|
100
240
|
|
|
101
241
|
Batch dot product of vector pairs. JIT loop-unrolled (up to 16x unroll).
|
|
@@ -107,7 +247,7 @@ import { dotProduct } from "defuss-multicore";
|
|
|
107
247
|
const scores: Float32Array = dotProduct(embeddings, queries);
|
|
108
248
|
```
|
|
109
249
|
|
|
110
|
-
- Input:
|
|
250
|
+
- Input: arrays of vector pairs (each inner element is one vector)
|
|
111
251
|
- Output: `Float32Array` of dot products
|
|
112
252
|
|
|
113
253
|
### `matmul(A, B)`
|
|
@@ -133,7 +273,7 @@ const diff = matsub(A, B);
|
|
|
133
273
|
const quot = matdiv(A, B);
|
|
134
274
|
```
|
|
135
275
|
|
|
136
|
-
All matrix ops use `Matrix<Float64Array>`
|
|
276
|
+
All matrix ops use `Matrix<Float64Array>` — an array of row vectors (`Float64Array[]`). The math ops run **synchronously on the caller thread**; combine them with `multicore()` or a task pool if you want them in workers.
|
|
137
277
|
|
|
138
278
|
### `getPoolSize()`
|
|
139
279
|
|
|
@@ -145,7 +285,7 @@ import { getPoolSize } from "defuss-multicore";
|
|
|
145
285
|
console.log(`Using ${getPoolSize()} cores`);
|
|
146
286
|
```
|
|
147
287
|
|
|
148
|
-
|
|
288
|
+
### Types
|
|
149
289
|
|
|
150
290
|
```ts
|
|
151
291
|
type NumericArray = number[] | Float32Array | Float64Array | Int8Array | ...;
|
|
@@ -155,13 +295,13 @@ type Vectors<T> = T[]; // Array of vectors
|
|
|
155
295
|
interface ParallelResult<R> extends AsyncIterable<R>, PromiseLike<R[]> {}
|
|
156
296
|
```
|
|
157
297
|
|
|
158
|
-
##
|
|
298
|
+
## Speed
|
|
159
299
|
|
|
160
|
-
All benchmarks measured on Node.js (worker_threads) on Apple Silicon (10 cores). Median of 5 runs, 2 warmup. Reproduce with `bun run bench
|
|
300
|
+
All benchmarks measured on Node.js (worker_threads) on Apple Silicon (10 cores). Median of 5 runs, 2 warmup. Reproduce with `bun run bench` (or `npm run bench`).
|
|
161
301
|
|
|
162
|
-
### Loop-
|
|
302
|
+
### Loop-unrolled ops vs naive baseline
|
|
163
303
|
|
|
164
|
-
Single-threaded comparison
|
|
304
|
+
Single-threaded comparison — same thread, unrolled kernels vs naive loops:
|
|
165
305
|
|
|
166
306
|
| Operation | Size | Speedup |
|
|
167
307
|
|-----------|------|---------|
|
|
@@ -172,11 +312,11 @@ Single-threaded comparison - same thread, unrolled kernels vs naive loops:
|
|
|
172
312
|
| **matsub** | 1000 x 1000 | 0.49x |
|
|
173
313
|
| **matdiv** | 1000 x 1000 | 0.37x |
|
|
174
314
|
|
|
175
|
-
Loop unrolling shines on **compute-heavy inner loops** like matrix multiplication, where the unrolled kernel avoids branch overhead and allows the CPU to pipeline instructions. Element-wise ops (add/sub/div) benefit less because the operation per element is trivial
|
|
315
|
+
Loop unrolling shines on **compute-heavy inner loops** like matrix multiplication, where the unrolled kernel avoids branch overhead and allows the CPU to pipeline instructions. Element-wise ops (add/sub/div) benefit less because the operation per element is trivial — the memory access pattern dominates.
|
|
176
316
|
|
|
177
|
-
### Multicore
|
|
317
|
+
### Multicore workers vs single-thread
|
|
178
318
|
|
|
179
|
-
Worker parallelism
|
|
319
|
+
Worker parallelism — dispatching across all CPU cores vs running on the main thread:
|
|
180
320
|
|
|
181
321
|
| Workload | Size | Speedup |
|
|
182
322
|
|----------|------|---------|
|
|
@@ -188,44 +328,59 @@ Worker parallelism - dispatching across all CPU cores vs running on the main thr
|
|
|
188
328
|
| **Filter** elements | 2M items | 0.39x |
|
|
189
329
|
| **Sum** (accumulate) | 10M items | 0.06x |
|
|
190
330
|
|
|
191
|
-
|
|
331
|
+
### Task-pool workload (module workers)
|
|
332
|
+
|
|
333
|
+
`bun run bench:tasks` runs the same deterministic chunk kernel on the caller thread and on 1/2/4 pooled workers, comparing every output element for exact equality. On the verification machine (64 chunks, 1 MiB output, warmed workers):
|
|
334
|
+
|
|
335
|
+
| Workers | Startup ms | Median task ms |
|
|
336
|
+
| --- | ---: | ---: |
|
|
337
|
+
| Caller thread | — | 44.78 |
|
|
338
|
+
| 1 | 100.73 | 58.73 |
|
|
339
|
+
| 2 | 123.33 | 26.81 |
|
|
340
|
+
| 4 | 153.92 | 17.55 |
|
|
341
|
+
|
|
342
|
+
Four warmed workers were ~2.55x faster than the caller thread, but cold startup exceeded the task duration, and one worker was *slower* than no workers. Persistent reuse and sufficiently large jobs matter.
|
|
343
|
+
|
|
344
|
+
## When to use it
|
|
192
345
|
|
|
193
346
|
The benchmarks tell a clear story: **worker parallelism pays off when each chunk does meaningful CPU work**. The overhead of serializing data, posting messages, and collecting results is ~2-10ms per dispatch. If the per-chunk work is under that threshold, you lose.
|
|
194
347
|
|
|
195
|
-
### DO:
|
|
348
|
+
### DO: parallelize these
|
|
196
349
|
|
|
197
|
-
- **Key derivation / password hashing**
|
|
198
|
-
- **Batch checksumming** (CRC32, SHA, etc.) of large messages
|
|
199
|
-
- **Heavy per-element computation**
|
|
350
|
+
- **Key derivation / password hashing** — thousands of rounds per item (4.9x speedup)
|
|
351
|
+
- **Batch checksumming** (CRC32, SHA, etc.) of large messages — enough work per chunk to amortize dispatch
|
|
352
|
+
- **Heavy per-element computation** — image processing, physics simulation, compression
|
|
200
353
|
- **Any workload where each chunk runs >5ms** on a single core
|
|
201
354
|
|
|
202
|
-
### DON'T:
|
|
355
|
+
### DON'T: parallelize these
|
|
203
356
|
|
|
204
|
-
- **Simple reductions** (sum, min, max)
|
|
205
|
-
- **Trivial transforms** (multiply, add constant)
|
|
206
|
-
- **Small arrays** (<1024 elements)
|
|
207
|
-
- **Single function calls**
|
|
208
|
-
- **I/O-bound work**
|
|
357
|
+
- **Simple reductions** (sum, min, max) — main-thread loop is faster than worker dispatch
|
|
358
|
+
- **Trivial transforms** (multiply, add constant) — memory-bandwidth bound, not CPU-bound
|
|
359
|
+
- **Small arrays** (<1024 elements) — the `threshold` option exists for this reason
|
|
360
|
+
- **Single function calls** — multicore is for **batches**, not individual invocations
|
|
361
|
+
- **I/O-bound work** — fetch, file reads, DB queries are already async; workers add overhead
|
|
209
362
|
|
|
210
|
-
### DO:
|
|
363
|
+
### DO: use loop-unrolled ops
|
|
211
364
|
|
|
212
365
|
- **`matmul`** for matrix multiplication, neural network layers (2x+ speedup)
|
|
213
366
|
- **`matadd`** for accumulating matrices (2.1x)
|
|
214
367
|
- **`dotProduct`** for embedding similarity, cosine distance, attention scores (1.5x+ speedup)
|
|
215
368
|
|
|
216
|
-
### Key
|
|
369
|
+
### Key principles
|
|
217
370
|
|
|
218
|
-
1. **Measure first.** The `threshold` option exists so small inputs fall back to the main thread automatically. But "small" depends on your workload
|
|
371
|
+
1. **Measure first.** The `threshold` option exists so small inputs fall back to the main thread automatically. But "small" depends on your workload — a 10K-element array of simple additions is too small; a 10K-element array of 1000-round hash stretches is perfect.
|
|
219
372
|
|
|
220
|
-
2. **Worker functions must be pure.**
|
|
373
|
+
2. **Worker functions must be pure.** `multicore()` serializes functions into isolated contexts — no closures, no imports, no DOM access. Everything the function needs must be passed as arguments or computed inline. Need imports and module state? Use module workers with `createPool()`.
|
|
221
374
|
|
|
222
|
-
3. **
|
|
375
|
+
3. **Transfers are explicit for pools, partition-only for `multicore()`.** With task pools you list transferables yourself (`transfer: [buf]`) and the buffer detaches. With `multicore()`, only internal partition copies are transferred — your inputs stay attached. Use `{ transfer: false }` to disable partition transfers.
|
|
223
376
|
|
|
224
377
|
4. **Use `reduce` for aggregation.** Without it, you get back an array of partial results (one per worker). With `reduce`, partial results are combined into a single value.
|
|
225
378
|
|
|
226
|
-
5. **Use `eager: true` for latency-sensitive paths.** By default,
|
|
379
|
+
5. **Use `eager: true` (or `warmup()`) for latency-sensitive paths.** By default, worker pools are created lazily on first call. Pre-spawn workers when the first call must be fast.
|
|
227
380
|
|
|
228
|
-
##
|
|
381
|
+
## Patterns
|
|
382
|
+
|
|
383
|
+
### Crypto/compression worker
|
|
229
384
|
|
|
230
385
|
```ts
|
|
231
386
|
import { multicore } from "defuss-multicore";
|
|
@@ -265,7 +420,7 @@ const parallelCRC32 = multicore(
|
|
|
265
420
|
const checksums = await parallelCRC32(messageIndices);
|
|
266
421
|
```
|
|
267
422
|
|
|
268
|
-
|
|
423
|
+
### Streaming results
|
|
269
424
|
|
|
270
425
|
```ts
|
|
271
426
|
const parallel = multicore(heavyComputation);
|
|
@@ -274,9 +429,14 @@ const parallel = multicore(heavyComputation);
|
|
|
274
429
|
for await (const result of parallel(data)) {
|
|
275
430
|
console.log("Worker finished:", result);
|
|
276
431
|
}
|
|
432
|
+
|
|
433
|
+
// Task pools: actual completion order across chunks
|
|
434
|
+
for await (const { index, value } of pool.stream("taskName", jobs)) {
|
|
435
|
+
console.log(index, value);
|
|
436
|
+
}
|
|
277
437
|
```
|
|
278
438
|
|
|
279
|
-
|
|
439
|
+
### Cancellation
|
|
280
440
|
|
|
281
441
|
```ts
|
|
282
442
|
const controller = new AbortController();
|
|
@@ -294,21 +454,44 @@ try {
|
|
|
294
454
|
}
|
|
295
455
|
```
|
|
296
456
|
|
|
297
|
-
##
|
|
457
|
+
## What "verified" means
|
|
298
458
|
|
|
299
|
-
|
|
300
|
-
# Unit tests (272 tests)
|
|
301
|
-
bun run test
|
|
459
|
+
Every claim in this README is backed by a suite you can run. A missing check counts as unverified, and unverified fails `bun run verify`.
|
|
302
460
|
|
|
303
|
-
|
|
304
|
-
bun run test:browser
|
|
305
|
-
|
|
461
|
+
- `bun run test` — 293 unit tests on Node.js (`worker_threads`): partitioning, transfer ownership, cancellation, crash isolation, queue bounds
|
|
462
|
+
- `bun run test:browser` — 25 E2E tests in real Chromium via Playwright (Web Workers, no mocks)
|
|
463
|
+
- `bun run test:production` — builds the Vite example with the production bundler and runs real browser workers against the built artifact
|
|
464
|
+
- `bun run test:package` — installs the published tarball in an isolated directory and exercises both the ESM and the CJS entry points
|
|
465
|
+
- `bun run verify` — all of the above plus `tsc` typechecks, including compile-time negative tests for wrong result types
|
|
466
|
+
|
|
467
|
+
Browser tests need Chromium: `bunx playwright install chromium`, or set `PLAYWRIGHT_CHROMIUM_EXECUTABLE` to an existing executable. All `npm run ...` equivalents work as well.
|
|
468
|
+
|
|
469
|
+
### Deliberate limits
|
|
470
|
+
|
|
471
|
+
No automatic retries, no worker affinity, no cross-worker state synchronization, no shared-memory protocol, no distributed execution, no automatic tuning. The math kernels are synchronous and stay on the caller thread. `close()` waits for non-terminating tasks that lack timeouts — use `terminate()` to stop them. Stale-result checks and authoritative state commits remain caller responsibilities. Implementation history and compatibility notes live in [CHANGELOG.md](CHANGELOG.md).
|
|
306
472
|
|
|
307
473
|
## Requirements
|
|
308
474
|
|
|
309
|
-
- **Node.js** ^18.17.1 || ^20.3.0 || >=21.0.0
|
|
310
|
-
- **
|
|
475
|
+
- **Node.js** ^18.17.1 || ^20.3.0 || >=21.0.0 (developed and verified on Node 24)
|
|
476
|
+
- **Bun** 1.x works as installer, script runner and runtime
|
|
477
|
+
- **Browser** — any browser with Web Workers + structured clone (module workers require ES module worker support)
|
|
478
|
+
|
|
479
|
+
## Citation
|
|
480
|
+
|
|
481
|
+
If you use defuss-multicore in research or want to reference it, cite it as:
|
|
482
|
+
|
|
483
|
+
```bibtex
|
|
484
|
+
@misc{homberg2026defussmulticore,
|
|
485
|
+
author = {Homberg, Aron},
|
|
486
|
+
affiliation = {Independent Researcher},
|
|
487
|
+
title = {defuss-multicore: Isomorphic Multicore Execution and Loop-Unrolled Linear Algebra for JavaScript},
|
|
488
|
+
year = {2026},
|
|
489
|
+
version = {0.1.0},
|
|
490
|
+
howpublished = {\url{https://www.npmjs.com/package/defuss-multicore}},
|
|
491
|
+
note = {npm package, MIT License}
|
|
492
|
+
}
|
|
493
|
+
```
|
|
311
494
|
|
|
312
495
|
## License
|
|
313
496
|
|
|
314
|
-
MIT
|
|
497
|
+
MIT — see [LICENSE](LICENSE).
|