Skip to content

fix(cli): settle threaded WASI disposal after async work - #3526

Merged
Brooooooklyn merged 4 commits into
mainfrom
fix/cli-wasi-terminate-workers
Sep 16, 2026
Merged

Brooooooklyn merged 4 commits into
mainfrom
fix/cli-wasi-terminate-workers

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Sep 15, 2026 •

Copy link
Copy Markdown
Member

fix(cli): settle WASI pool worker termination on dispose

What

Two defects in the generated threaded WASI loaders, both on the dispose()
path, both reproduced on upstream examples/napi/example.wasi.cjs.

1. Disposal crashes the process

async work done
worker (tid = 43) sent an error! Worker stopped with exit code 1
node_modules/@emnapi/wasi-threads/dist/wasi-threads.js:347  throw error;
Error: Worker stopped with exit code 1
    at Worker.<anonymous> (wasi-threads.js:408:37)
    at Worker.emit (node:events:526:24)
    at [kOnExit] (node:internal/worker:400:10)

The mechanism, end to end:

  1. __terminateWasiWorkers called a bare worker.terminate().
  2. ThreadManager records a termination as expected only in its own
    terminateWorker() (which is what fills the private expectedTerminations).
  3. So its worker.on('exit') listener sees Node's normal terminate() exit
    code 1, treats it as a worker failure, calls fail() and — on Node —
    throws inside the exit emit.
  4. That throw aborts the emit, so the once('exit', resolve) backing
    terminate()'s own promise never runs.
  5. Promise.all(pending) never settles; dispose() hangs and the process dies
    with an uncaught exception.

Minimal trigger: one napi_async_work call (any async export) followed by
one dispose(). Sync-only calls never spawn a pool worker, so they never reach
this.

Why CI missed it: it is timing-gated. With nothing keeping the loop alive
the process simply exits 0 with the dispose promise pending, and no example ever
disposes the threaded flavor after async work (examples/custom-async-runtime
disposes only the threadless one).

2. await dispose() as a script's last statement never resolves

The Node loader unreferences its pool workers and stubs kHandle.ref /
kPublicPort.ref so an idle binding cannot hold the process open.
Worker#terminate() references the worker through exactly those two
functions
to observe the 'exit' that resolves its promise — so the pending
terminations could not keep the loop alive. The process exited 0 and everything
after the await was skipped. A dispose promise that silently never settles is
a defect in its own right.

The fixes

# Change
1 Mark the termination through PThread.terminateWorker(worker) before calling worker.terminate(), and clear the message reporter it installs (worker.onmessage = undefined), which otherwise logs every message Node flushes from the port on exit.
2 Hold the event loop open with a timer the loader owns while the terminations are pending, released the moment they settle. The workers themselves cannot do it: they are unreferenced so an idle binding never keeps a process alive, and emnapi unreferences them again whenever one reports async-thread-ready.
3 Capture the thread manager from an emnapi plugin factory, which runs while the module is being created — before the wasm is loaded and before any registration. The initialization rollback runs on the one path where __napiModule was never assigned, and terminating unmarked there turns a caught init error into a fatal Worker stopped with exit code 1.

Not PThread.terminateAllThreads(): its shutdownAllWorkers(recreatePool = true) spawns a fresh pool in the middle of disposal. Not
removeAllListeners('exit'): Node-only, and it leaves registeredWorkers /
loadRejects stale. terminateWorker(worker) is public API in
@emnapi/[email protected]; expectedTerminations is private. No change to
@emnapi/wasi-threads and no Rust change.

Both live in the shared loader prelude, so the node CJS and browser threaded
flavors are covered; the deferred/workerd loader is threadless and has no
workers.

Before / after

Upstream examples/napi/example.wasi.cjs, zero third-party code:

probe before after
async work → dispose(), loop kept alive exit 1, uncaught Worker stopped with exit code 1 exit 0, DISPOSE_SETTLED
async work → await dispose() as last statement exit 13, Detected unsettled top-level await exit 7, marker printed
24-concurrent async work × 3 cycles → dispose (×3 runs) 3/3 fail 3/3 clean, no sent an error!
async work, no dispose exits promptly exits promptly (0.1s)
init fails after the pool spawned workers, caller catches exit 1, fatal Worker stopped with exit code 1 exit 0, caller carries on

Verified on Node 20.20.2, 22.23.2 and 24.11.1, plus the 24.21.0 in PATH.

Tests

