Repository navigation
fix(cli): settle threaded WASI disposal after async work - #3526
Conversation
…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
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Advanced Run ID: ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (11)
Included review availability: Your plan provides up to 8 included reviews per hour; 7 remain after this review. 📝 WalkthroughWalkthroughWASI 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. ChangesWASI worker lifecycle
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
Merge Risk: ⚪ Minimal · up to Worker disposal retains the process until cleanup completes, with no actionable merge-blocking risk identified. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Docstring CoverageExplanation 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.)
✨ Finishing Touches 💡 2📝 Generate docstrings 💡
🛠️ Fix failing CI checks 💡
🧪 Generate unit tests (beta)
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. Comment |
`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
Bugbot couldn't run - usage limit reachedBugbot 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) |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
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
The mechanism, end to end:
__terminateWasiWorkerscalled a bareworker.terminate().ThreadManagerrecords a termination as expected only in its ownterminateWorker()(which is what fills the privateexpectedTerminations).worker.on('exit')listener sees Node's normalterminate()exitcode
1, treats it as a worker failure, callsfail()and — on Node —throws inside the
exitemit.once('exit', resolve)backingterminate()'s own promise never runs.Promise.all(pending)never settles;dispose()hangs and the process dieswith an uncaught exception.
Minimal trigger: one
napi_async_workcall (any async export) followed byone
dispose(). Sync-only calls never spawn a pool worker, so they never reachthis.
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-runtimedisposes only the threadless one).
2.
await dispose()as a script's last statement never resolvesThe Node loader unreferences its pool workers and stubs
kHandle.ref/kPublicPort.refso an idle binding cannot hold the process open.Worker#terminate()references the worker through exactly those twofunctions to observe the
'exit'that resolves its promise — so the pendingterminations could not keep the loop alive. The process exited 0 and everything
after the
awaitwas skipped. A dispose promise that silently never settles isa defect in its own right.
The fixes
PThread.terminateWorker(worker)before callingworker.terminate(), and clear the message reporter it installs (worker.onmessage = undefined), which otherwise logs every message Node flushes from the port on exit.async-thread-ready.__napiModulewas never assigned, and terminating unmarked there turns a caught init error into a fatalWorker stopped with exit code 1.Not
PThread.terminateAllThreads(): itsshutdownAllWorkers(recreatePool = true)spawns a fresh pool in the middle of disposal. NotremoveAllListeners('exit'): Node-only, and it leavesregisteredWorkers/loadRejectsstale.terminateWorker(worker)is public API in@emnapi/[email protected];expectedTerminationsis private. No change to@emnapi/wasi-threadsand 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:dispose(), loop kept aliveWorker stopped with exit code 1DISPOSE_SETTLEDawait dispose()as last statementDetected unsettled top-level awaitsent an error!Worker stopped with exit code 1Verified 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.tspool workers are terminated through the thread manager: node cjs | browser esm— asserts the mark precedes
worker.terminate(), thatterminateAllThreadsis not used, that the reporter is cleared, and that the
refrestore happensbefore 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
reffunctions 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, commentsincluded. 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 scriptwasi-worker-termination.js) — gated the way the sibling WASI specs are(
WASI_TESTset,NAPI_RS_WASI_FLAVOR !== 'wasm32-wasip1'), so it runs in thethreaded lanes and skips in the threadless one. Each case spawns a child
nodeagainst the built
example.wasi.cjs:dispose()settles, with the loop held open — and nosent an error!on stderr;await dispose()as the last statement resolves and its marker is printed(asserted through a distinct exit code);
without going fatal — the caller catches the error and the process exits 0
(
wasi-init-rollback.jsreproduces that state by taking__napiModuleawayfrom 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
yarn test:cliexamples/napithreaded (WASI_TEST=1)node examples/custom-async-runtime/test.mjs wasi(threadless)NAPI_RS_TEST_THREADLESS_WASI_BUFFER=1)NAPI_RS_WASI_FLAVOR=wasm32-wasip1)oxlint/oxfmt --checktsc -p examples/napi/tsconfig.jsonexamples/napi/*loaders regenerated withnode examples/napi/build.mjs --regenerate-allagainst the real toolchain; the only artifact hunks are theones the template change produces, and no unrelated drift was kept.
cli/docs/wasi.mdgains a short paragraph on how pool workers are terminated.See https://github.com/emnapi/emnapi
ThreadManager.terminateWorker/loadWasmModuleToWorkerfor the expected-termination bookkeeping this relieson.
Known limitation (pre-existing, out of scope)
dispose()while anapi_async_worktask (anAsyncTask) is still in flightleaks the emnapi waiting-request counter: the pool workers that would complete
the task are terminated, so
Context.refCounter(@emnapi/runtimeNodejsWaitingRequestCounter) stays at 1 and its ref'dMessagePortkeepsthe event loop alive.
mainWorker stopped with exit code 0, counter = 1dispose()settles, then the process cannot exit, counter = 1Same 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 crashto a hang, because the unexpected-exit handler no longer throws.
Fixing it is a product call for its own change: either
dispose()waits forin-flight tasks (disposal latency, can block on a long task) or cancels them
(
napi_cancel_async_workonly cancels work that has not started). Verifiedlever 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.terminateWorkerbeforeworker.terminate(), so@emnapi/wasi-threadstreats the exit as expected (bareterminate()was reported as a worker failure and could throw during Node’sexitemit). The thread manager is captured early via a small emnapi plugin so rollback still works when instantiation fails before__napiModuleexists.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—soawait 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 threadedexamples/napiintegration 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