defuss-multicore 0.0.3 → 0.1.0

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 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
@@ -2,16 +2,18 @@
2
2
 
3
3
  Isomorphic multicore execution + loop-unrolled linear algebra for JavaScript/TypeScript.
4
4
 
5
- - **Web Workers** in the browser, **worker_threads** in Node.js - same API
5
+ - **Web Workers** in the browser, **worker_threads** in Node.js — same API
6
6
  - Auto-splits arrays/TypedArrays across CPU cores
7
7
  - JIT loop-unrolled vector/matrix ops (4x/8x/16x unroll factors, auto-selected)
8
8
  - Parallel `map`, `filter`, `reduce` for any array
9
+ - Typed **module workers** with task pools: batching, streaming, priorities, timeouts, cancellation
9
10
  - Zero dependencies, ESM + CJS dual output
10
11
 
11
12
  ## Install
12
13
 
13
14
  ```bash
14
15
  bun add defuss-multicore
16
+ # or: npm install defuss-multicore
15
17
  ```
16
18
 
17
19
  ## Quick Start
@@ -47,13 +49,14 @@ for await (const r of parallel(data)) { ... } // stream as workers finish
47
49
 
48
50
  - Array/TypedArray args are **auto-split** across cores
49
51
  - Scalar args are **broadcast** to every worker
50
- - Returns `ParallelResult<R>` - both `PromiseLike<R[]>` and `AsyncIterable<R>`
52
+ - Returns `ParallelResult<R>` — both `PromiseLike<R[]>` and `AsyncIterable<R>`
53
+ - The callable also exposes `warmup()`, `close()` and `terminate()`
51
54
 
52
55
  #### `MulticoreOptions<R>`
53
56
 
54
57
  | Option | Type | Default | Description |
55
58
  |-------------|---------------------------|------------------------|-------------|
56
- | `cores` | `number` | `navigator.hardwareConcurrency` | Number of worker threads |
59
+ | `cores` | `number` | available CPU cores | Number of worker threads |
57
60
  | `threshold` | `number` | `1024` | Min array length before parallelizing (falls back to main thread below this) |
58
61
  | `reduce` | `(a: R, b: R) => R` | - | Reduce partial results into a single value |
59
62
  | `eager` | `boolean` | `false` | Pre-spawn workers immediately instead of on first call |
@@ -62,9 +65,13 @@ for await (const r of parallel(data)) { ... } // stream as workers finish
62
65
 
63
66
  | Option | Type | Default | Description |
64
67
  |------------|----------------|----------|-------------|
65
- | `cores` | `number` | - | Override core count for this call |
68
+ | `cores` | `number` | - | Override partition count for this call (within the pool cap) |
66
69
  | `signal` | `AbortSignal` | - | Cancel in-flight workers |
67
- | `transfer` | `boolean` | `true` | Auto-detect and transfer ArrayBuffer ownership (zero-copy) |
70
+ | `transfer` | `boolean` | `true` | Transfer the internally created partition buffers (see ownership note below) |
71
+
72
+ **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 }`.
73
+
74
+ **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
75
 
69
76
  ### `map(array, fn, options?)`
70
77
 
@@ -88,7 +95,7 @@ const evens = await filter(hugeArray, (x) => x % 2 === 0);
88
95
 
89
96
  ### `reduce(array, fn, initial, options?)`
90
97
 
91
- Parallel `Array.prototype.reduce`. Each worker reduces its chunk, then partial results are reduced on the main thread.
98
+ 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
99
 
93
100
  ```ts
94
101
  import { reduce } from "defuss-multicore";
@@ -96,6 +103,85 @@ import { reduce } from "defuss-multicore";
96
103
  const sum = await reduce(hugeArray, (a, b) => a + b, 0);