cli/src/api/__tests__/templates.spec.ts

  • pool workers are terminated through the thread manager: node cjs | browser esm
    — asserts the mark precedes worker.terminate(), that terminateAllThreads
    is not used, that the reporter is cleared, and that the ref restore happens
    before the terminate promise is created.
  • a pending termination holds the event loop open: node cjs | browser esm
    — asserts the terminate promises are awaited under the keep-alive, that it is
    released on both settlement paths, and that nothing puts the stubbed ref
    functions back.
  • the node loader keeps its pool workers unreferenced for life.
  • threadless loaders never name Worker: … — the threadless loaders assert on
    /\bWorker\b, and the shared prelude is emitted into them, comments
    included. That check otherwise needs a wasm build to fail.

All of them fail against the unpatched template. Template snapshots regenerated
with --update-snapshots (purely additive: no deleted lines).

examples/napi/__tests__/wasi-worker-termination.spec.ts (+ child script
wasi-worker-termination.js) — gated the way the sibling WASI specs are
(WASI_TEST set, NAPI_RS_WASI_FLAVOR !== 'wasm32-wasip1'), so it runs in the
threaded lanes and skips in the threadless one. Each case spawns a child node
against the built example.wasi.cjs:

  1. async work then dispose() settles, with the loop held open — and no
    sent an error! on stderr;
  2. await dispose() as the last statement resolves and its marker is printed
    (asserted through a distinct exit code);
  3. an undisposed binding still does not keep an idle process alive;
  4. an initialization that fails after the pool spawned workers tears them down
    without going fatal — the caller catches the error and the process exits 0
    (wasi-init-rollback.js reproduces that state by taking __napiModule away
    from a copy of the generated loader, which is exactly what a throw during
    instantiation leaves behind).

Cases 1, 2 and 4 fail against the unpatched loader, on Node 20, 22 and 24. No workflow change was needed:
both threaded lanes (test-node-wasi, wasi-sdk) run the whole example suite.

Verification

check result
yarn test:cli 341 passed
examples/napi threaded (WASI_TEST=1) 298 passed, 11 skipped, 0 failed
node examples/custom-async-runtime/test.mjs wasi (threadless) exit 0
each child script x25-40, Node 20/22/24 no flakes
threadless lane specs (NAPI_RS_TEST_THREADLESS_WASI_BUFFER=1) 20 passed
threadless lifecycle (NAPI_RS_WASI_FLAVOR=wasm32-wasip1) passed; the new spec skips
oxlint / oxfmt --check clean
tsc -p examples/napi/tsconfig.json clean

