Skip to content

feat: support plain Node by running codec workers on node:worker_threads - #11

Merged
thewtex merged 3 commits into
mainfrom
worker-path
Aug 7, 2026
Merged

thewtex merged 3 commits into
mainfrom
worker-path

Conversation

@thewtex

@thewtex thewtex commented Aug 7, 2026 •

Copy link
Copy Markdown
Member

Why

The worker path was entirely broken outside a browser. Plain Node has no global Worker, so the moment a pooled task fell back to new Worker(...) it threw:

ReferenceError: Worker is not defined

That made getWorker/setWorker unusable in Node, and because nothing in the suite ran outside Chromium, the breakage was invisible. This adds node:worker_threads support behind the existing interface and puts the path under test.

What changed

@fideus-labs/worker-pool (1.0.0 → 2.0.0)

  • WorkerLike (src/types.ts) — the slice of the Worker API the pool and its tasks actually use: postMessage, terminate, addEventListener, removeEventListener. WorkerPoolTask and WorkerPool.workerQueue are now typed against it instead of the DOM global, which is what lets a single task function serve both runtimes. A browser Worker satisfies it structurally, so the pool is unchanged at runtime. Ships alongside WorkerMessageEventLike / WorkerErrorEventLike, since browsers deliver a MessageEvent/ErrorEvent and Node delivers a raw value/Error.
  • NodeWorker (src/node-worker.ts) — a worker_threads adapter behind that interface, plus createWorker(url) (picks per runtime) and isNodeRuntime().

@fideus-labs/fizarrita (1.4.1 → 2.0.0)

  • internals/codec-worker-core.ts — the message protocol and pipeline cache, lifted out of codec-worker.ts. codec-worker.ts is now a thin browser entry over self; codec-worker-node.ts is the parentPort equivalent. Both are exposed as subpath exports, as is handleCodecMessage, so a custom worker can extend the protocol without reimplementing it.
  • create-worker.ts — one createDefaultWorker/createCodecWorker, replacing the copy that previously existed in both get-worker.ts and set-worker.ts.

Implementation details worth reviewing

Keeping Node out of browser bundles. node:worker_threads is imported through a variable specifier carrying @vite-ignore and webpackIgnore, so bundlers never try to resolve it. Verified against a real production build (vite build on the benchmark): the specifier survives only as an inert string inside the branch guarded by typeof Worker, and no Node module is pulled in.

Keeping bundler worker-detection working. The two branches need opposite treatment, which is why createDefaultWorker looks asymmetric on purpose:

if (typeof Worker !== "undefined") {
  // Literal form — the only shape bundlers recognise as a worker entry point.
  return new Worker(new URL("./codec-worker.js", import.meta.url), { type: "module" })
}
// Behind a variable, so bundlers targeting the browser leave it alone.
const nodeEntry = "./codec-worker-node.js"
return new NodeWorker(new URL(nodeEntry, import.meta.url))

Confirmed in the built output: codec-worker-*.js is still emitted as a proper worker chunk with its dependency graph.

Synchronous constructor over an async import. NodeWorker can't get the ctor synchronously, but it must be a drop-in for new Worker(...). Messages posted before the thread exists queue on the same promise chain, which preserves their order (covered by a test).

Five ways a request could hang, closed. These callers are RPC layers waiting on a reply, so a dropped message reads to them as a request that never finishes — silence is worse than an error:

Case Behavior
Startup failure lands before listeners attach Latched and replayed on the next postMessage
Thread exits unrequested Raises an error even at exit code 0
postMessage after terminate() Raises rather than no-opping — a deliberate divergence from browser Worker
terminate() races thread startup, stranding a queued message Raises when the thread resolves
terminate() kills a thread with a request already on it terminate() raises; the exit handler cannot, since that exit was requested
Reply fails to post Retried without its payload

The last three are adjacent and were closed at different times — the third and fourth during self-review, the fifth from CodeRabbit's finding. Each regression test was verified by removing its fix and confirming the test fails; a test asserting "this does not hang" is worth little until you have watched it hang.

Testing

before after
Node 0 39
Browser 119 123