97
104
  ```
98
105
 
106
+ `map`/`filter`/`reduce` cache one pool per callback + core configuration. Use `releaseArrayWorkers(callback)` to release a cached pool explicitly; idle workers otherwise expire.
107
+
108
+ ### Module workers & task pools
109
+
110
+ 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.
111
+
112
+ `worker.ts` — runs inside the worker:
113
+
114
+ ```ts
115
+ import { expose, transfer } from "defuss-multicore/worker";
116
+
117
+ let calls = 0;
118
+ export const tasks = {
119
+ sum(values: Float64Array) {
120
+ let total = 0;
121
+ for (const value of values) total += value;
122
+ return total;
123
+ },
124
+ async counter(_: null) { return ++calls; },
125
+ double(values: Float64Array<ArrayBuffer>) {
126
+ for (let i = 0; i < values.length; i++) values[i] *= 2;
127
+ return transfer({ values }, [values.buffer]); // explicit zero-copy move
128
+ },
129
+ };
130
+
131
+ await expose(tasks, { init: async () => { calls = 0; } });
132
+ ```
133
+
134
+ Application side (browser shown; Node is identical with `Worker` from `node:worker_threads`):
135
+
136
+ ```ts
137
+ import { createPool } from "defuss-multicore";
138
+ import type { tasks } from "./worker.js";
139
+
140
+ const pool = createPool<typeof tasks>({
141
+ worker: () => new Worker(new URL("./worker.ts", import.meta.url), { type: "module" }),
142
+ maxWorkers: 2,
143
+ maxQueue: 32,
144
+ });
145
+
146
+ try {
147
+ await pool.warmup();
148
+ const input = new Float64Array([1, 2, 3]);
149
+ const result = await pool.run("double", input, { transfer: [input.buffer] });
150
+ console.log(result.values); // [2, 4, 6]; input.buffer is detached
151
+ } finally {
152
+ await pool.close();
153
+ }
154
+ ```
155
+
156
+ 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` and `examples/vite`.
157
+
158
+ #### Pool contract
159
+
160
+ | API | Behavior |
161
+ | --- | --- |
162
+ | `createPool<Tasks>(options)` | One explicit pool shared by all registered task names. Default workers: `max(1, min(4, cores - 1))`. |
163
+ | `run(name, payload, options?)` | Always worker execution — no size threshold or silent main-thread fallback. Awaits sync/async handlers. |
164
+ | `batch(name, jobs, options?)` | Ordered results. Default `chunkSize: 1`, `concurrency: maxWorkers`. Bounded outstanding chunks. |
165
+ | `stream(name, jobs, options?)` | Actual completion order across chunks; input order within each chunk. Yields `{ index, value }` with backpressure. |
166
+ | `warmup(count?)` | Spawn up to the pool cap and await module init/ready handshakes. |
167
+ | `close()` | Reject new submissions, drain accepted work, await termination. Idempotent. |
168
+ | `terminate()` | Reject pending/active jobs, stop workers, await shutdown. Idempotent. |
169
+ | `stats` | `workers`, `ready`, `active`, `queued`, lifecycle `state`, cumulative `completed`/`failed`/`cancelled`. |
170
+
171
+ Pool options: `maxWorkers`, `maxQueue` (default 128), `idleTimeoutMs` (30,000), `startupTimeoutMs` (10,000), `onTask(timing)`.
172
+
173
+ `run` options: `signal`, `transfer` (explicit list), `priority` (larger first; FIFO for ties; never preempts), `timeoutMs` (covers queue wait + execution).
174
+
175
+ `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.
176
+
177
+ #### Lifecycle, errors and cancellation
178
+
179
+ `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.
180
+
181
+ 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.
182
+
183
+ 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.
184
+
99
185
  ### `dotProduct(as, bs)`
100
186
 
101
187
  Batch dot product of vector pairs. JIT loop-unrolled (up to 16x unroll).
@@ -107,7 +193,7 @@ import { dotProduct } from "defuss-multicore";
107
193
  const scores: Float32Array = dotProduct(embeddings, queries);
108
194
  ```
109
195
 
110
- - Input: `Float64Array[]` pairs (each inner array is one vector)
196
+ - Input: arrays of vector pairs (each inner element is one vector)
111
197
  - Output: `Float32Array` of dot products
112
198
 
113
199
  ### `matmul(A, B)`
@@ -133,7 +219,7 @@ const diff = matsub(A, B);
133
219
  const quot = matdiv(A, B);
134
220
  ```
135
221
 
136
- All matrix ops use `Matrix<Float64Array>` - an array of row vectors (`Float64Array[]`).
222
+ 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
223
 
138
224
  ### `getPoolSize()`
139
225
 
@@ -157,11 +243,11 @@ interface ParallelResult<R> extends AsyncIterable<R>, PromiseLike<R[]> {}
157
243
 
158
244
  ## Benchmark Results
159
245
 
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`.
246
+ 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
247
 
162
248
  ### Loop-Unrolled Ops vs Naive Baseline
163
249
 
164
- Single-threaded comparison - same thread, unrolled kernels vs naive loops:
250
+ Single-threaded comparison — same thread, unrolled kernels vs naive loops:
165
251
 
166
252
  | Operation | Size | Speedup |
167
253
  |-----------|------|---------|
@@ -172,11 +258,11 @@ Single-threaded comparison - same thread, unrolled kernels vs naive loops:
172
258
  | **matsub** | 1000 x 1000 | 0.49x |
173
259
  | **matdiv** | 1000 x 1000 | 0.37x |
174
260
 
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 - the memory access pattern dominates.
261
+ 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
262
 
177
263
  ### Multicore Workers vs Single-Thread
178
264
 
179
- Worker parallelism - dispatching across all CPU cores vs running on the main thread:
265
+ Worker parallelism — dispatching across all CPU cores vs running on the main thread:
180
266
 
181
267
  | Workload | Size | Speedup |
182
268
  |----------|------|---------|
@@ -188,24 +274,37 @@ Worker parallelism - dispatching across all CPU cores vs running on the main thr
188
274
  | **Filter** elements | 2M items | 0.39x |
189
275
  | **Sum** (accumulate) | 10M items | 0.06x |
190
276
 
277
+ ### Task-pool workload (module workers)
278
+
279
+ `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):
280
+
281
+ | Workers | Startup ms | Median task ms |
282
+ | --- | ---: | ---: |
283
+ | Caller thread | — | 44.78 |
284
+ | 1 | 100.73 | 58.73 |
285
+ | 2 | 123.33 | 26.81 |
286
+ | 4 | 153.92 | 17.55 |
287
+
288
+ 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.
289
+
191
290
  ## When to Use `multicore()`