examples/napi/* loaders regenerated with node examples/napi/build.mjs --regenerate-all against the real toolchain; the only artifact hunks are the
ones the template change produces, and no unrelated drift was kept.

cli/docs/wasi.md gains a short paragraph on how pool workers are terminated.

See https://github.com/emnapi/emnapi ThreadManager.terminateWorker /
loadWasmModuleToWorker for the expected-termination bookkeeping this relies
on.

Known limitation (pre-existing, out of scope)

dispose() while a napi_async_work task (an AsyncTask) is still in flight
leaks the emnapi waiting-request counter: the pool workers that would complete
the task are terminated, so Context.refCounter (@emnapi/runtime
NodejsWaitingRequestCounter) stays at 1 and its ref'd MessagePort keeps
the event loop alive.

loader dispose with a task in flight
main exit 1, uncaught Worker stopped with exit code 0, counter = 1
this PR dispose() settles, then the process cannot exit, counter = 1

Same on Node 20 / 22 / 24, with or without an initialization failure. The
state is identical on main; this PR only changes the symptom from a crash
to a hang, because the unexpected-exit handler no longer throws.

Fixing it is a product call for its own change: either dispose() waits for
in-flight tasks (disposal latency, can block on a long task) or cancels them
(napi_cancel_async_work only cancels work that has not started). Verified
lever for a later fix: after the workers are gone, ctx.refCounter.refHandle.unref()
lets the process exit.

🤖 Generated with Claude Code

https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda


Note

Medium Risk
Touches generated loader lifecycle for threaded WASI (worker termination and event-loop behavior during dispose); fixes real shutdown bugs but affects process-exit timing and init-failure rollback paths.

Overview
Fixes threaded WASI loader disposal so dispose() reliably settles after async-work pool workers exist, instead of crashing or leaving the promise pending.

Worker shutdown now goes through emnapi’s PThread.terminateWorker before worker.terminate(), so @emnapi/wasi-threads treats the exit as expected (bare terminate() was reported as a worker failure and could throw during Node’s exit emit). The thread manager is captured early via a small emnapi plugin so rollback still works when instantiation fails before __napiModule exists.

While terminate promises are pending, disposal uses __keepEventLoopAliveUntil (a short-lived interval) because pool workers stay unreferenced and cannot keep the event loop alive on their own—so await dispose() as the script’s last line can complete without holding idle processes open when never disposed.

Changes land in load-wasi-template.ts (regenerated example loaders + snapshots), cli/docs/wasi.md, template unit tests, and threaded examples/napi integration tests for dispose, last-statement await, and init rollback.

Reviewed by Cursor Bugbot for commit 1063014. Bugbot is set up for automated code reviews on this repo. Configure here.

Summary by CodeRabbit

  • Bug Fixes
    • Improved WASI worker cleanup and disposal reliability, including during failed initialization.
    • Ensured asynchronous worker termination completes before disposal settles.
    • Prevented unexpected worker exits from being reported as failures during normal cleanup.
    • Preserved process exit behavior for idle bindings that have not been disposed.
  • Tests
    • Added coverage for worker termination, initialization rollback, disposal completion, and process liveness.

Brooooooklyn and others added 2 commits September 16, 2026 00:31
…ispose

`@emnapi/wasi-threads` records a worker exit as expected only when its own
`ThreadManager.terminateWorker` performed the termination. The generated
threaded loaders called `worker.terminate()` directly, so the manager's
`exit` listener saw Node's normal terminate exit code 1, reported
`worker (tid = N) sent an error! Worker stopped with exit code 1` and rethrew
inside the emit. That throw aborts the emit, so the `once('exit')` backing the
terminate promise never runs: `dispose()` waits on a promise that can no longer
settle, and the process dies with an uncaught exception whenever something else
holds the event loop open.

One `napi_async_work` call followed by one `dispose()` is the whole trigger.
Sync-only calls never spawn a pool worker, and no example disposes a threaded
binding after async work, which is why no lane caught it.

Mark the termination on the manager first, then terminate. Not
`terminateAllThreads()`: its `shutdownAllWorkers(recreatePool = true)` spawns a
fresh pool in the middle of disposal.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
…tles

The Node.js threaded loader unreferences its pool workers and stubs out the
`ref` functions on their `kHandle` / `kPublicPort` handles, so an idle binding
cannot hold the process open. `Worker#terminate()` references the worker
through exactly those two functions, to observe the 'exit' that resolves its
promise — so with them stubbed the pending terminations could not keep the loop
alive. An `await dispose()` with nothing else pending never resolved: the
process exited 0 with the promise still pending and everything after the
`await` skipped.

Keep the original `ref` functions when the stubs are installed and put them
back before terminating. Nothing has to unreference them again afterwards: the
worker is gone once the termination settles, and a termination that throws
synchronously unreferences the worker again so the process can still exit.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
@coderabbitai

coderabbitai Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Advanced

Run ID: 0f85fcb5-0cc8-4051-8f36-de61d3bee0e8

📥 Commits

Reviewing files that changed from the base of the PR and between 43100ba and 1063014.

⛔ Files ignored due to path filters (1)
  • cli/src/api/__tests__/__snapshots__/templates.spec.ts.snap is excluded by !**/*.snap
📒 Files selected for processing (11)
  • cli/docs/wasi.md
  • cli/src/api/__tests__/__snapshots__/templates.spec.ts.md
  • cli/src/api/__tests__/templates.spec.ts
  • cli/src/api/templates/load-wasi-template.ts
  • examples/napi/__tests__/wasi-init-rollback.js
  • examples/napi/__tests__/wasi-worker-termination.js
  • examples/napi/__tests__/wasi-worker-termination.spec.ts
  • examples/napi/example.wasi-browser.js
  • examples/napi/example.wasi.cjs
  • examples/napi/example.wasip1-browser.js
  • examples/napi/example.wasip1.cjs

Included review availability: Your plan provides up to 8 included reviews per hour; 7 remain after this review.


📝 Walkthrough

Walkthrough

WASI loaders now capture the emnapi thread manager before instantiation, use it during worker termination, and keep asynchronous disposal alive until termination settles. Generated bindings, snapshots, documentation, and regression tests cover normal disposal, rollback, idle workers, and threadless loaders.

Changes

WASI worker lifecycle