Node tests run against the built dist/ of both packages — what npm consumers actually get — and cover pool scheduling, transfer lists, worker-path forms (file: URL string vs. filesystem path), workerData, every error/exit/terminate path, and setWorker/getWorker round-trips through zstd, blosc, edge chunks, chunk cache, SharedArrayBuffer decode_into, and fill values. The four new browser tests cover the other branch of createWorker, which had no coverage at all. Wired into CI ahead of the Playwright step.

Settle-sensitive tests carry explicit timeouts: a regression in this area hangs rather than fails, which would block CI instead of reporting. Verified by patching the terminate-race fix back out — the regression test hung, reproducing the defect exactly.

Breaking change (types only) — hence the major bumps

A task callback annotated (worker: Worker | null) no longer typechecks under strictFunctionTypes and must say WorkerLike | null. fizarrita breaks more narrowly: createDefaultWorker() returns WorkerLike where it returned Worker.

Both packages go to 2.0.0. The break is compile-time only, but a consumer on ^1 running npm update would hit it with no opt-in, and there is no shim that avoids it — the break is contravariance in WorkerPoolTask's parameter, so preserving compatibility means keeping Worker, which is what made the pool unusable in Node. Also note that const w = worker ?? new Worker(...) infers the union WorkerLike | Worker, from which TypeScript picks the wrong postMessage overload — annotate the local. Both are documented in the README; in-repo callers are updated.

Incidental

pnpm install was exiting 1 before any of this: pnpm 11 no longer reads pnpm.onlyBuiltDependencies from package.json, leaving esbuild unapproved and every pnpm script failing. Moved to allowBuilds in pnpm-workspace.yaml. Not part of the feature, but nothing ran without it.

Note on codec availability

Which codecs work in Node is zarrita's business, not ours: zstd, blosc, lz4, and bytes have real implementations, while gzip, zlib, and crc32c throw "not enabled by default" and need a numcodecs codec registered inside a custom worker. Documented rather than worked around.

🤖 Generated with Claude Code

Plain Node has no global `Worker`, so every pooled task that fell back to
`new Worker(...)` threw `ReferenceError: Worker is not defined`. That made
`getWorker`/`setWorker` unusable outside a browser, and nothing exercised
the path, so it stayed broken silently.

worker-pool (1.0.0 -> 1.1.0):

- Add `WorkerLike`, the slice of the `Worker` API the pool and its tasks
  actually use, plus `WorkerMessageEventLike`/`WorkerErrorEventLike`.
  `WorkerPoolTask` and `WorkerPool.workerQueue` are typed against it rather
  than the DOM global, which is what lets one task function serve both
  runtimes. A browser `Worker` satisfies it structurally.
- Add `NodeWorker`, a `node:worker_threads` adapter behind that interface,
  plus `createWorker` (picks per runtime) and `isNodeRuntime`.
  `node:worker_threads` is imported through a variable specifier carrying
  `@vite-ignore`/`webpackIgnore`, so browser bundles never resolve it.

fizarrita (1.4.1 -> 1.5.0):

- Lift the codec protocol and pipeline cache out of `codec-worker.ts` into
  `internals/codec-worker-core.ts`. `codec-worker.ts` is now a thin browser
  entry; `codec-worker-node.ts` is the `parentPort` equivalent. Both are
  exposed as subpath exports, as is `handleCodecMessage`.
- Add `create-worker.ts` with a single `createDefaultWorker`/
  `createCodecWorker`, replacing the copy that existed in each of get/set.
  The browser branch keeps the literal `new Worker(new URL(...))` form
  bundlers need to detect a worker entry; the Node branch is deliberately
  hidden from them behind a variable.

Four ways a request could hang are closed, since a dropped message reads to
an RPC caller as a request that never finishes: a startup failure landing
before listeners attach is latched and replayed; an unrequested thread exit
raises an error even at code 0; posting after `terminate()` raises rather
than no-opping (a deliberate divergence from browser `Worker`); and a reply
that fails to post is retried without its payload.

Tests: 37 Node tests under `test/node/` covering pool scheduling, transfer
lists, worker-path forms, `workerData`, the error/exit/terminate paths, and
`setWorker`/`getWorker` round-trips through zstd, blosc, edge chunks, chunk
cache, SharedArrayBuffer `decode_into`, and fill values. Four browser tests
cover the other branch of `createWorker`. Wired into CI ahead of Playwright.