192
291
 
193
292
  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
293
 
195
294
  ### DO: Parallelize These
196
295
 
197
- - **Key derivation / password hashing** - thousands of rounds per item (4.9x speedup)
198
- - **Batch checksumming** (CRC32, SHA, etc.) of large messages - enough work per chunk to amortize dispatch
199
- - **Heavy per-element computation** - image processing, physics simulation, compression
296
+ - **Key derivation / password hashing** — thousands of rounds per item (4.9x speedup)
297
+ - **Batch checksumming** (CRC32, SHA, etc.) of large messages — enough work per chunk to amortize dispatch
298
+ - **Heavy per-element computation** — image processing, physics simulation, compression
200
299
  - **Any workload where each chunk runs >5ms** on a single core
201
300
 
202
301
  ### DON'T: Parallelize These
203
302
 
204
- - **Simple reductions** (sum, min, max) - main-thread loop is faster than worker dispatch
205
- - **Trivial transforms** (multiply, add constant) - memory-bandwidth bound, not CPU-bound
206
- - **Small arrays** (<1024 elements) - the `threshold` option exists for this reason
207
- - **Single function calls** - multicore is for **batches**, not individual invocations
208
- - **I/O-bound work** - fetch, file reads, DB queries are already async; workers add overhead
303
+ - **Simple reductions** (sum, min, max) — main-thread loop is faster than worker dispatch
304
+ - **Trivial transforms** (multiply, add constant) — memory-bandwidth bound, not CPU-bound
305
+ - **Small arrays** (<1024 elements) — the `threshold` option exists for this reason
306
+ - **Single function calls** — multicore is for **batches**, not individual invocations
307
+ - **I/O-bound work** — fetch, file reads, DB queries are already async; workers add overhead
209
308
 
210
309
  ### DO: Use Loop-Unrolled Ops
211
310
 
@@ -215,15 +314,15 @@ The benchmarks tell a clear story: **worker parallelism pays off when each chunk
215
314
 
216
315
  ### Key Principles
217
316
 
218
- 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.
317
+ 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
318
 
220
- 2. **Worker functions must be pure.** They run in isolated contexts - no closures, no imports, no DOM access. Everything the function needs must be passed as arguments or computed inline.
319
+ 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
320
 
222
- 3. **Transferables are auto-detected.** ArrayBuffers are transferred (zero-copy) by default. Disable with `{ transfer: false }` if you need to reuse the buffer after the call.
321
+ 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
322
 
224
323
  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
324
 
226
- 5. **Use `eager: true` for latency-sensitive paths.** By default, the worker pool is created lazily on first call. Set `eager: true` to pre-spawn workers at wrap time.
325
+ 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
326
 
228
327
  ## Pattern: Crypto/Compression Worker
229
328
 
@@ -274,6 +373,11 @@ const parallel = multicore(heavyComputation);
274
373
  for await (const result of parallel(data)) {
275
374
  console.log("Worker finished:", result);
276
375
  }
376
+
377
+ // Task pools: actual completion order across chunks
378
+ for await (const { index, value } of pool.stream("taskName", jobs)) {
379
+ console.log(index, value);
380
+ }
277
381
  ```
278
382
 
279
383
  ## Pattern: Cancellation
@@ -297,17 +401,29 @@ try {
297
401
  ## Testing
298
402
 
299
403
  ```bash
300
- # Unit tests (272 tests)
404
+ # Unit tests (293 tests, Node)
301
405
  bun run test
302
406
 
303
- # Browser E2E tests via Playwright (21 tests)
407
+ # Browser E2E tests via Playwright (25 tests, real Chromium)
304
408
  bun run test:browser
409
+
410
+ # Production smoke test (Vite build + real browser workers)
411
+ bun run test:production
412
+
413
+ # Package smoke test (isolated tarball install, ESM + CJS)
414
+ bun run test:package
415
+
416
+ # Everything, including typechecks
417
+ bun run verify
305
418
  ```
306
419
 
420
+ All `npm run ...` equivalents work as well. Browser tests need Chromium: `bunx playwright install chromium`, or set `PLAYWRIGHT_CHROMIUM_EXECUTABLE` to an existing executable. Implementation and compatibility notes live in `CHANGELOG.md`.
421
+
307
422
  ## Requirements
308
423
 
309
- - **Node.js** ^18.17.1 || ^20.3.0 || >=21.0.0
310
- - **Browser** Any browser with Web Workers + structured clone
424
+ - **Node.js** ^18.17.1 || ^20.3.0 || >=21.0.0 (developed and verified on Node 24)
425
+ - **Bun** 1.x works as installer, script runner and runtime
426
+ - **Browser** — any browser with Web Workers + structured clone (module workers require ES module worker support)
311
427
 
312
428
  ## License
313
429