Layer / File(s) Summary
Loader termination and manager wiring
cli/src/api/templates/load-wasi-template.ts, cli/src/api/__tests__/__snapshots__/templates.spec.ts.md, cli/docs/wasi.md
The template captures context.PThread, resolves the manager during cleanup, calls terminateWorker before the fallback termination, clears worker.onmessage, and keeps pending cleanup alive with a temporary interval. Snapshots cover the generated variants.
Generated binding integration
examples/napi/example.wasi*, examples/napi/example.wasip1*
Generated browser and CommonJS bindings register the capture plugin before module initialization and apply manager-mediated termination and event-loop keepalive handling. Worker reference stubs remain installed through disposal.
Termination and rollback validation
cli/src/api/__tests__/templates.spec.ts, examples/napi/__tests__/*
Tests cover termination ordering, pending disposal, unreferenced workers, threadless loaders, undisposed bindings, and rollback when __napiModule is cleared.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant Binding
  participant PThread
  participant Worker
  participant EventLoop
  Binding->>PThread: capture context.PThread
  Binding->>PThread: terminateWorker(worker)
  PThread->>Worker: process managed termination
  Binding->>Worker: worker.terminate() fallback
  Binding->>EventLoop: keep pending termination alive
  EventLoop-->>Binding: pending termination settles
Loading

Merge Risk: ⚪ Minimal · up to 10630

Worker disposal retains the process until cleanup completes, with no actionable merge-blocking risk identified.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 32.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 25 functions across 9 files. (2 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: fixing settlement of threaded WASI disposal after asynchronous work.
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.
Full details: Docstring Coverage

Explanation

Docstring coverage is 32.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 25 functions across 9 files. (2 skipped: 2 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/cli-wasi-terminate-workers

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

Brooooooklyn and others added 2 commits September 16, 2026 00:47
`examples/custom-async-runtime/test.mjs` asserts that a threadless loader
source never matches `/\bWorker\b/`. The two comments the previous commits
added sit in the shared loader prelude, so they are emitted for every flavor
and leaked the standalone word into the threadless loaders, failing the
"Test custom async runtime on wasm32-wasip1" job.

Reword both so the prelude names no class:

- "Node's own `Worker#terminate`" -> "a worker's own `terminate()`"
- "sent an error! Worker stopped with exit code 1" -> "sent an error! ...
  stopped with exit code 1"

The structure is unchanged — the threadless loaders already carried the inert
`__terminateWasiWorkers` helper before any of this — and the threaded loaders
keep their real `Worker` references.

Also assert it at the template layer, which needs no wasm build to fail.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
…n rollback

Two defects on the initialization-rollback path, both found by fault injection
on the generated threaded loader.

`__napiModule` is assigned by the destructuring that consumes
`instantiateNapiModuleSync`, so it is assigned only when instantiation RETURNS.
The rollback runs on exactly the path where it did not: a module-init hook that
spawns pool threads and then fails leaves those workers registered and loaded
with the emnapi thread manager while `__napiModule` is still undefined. Reading
the manager off it meant the rollback fell back to a bare `worker.terminate()`,
so the manager's unexpected-exit handler turned a CAUGHT initialization error
into a fatal `Worker stopped with exit code 1`.

`@emnapi/core` exposes no way to reach the manager before the load, but a
plugin factory is constructed while the emnapi module is being created — before
the wasm is loaded and before any registration runs — and its context carries
the very same `ThreadManager` instance. Capture it there.

The second defect is in the event-loop hold added for `await dispose()` as a
last statement. Putting the stubbed `ref` functions back cannot work: emnapi
unreferences a worker again the moment it reports `async-thread-ready`
(`_emnapi_tell_js_uvthreadpool`), which for a worker that was still starting
lands after the termination began. Around 13% of runs lost the reference that
way and exited with the dispose promise unsettled. Hold the loop with a timer
the loader owns and releases when the terminations settle, and leave the
workers unreferenced for life.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
@Brooooooklyn
Brooooooklyn marked this pull request as ready for review September 16, 2026 02:58
@cursor

cursor Bot commented Sep 16, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_daf1342c-5d8d-40cc-8b68-91d4ed0cf043)

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-16T03:02:28.296746Z 1063014 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Brooooooklyn
Brooooooklyn merged commit f9be941 into main Sep 16, 2026
150 of 152 checks passed
@Brooooooklyn
Brooooooklyn deleted the fix/cli-wasi-terminate-workers branch September 16, 2026 03:04
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.

1 participant