Also fixes `pnpm install` exiting 1: pnpm 11 no longer reads
`pnpm.onlyBuiltDependencies` from package.json, leaving esbuild unapproved
and every pnpm script failing. Moved to `allowBuilds` in pnpm-workspace.yaml.

Note for consumers: a task callback annotated `(worker: Worker | null)` no
longer typechecks under strictFunctionTypes and must say `WorkerLike | null`.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Copilot AI lite review requested due to automatic review settings August 7, 2026 18:10
@coderabbitai

coderabbitai Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The PR adds cross-runtime worker support through WorkerLike, implements a Node worker_threads adapter, centralizes codec-worker logic, selects workers by runtime, updates fizarrita integration, and adds browser, Node, package, documentation, and CI coverage.

Changes

Cross-runtime worker support

Layer / File(s) Summary
WorkerLike and Node worker runtime
src/types.ts, src/node-worker.ts, src/worker-pool.ts, src/index.ts, test/node/*
The worker pool now accepts browser-compatible and Node workers. NodeWorker adapts worker threads with queued messages, event handling, termination, and error propagation.
Shared codec protocol and runtime entry points
fizarrita/src/internals/codec-worker-core.ts, fizarrita/src/codec-worker.ts, fizarrita/src/codec-worker-node.ts, fizarrita/src/create-worker.ts
Codec protocol handling, pipeline caching, edge-shape correction, encode/decode operations, shared-buffer handling, and typed error replies now use shared logic for browser and Node workers.
Fizarrita worker integration
fizarrita/src/worker-rpc.ts, fizarrita/src/get-worker.ts, fizarrita/src/set-worker.ts, test/node/fizarrita.test.js, test/app/zarrita/*
Fizarrita worker RPC and get/set tasks now use WorkerLike and runtime-aware codec worker creation. Node tests cover codec operations, selections, caching, shared buffers, URLs, and failure handling.
Browser integration and documentation
test/app/main.ts, test/browser/runtime-worker.spec.ts, README.md, fizarrita/README.md
Browser runtime helpers and tests cover worker creation, pooling, codec initialization, cleanup, and runtime detection. Documentation describes browser and Node usage and worker lifecycle cleanup.
Package and CI wiring
package.json, pnpm-workspace.yaml, .github/workflows/ci.yml
Package metadata, exports, Node test commands, pnpm build approval, and separate Node and browser CI steps were added or updated.

Estimated code review effort: 4 (Complex) | ~60 minutes

Poem

Poem

A rabbit watched the workers run,
Through browser clouds and Node’s bright sun.
Codec messages hopped in line,
Cleanups closed each burrow fine.
Tests thumped softly: all is well.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 80.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the primary change: adding plain Node.js support through node:worker_threads for codec workers.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch worker-path

Comment @coderabbitai help to get the list of available commands.

@thewtex thewtex changed the title feat: run the worker path on node:worker_threads feat: support plain Node by running codec workers on node:worker_threads Aug 7, 2026

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds first-class Node.js support for the worker-pool runtime path by introducing a WorkerLike abstraction plus a node:worker_threads adapter, and refactors fizarrita’s codec worker into shared core logic with separate browser/Node entries. This makes getWorker/setWorker and pooled tasks usable in plain Node without a global Worker.

Changes:

  • Introduce WorkerLike, NodeWorker, createWorker(), and isNodeRuntime(); update the pool/task typing to be runtime-agnostic.
  • Split fizarrita’s codec worker into a shared core (handleCodecMessage) and thin browser/Node entry points; add runtime-aware codec worker creation helpers.
  • Add comprehensive Node test suite and wire it into CI; update docs and pnpm build-allowlist config.

Reviewed changes

Copilot reviewed 28 out of 28 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
test/node/worker-pool.test.js Node integration tests for WorkerPool scheduling, transfers, and NodeWorker behaviors.
test/node/square-worker.mjs Minimal worker_threads worker used by Node pool tests.
test/node/node-worker-api.test.js NodeWorker/createWorker API-surface tests (URL/path handling, workerData, terminate semantics).
test/node/fizarrita.test.js End-to-end Node tests for fizarrita get/set through the pool with real zarrita arrays.
test/node/exiting-worker.mjs Worker that exits without replying to validate “reject not hang” behavior.
test/node/echo-worker.mjs Worker that echoes workerData to validate constructor option pass-through.
test/node/codec-worker-core.test.js Direct tests of handleCodecMessage protocol/core logic without a worker thread.
test/browser/runtime-worker.spec.ts Browser coverage for runtime-aware worker factories and fizarrita default worker protocol.
test/app/zarrita/index.ts Update test app typings from Worker to WorkerLike for task signatures.
test/app/main.ts Expose runtime helpers to Playwright and update task helpers to use WorkerLike + event listeners.
src/worker-pool.ts Retype worker slots/queue to WorkerLike and update docs to reflect non-browser workers.
src/types.ts Add WorkerLike + event-like types; update WorkerPoolTask contract to use WorkerLike.
src/node-worker.ts Implement NodeWorker adapter + createWorker()/isNodeRuntime() runtime selection.
src/index.ts Export new Node runtime APIs and the new public types.
README.md Document Node support, WorkerLike, and recommended termination patterns (finally blocks).
pnpm-workspace.yaml Add pnpm build allowlist for esbuild to keep installs/scripts working.
package.json Bump version, add node-related keywords, add test:node script, update package description.
fizarrita/src/worker-rpc.ts Retype dispatcher to WorkerLike and use shared event-like types.
fizarrita/src/set-worker.ts Switch worker construction to createCodecWorker; update task slot typing to WorkerLike.
fizarrita/src/internals/codec-worker-core.ts New shared codec worker core (handleCodecMessage) and pipeline caching/protocol handling.
fizarrita/src/index.ts Re-export new worker creation helpers and codec worker core types/handler.
fizarrita/src/get-worker.ts Switch worker construction to createCodecWorker; update task slot typing to WorkerLike.
fizarrita/src/create-worker.ts Add runtime-aware createDefaultWorker/createCodecWorker and keep bundler-detectable browser worker form.
fizarrita/src/codec-worker.ts Make browser worker entry a thin wrapper over handleCodecMessage with retry-on-post failure.
fizarrita/src/codec-worker-node.ts Add Node worker_threads entry point that wires parentPort to handleCodecMessage.
fizarrita/README.md Document Node behavior and new subpath exports for browser + node codec workers.
fizarrita/package.json Bump version and add exports for node worker and codec-worker core.
.github/workflows/ci.yml Add Node test step before Playwright; rename browser test step for clarity.
Suppressed comments (1)

fizarrita/src/internals/codec-worker-core.ts:317

  • Same issue in the encode path: when metaId isn't registered and meta is absent, meta = msg.meta! produces an unhelpful runtime error message that gets surfaced to callers. Prefer an explicit check and a stable, actionable error string.
      if (msg.metaId !== undefined && pipelineByMetaId.has(msg.metaId)) {
        pipeline = getPipeline(msg.metaId)
        meta = metaByMetaId.get(msg.metaId)!
      } else {
        meta = msg.meta!

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

A decode or encode naming an unregistered `metaId` with no inline `meta`
fell through to the legacy path with `meta` undefined, so the failure
surfaced as `Cannot read properties of undefined (reading 'data_type')`.
That names nothing the caller can act on, and it moves with any refactor of
the pipeline builder.

Both call sites now go through `resolvePipeline`, which reports the actual
cause: a request referencing codec metadata the worker was never sent.

The existing test asserted only that some error came back, which is what let
the unhelpful message through; it now asserts the specific text.

Raised by Copilot on #11.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@thewtex

thewtex commented Aug 7, 2026

Copy link
Copy Markdown
Member Author

Review round addressed — pushed c1d45bd.

Copilot: 1 comment, valid, fixed. Unregistered metaId with no inline meta produced Cannot read properties of undefined (reading 'data_type') instead of naming the missing codec metadata. Both call sites now go through a resolvePipeline helper; details in the resolved thread.

The useful part of that finding was the second half — that the error string was unstable. It had already caught me out: I hit that exact message while writing codec-worker-core.test.js, and loosened the assertion to "some non-empty error" rather than fixing the cause. The test was pinned to nothing. Now it asserts the specific text, with an added case for a request carrying neither metaId nor meta.

CodeRabbit: no review. Both the CLI and the GitHub app returned rate-limit errors with orgAttributed: true — the organization usage spending cap, not a transient throttle. The green CodeRabbit check on this PR is that failure state, not a pass, so nothing here has been CodeRabbit-reviewed. Worth knowing before reading the check as a signal.

The gap that leaves is specific: an earlier CLI run did review the tracked modified files and produced three valid README.md findings (all fixed before the first commit), but every new file was absent from its reviewedFiles — untracked files are not in the diff. So src/node-worker.ts, create-worker.ts, codec-worker-core.ts, codec-worker-node.ts, and the tests were only ever covered by Copilot and by my own read-through. That self-review is where the NodeWorker terminate-race came from: a message posted before the worker thread existed was silently dropped if terminate() landed in between, hanging the caller. Fixed, with a regression test that reproduces it (it hangs without the fix, which is also why the settle-sensitive tests carry explicit timeouts).

Anyone wanting real CodeRabbit coverage of the new files can comment @coderabbitai review once the cap clears — I have not triggered it, since it bills against the cap.

38 Node + 123 browser tests pass.

@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@thewtex: Acknowledged. The green CodeRabbit check does not indicate a completed review in this case.

I noted that the new worker and codec files did not receive CodeRabbit coverage. I also noted the resolvePipeline fix and its deterministic error test. When the usage cap clears, a new @coderabbitai review request can review the complete committed diff.


✏️ Learnings added
Learnt from: thewtex
URL: https://github.com/fideus-labs/worker-pool/pull/11

Timestamp: 2026-08-07T18:19:20.718Z
Learning: For GitHub PR `#11` in `fideus-labs/worker-pool`, a CodeRabbit check can be green after a review failure caused by the organization usage spending cap (`orgAttributed: true`). Treat that state as no completed CodeRabbit review, not as a passing review.

Learnt from: thewtex
URL: https://github.com/fideus-labs/worker-pool/pull/11

Timestamp: 2026-08-07T18:19:20.718Z
Learning: For GitHub PR `#11` in `fideus-labs/worker-pool`, an earlier CodeRabbit CLI review omitted files that were untracked at review time. The files requiring review after they are committed include `src/node-worker.ts`, `create-worker.ts`, `codec-worker-core.ts`, `codec-worker-node.ts`, and their tests.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

You are interacting with an AI system.

@thewtex

thewtex commented Aug 7, 2026

Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🧹 Nitpick comments (5)
fizarrita/src/codec-worker.ts (1)

19-37: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Optional: move the post-and-fallback block into the shared core.

codec-worker-node.ts lines 40-55 contain the same reply-posting and fallback logic. Export a helper from internals/codec-worker-core.ts that takes a post function, then both entries call it. This keeps the two runtimes from drifting.

♻️ Sketch
// internals/codec-worker-core.ts
export async function dispatchCodecMessage(
  msg: CodecWorkerMessage,
  post: (response: Record<string, unknown>, transfer?: ArrayBuffer[]) => void,
): Promise<void> {
  const reply = await handleCodecMessage(msg)
  if (!reply) return
  try {
    post(reply.response, reply.transfer)
  } catch (error) {
    post({
      type: reply.response.type,
      id: reply.response.id,
      error: error instanceof Error ? error.message : String(error),
    })
  }
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@fizarrita/src/codec-worker.ts` around lines 19 - 37, Move the shared
reply-posting and fallback behavior from the codec worker entrypoints into a new
exported dispatchCodecMessage helper in codec-worker-core, accepting the message
and post callback. Update the browser worker’s message listener and
codec-worker-node to call this helper, preserving the existing transfer handling
and fallback error response.
fizarrita/src/internals/codec-worker-core.ts (1)

120-156: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

The pipeline caches grow without bound.

pipelineByMetaId, metaByMetaId, and pipelineByKey are module-level maps and no entry is ever removed. A worker thread is long-lived and is reused across arrays, so each new metaId or inline meta adds a permanent entry. Add an eviction policy, for example a bounded LRU, or add a release message type that deletes a metaId.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@fizarrita/src/internals/codec-worker-core.ts` around lines 120 - 156, Add
bounded cache eviction for the module-level pipelineByMetaId, metaByMetaId, and
pipelineByKey maps, or implement a release message that removes associated
metaId entries and pipelines. Ensure cleanup is triggered as arrays are
discarded so long-lived workers do not retain every created pipeline
indefinitely, while preserving current getPipeline and getOrCreatePipelineLegacy
behavior for active entries.
test/node/worker-pool.test.js (1)

162-180: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Optional: resolve from the listener instead of polling.

The poll loop adds latency and extra timers. Resolve the promise directly in the message listener when four results arrive.

♻️ Proposed refactor
-    const seen = []
-    worker.addEventListener('message', (event) => seen.push(event.data.result))
+    const seen = []
+    const done = new Promise((resolve) => {
+      worker.addEventListener('message', (event) => {
+        seen.push(event.data.result)
+        if (seen.length === 4) resolve()
+      })
+    })
 
     // All four are posted synchronously, before the dynamic import of
     // node:worker_threads has even resolved.
     for (const value of [1, 2, 3, 4]) worker.postMessage({ value })
 
-    await new Promise((resolve) => {
-      const check = () => (seen.length === 4 ? resolve() : setTimeout(check, 10))
-      check()
-    })
+    await done
     assert.deepEqual(seen, [1, 4, 9, 16])
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/node/worker-pool.test.js` around lines 162 - 180, Update the
message-waiting logic in the test around createWorker and the seen listener to
resolve the promise directly when the fourth result is received, rather than
polling with setTimeout. Preserve the existing result collection, ordering
assertion, timeout, and worker termination behavior.
test/browser/runtime-worker.spec.ts (2)

46-53: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Remove the stale error listener when a pooled task completes.

Line 52 adds an error listener, but Line 48 removes only onMessage. WorkerPool reuses the worker for later tasks, so each successful task leaves an error listener attached. Use one detach() function that removes both listeners before resolving or rejecting.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/browser/runtime-worker.spec.ts` around lines 46 - 53, Update the worker
task setup around the onMessage listener to define a shared detach() function
that removes both the message and error listeners. Call detach() before
resolving on successful completion and before rejecting on worker errors,
ensuring pooled Worker instances do not retain listeners between tasks.

43-57: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Keep the pool test type-safe.

Lines 43, 46, and 57 bypass the WorkerLike and WorkerPoolTask<number> contracts with unknown, a browser Worker cast, and as never. The test can pass while returning an incompatible worker. Type the slot as WorkerLike | null, keep the local worker as WorkerLike, and call runTasks<number>(tasks) without the cast.

Proposed fix
+import type { WorkerLike } from '../../src/index.js'
...
-        const tasks = [2, 3, 4].map((value) => async (slot: unknown) => {
-          const worker = slot ?? window.createWorker(window.testWorkerUrl)
+        const tasks = [2, 3, 4].map((value) => async (slot: WorkerLike | null) => {
+          const worker: WorkerLike =
+            slot ?? window.createWorker(window.testWorkerUrl)
...
-            const w = worker as Worker
+            const w = worker
...
-        const { promise } = pool.runTasks(tasks as never)
+        const { promise } = pool.runTasks<number>(tasks)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/browser/runtime-worker.spec.ts` around lines 43 - 57, Make the pool test
type-safe by typing the task slot as WorkerLike | null and keeping the local
worker variable as WorkerLike instead of using unknown or casting to the browser
Worker type. Update the task array and invoke pool.runTasks<number>(tasks)
directly, removing the as never cast while preserving the existing worker
creation and result handling.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@fizarrita/README.md`:
- Around line 252-261: Clarify the subpath worker documentation near the
codec-worker examples: state that these modules are worker entry points only and
that bare imports execute them in the current context, or document
createDefaultWorker() as the supported API for creating workers and obtaining a
workerUrl. Avoid implying that importing either subpath creates a worker.

In `@fizarrita/src/internals/codec-worker-core.ts`:
- Around line 45-78: Update fixEdgeChunkShapeStride to explicitly reject decoded
chunks whose actualElements are less than expectedElements, before returning the
unchanged chunk. Throw a clear error for this undersized-data case, while
preserving the existing shape/stride correction for matching or padded chunks
and the fallback behavior when actualChunkShape is absent.

In `@package.json`:
- Around line 3-4: Update the package version from 1.1.0 to 2.0.0 to reflect the
breaking public WorkerLike type change; do not release this incompatible API
under the 1.x version range.

In `@src/node-worker.ts`:
- Around line 169-176: Update NodeWorker.terminate() and its thread-exit
handling to reject all active WorkerDispatcher requests with a termination error
once the thread stops, instead of suppressing the error when terminated is true.
Preserve idempotency for repeated terminate() calls, and add coverage that waits
for startup, sends a delayed request, terminates the worker, and asserts the
request rejects.

In `@test/app/main.ts`:
- Around line 44-45: Update the intentionally failing task returned by the
worker callback to terminate the created or borrowed worker before rejecting.
Ensure the worker referenced by w is terminated on every failure path, including
when the task does not return a resolved worker, while preserving the existing
rejection behavior.
- Line 19: Update the worker construction around testWorkerUrl and the
corresponding usage near the second Worker creation to use Vite’s worker-entry
syntax, such as a worker-emitting import or literal new Worker(new URL(...),
...) form. Ensure test-worker.ts is compiled and emitted as JavaScript, and that
window.testWorkerUrl references the emitted worker asset rather than a generic
TypeScript asset.

---

Nitpick comments:
In `@fizarrita/src/codec-worker.ts`:
- Around line 19-37: Move the shared reply-posting and fallback behavior from
the codec worker entrypoints into a new exported dispatchCodecMessage helper in
codec-worker-core, accepting the message and post callback. Update the browser
worker’s message listener and codec-worker-node to call this helper, preserving
the existing transfer handling and fallback error response.

In `@fizarrita/src/internals/codec-worker-core.ts`:
- Around line 120-156: Add bounded cache eviction for the module-level
pipelineByMetaId, metaByMetaId, and pipelineByKey maps, or implement a release
message that removes associated metaId entries and pipelines. Ensure cleanup is
triggered as arrays are discarded so long-lived workers do not retain every
created pipeline indefinitely, while preserving current getPipeline and
getOrCreatePipelineLegacy behavior for active entries.

In `@test/browser/runtime-worker.spec.ts`:
- Around line 46-53: Update the worker task setup around the onMessage listener
to define a shared detach() function that removes both the message and error
listeners. Call detach() before resolving on successful completion and before
rejecting on worker errors, ensuring pooled Worker instances do not retain
listeners between tasks.
- Around line 43-57: Make the pool test type-safe by typing the task slot as
WorkerLike | null and keeping the local worker variable as WorkerLike instead of
using unknown or casting to the browser Worker type. Update the task array and
invoke pool.runTasks<number>(tasks) directly, removing the as never cast while
preserving the existing worker creation and result handling.

In `@test/node/worker-pool.test.js`:
- Around line 162-180: Update the message-waiting logic in the test around
createWorker and the seen listener to resolve the promise directly when the
fourth result is received, rather than polling with setTimeout. Preserve the
existing result collection, ordering assertion, timeout, and worker termination
behavior.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 4293e585-361d-4c86-9823-c200643f1d1f

📥 Commits

Reviewing files that changed from the base of the PR and between 3063f6e and c1d45bd.

📒 Files selected for processing (28)
  • .github/workflows/ci.yml
  • README.md
  • fizarrita/README.md
  • fizarrita/package.json
  • fizarrita/src/codec-worker-node.ts
  • fizarrita/src/codec-worker.ts
  • fizarrita/src/create-worker.ts
  • fizarrita/src/get-worker.ts
  • fizarrita/src/index.ts
  • fizarrita/src/internals/codec-worker-core.ts
  • fizarrita/src/set-worker.ts
  • fizarrita/src/worker-rpc.ts
  • package.json
  • pnpm-workspace.yaml
  • src/index.ts
  • src/node-worker.ts
  • src/types.ts
  • src/worker-pool.ts
  • test/app/main.ts
  • test/app/zarrita/index.ts
  • test/browser/runtime-worker.spec.ts
  • test/node/codec-worker-core.test.js
  • test/node/echo-worker.mjs
  • test/node/exiting-worker.mjs
  • test/node/fizarrita.test.js
  • test/node/node-worker-api.test.js
  • test/node/square-worker.mjs
  • test/node/worker-pool.test.js

Comment thread fizarrita/README.md Resolved
Comment thread package.json Resolved
Comment thread src/node-worker.ts Resolved
Comment thread test/app/main.ts Resolved
Comment thread test/app/main.ts Resolved
CodeRabbit's review of the new files (its earlier run only covered tracked
modified files) raised six findings. All were valid.

Reject in-flight requests when a live worker is terminated (major). A message
already delivered to a running thread is never answered once that thread is
killed, and the 'exit' handler stays quiet because the exit was requested — so
the request hung. `terminate()` now raises a termination error, and is
idempotent. The earlier fixes covered posting *after* terminate and terminate
racing thread startup; this is the third case, where the message reached the
thread first.

The regression test for it initially passed without the fix, because
postMessage hands off on a microtask and terminating in the same tick is
caught by the queued-message guard instead. It now waits for the message to
actually reach the thread; verified failing at the timeout without the fix.

Fail explicitly when a decoded chunk holds fewer elements than its edge shape
requires. `fixEdgeChunkShapeStride` returned it unchanged, so the reply carried
a shape that overstated its data and `set_from_chunk_binary` would read past
the end.

Bump both packages to 2.0.0. `WorkerLike` is a documented breaking change for
TypeScript consumers, and SemVer wants a major for that — a `^1` consumer
running `npm update` would otherwise hit a compile error.

Emit the test worker as JavaScript via `?worker&url`. The comment claimed that
suffix was already in use, but it was not, so Vite treated the TypeScript
worker as a generic asset that a production build could not parse.

Terminate the worker in `createFailingTask`. The pool only recycles workers
returned by resolved tasks and does not terminate the one it lent out, so the
failing task leaked it.

Document the codec-worker subpaths as worker entry modules. The README showed
bare imports, which do not create a worker — the browser entry would bind its
handler to the page and the Node entry throws.

Raised by CodeRabbit on #11.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@thewtex

thewtex commented Aug 7, 2026

Copy link
Copy Markdown
Member Author

CodeRabbit's review completed and covered the new files this time. Six findings, all valid, all fixed in 7d34e97 — threads answered individually and resolved.

Finding Severity Outcome
In-flight request hangs when a live worker is terminated 🟠 Major terminate() now rejects; idempotent
Decoded chunk smaller than its edge shape returned unchanged 🟡 Minor Throws instead of inviting an OOB read
Type break shipped as a minor version 🟠 Major Both packages → 2.0.0
Test worker emitted as TypeScript, not JS 🟡 Minor Real ?worker&url import
Failing task leaks its borrowed worker 🟡 Minor Terminates before rejecting
README shows bare imports of worker entry modules 🟡 Minor Documented createDefaultWorker()

Two are worth calling out beyond the table.

The terminate hang was a real miss. I had already closed two variants — posting after terminate, and terminate racing thread startup — and assumed that covered it. It did not. If the message reaches a running thread first, killing that thread destroys the reply, and the exit handler stays silent precisely because the exit was requested. Three adjacent guards, and the gap sat between them.

My regression test for it passed without the fix. postMessage hands off on a microtask, so post-then-terminate in the same tick is intercepted by the queued-message guard and never reaches the new path. The test now waits for the message to actually land on the thread; it fails at the 10s timeout without the fix and passes in 116ms with it. Both the earlier terminate-race test and this one were verified by removing the fix and confirming failure — a test asserting "this does not hang" is worth very little unless you have watched it hang.

On the version bump, I had originally reasoned that type-only widening is conventionally a minor. That convention is real but does not survive the concrete case: a consumer on ^1.0.0 running npm update gets a compile error with no opt-in, and for a TypeScript-first library the types are the API. There is no shim that avoids it — the break is contravariance in WorkerPoolTask's parameter, and preserving that means keeping Worker, which is the thing that made the pool unusable in Node. Reverting to 1.1.0/1.5.0 is a two-line change if you'd rather ship it as a minor; that call is yours.

One deliberate non-fix: the pool permanently loses a slot when a task rejects (addTask recycles only in its .then branch). That is pre-existing and unrelated to Node support, so I fixed only the test helper that tripped over it and left the pool alone — worth a follow-up issue.

39 Node + 123 browser tests pass; production bundle still builds clean.

@thewtex
thewtex merged commit aa4d492 into main Aug 7, 2026
1 check passed
@thewtex
thewtex deleted the worker-path branch August 7, 2026 18:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants