Skip to content

fix: reject the in-flight task when a worker thread exits - #148

Open
MFA-G wants to merge 1 commit into
tinylibs:mainfrom
MFA-G:fix/worker-thread-unexpected-exit
Open

MFA-G wants to merge 1 commit into
tinylibs:mainfrom
MFA-G:fix/worker-thread-unexpected-exit

Conversation

@MFA-G

@MFA-G MFA-G commented Nov 14, 2026

Copy link
Copy Markdown

The bug

With the default worker_threads runtime, a worker that exits during a task (for example by calling process.exit(1)) leaves pool.run() pending forever, and the dead worker stays in the pool instead of being replaced. The child_process runtime already handles this case.

const pool = new Tinypool({ filename, maxThreads: 1, minThreads: 1 })

await pool.run('process.exit(1)') // never settles
await pool.run('42')              // never settles either

Cause

ThreadWorker only forwarded error, and Node emits exit (without error) when a worker calls process.exit(). ProcessWorker already turns an unexpected exit into an error via onUnexpectedExit, so this brings the thread runtime to parity.

Fix

  • ThreadWorker now listens for exit and reports Worker exited unexpectedly when the exit was neither requested nor preceded by an error event. A worker that throws emits error before exit, so the exit listener is skipped in that case to avoid reporting the same failure twice.
  • terminate() marks intentional shutdowns and removes the exit listener, like ProcessWorker.terminate().

The pool's existing error path then rejects the in-flight task, removes the dead worker, spawns a replacement and drains the queue.

Tests

Added test/worker-exit.test.ts, asserting that both worker_threads and child_process reject the in-flight task and that a subsequent task succeeds on the replacement worker. It also passes with isolateWorkers: true.

pnpm vitest run   # 17 files, 100 tests passed
pnpm lint         # clean
pnpm typecheck    # clean

Fixes #147.

`ThreadWorker` only listened for `error` events, but `process.exit()` and
other clean shutdowns in a worker emit only `exit`. The task stayed pending
forever and the dead worker stayed in the pool, so the queue could not make
progress. The `child_process` runtime already reports an unexpected exit as
an error through `ProcessWorker.onUnexpectedExit`; do the same for threads.

A worker that throws emits `error` before `exit`, so the `exit` listener is
skipped once an error was reported to avoid handling the same failure twice.
`terminate()` flags intentional shutdowns so they are ignored.
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.

worker_threads runtime leaves tasks pending forever when a worker exits

1 participant