Repository navigation
fix(napi): register the async runtime env cleanup hook per registration - #3400
Conversation
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_4999cdff-9d2b-4d97-8b45-f7be148821b6) |
📝 WalkthroughWalkthroughTokio environment cleanup registration now occurs for every ChangesTokio environment cleanup
Estimated code review effort: 2 (Simple) | ~10 minutes 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 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 |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 394c7f01af
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
`napi_register_module_v1` runs once per env — the main thread, every `worker_threads` worker (its own V8 isolate + env), and every Electron renderer reload (env destroyed + recreated). Each call increments `MODULE_COUNT` and starts the shared async runtime; teardown is refcounted by the `thread_cleanup` env-cleanup hook, which decrements `MODULE_COUNT` and shuts the runtime down only when it reaches zero (the last live env). The hook was installed behind a process-wide one-shot gate (`ENV_CLEANUP_HOOK_ADDED: RwLock<bool>`) that was set once and never reset, so it registered for the first registration only. Every additional or recreated env bumped `MODULE_COUNT` with no matching cleanup hook, so the count could never return to zero and `shutdown_async_runtime` was never called — the runtime's backend threads/tasks outlived the addon image (worker_threads, Electron reload). Register the hook on every registration instead. The same addon can also be (re)loaded into the *same* env (`unload.spec.js` clears the require cache and re-`require`s it), and Node's `napi_add_env_cleanup_hook` asserts every `(fn, arg)` pair is unique within an env — so each registration gets a distinct, never-dereferenced cookie instead of a shared `null` arg. Otherwise the second same-env load aborts in `AddEnvironmentCleanupHook` on `result.second`. One hook per registration keeps `MODULE_COUNT` balanced (one decrement per increment), so the last env's teardown still shuts the runtime down exactly once. Split out of the #3352 review (codex, module_register.rs:577); the bug is pre-existing on the `tokio_rt` path on `main`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
394c7f0 to
4c39221
Compare
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_a866e71a-c2be-4b09-9570-c7d9726a9a7c) |
Reconcile the stacked non-threaded-WASI work with the squash-merged AsyncRuntime SPI base (#3352) and per-registration cleanup-hook fix (#3400): - yarn.lock: regenerated so it reconciles main's dependency bumps (notably oxc-parser 0.139.0 -> 0.140.0) with the example deps; `yarn install --immutable` is now clean. - examples/napi WASI binding surfaces and the type-def snapshot: regenerated so every flavor carries main's createErroringReadableStream export (the carried #3353 surfaces predated it). Produced via `yarn workspace @examples/napi regenerate` and `ava --update-snapshots`; not hand-edited. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
Reconcile the stacked non-threaded-WASI work with the squash-merged AsyncRuntime SPI base (#3352) and per-registration cleanup-hook fix (#3400): - yarn.lock: regenerated so it reconciles main's dependency bumps (notably oxc-parser 0.139.0 -> 0.140.0) with the example deps; `yarn install --immutable` is now clean. - examples/napi WASI binding surfaces and the type-def snapshot: regenerated so every flavor carries main's createErroringReadableStream export (the carried #3353 surfaces predated it). Produced via `yarn workspace @examples/napi regenerate` and `ava --update-snapshots`; not hand-edited. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
Reconcile the stacked non-threaded-WASI work with the squash-merged AsyncRuntime SPI base (#3352) and per-registration cleanup-hook fix (#3400): - yarn.lock: regenerated so it reconciles main's dependency bumps (notably oxc-parser 0.139.0 -> 0.140.0) with the example deps; `yarn install --immutable` is now clean. - examples/napi WASI binding surfaces and the type-def snapshot: regenerated so every flavor carries main's createErroringReadableStream export (the carried #3353 surfaces predated it). Produced via `yarn workspace @examples/napi regenerate` and `ava --update-snapshots`; not hand-edited. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
Reconcile the stacked non-threaded-WASI work with the squash-merged AsyncRuntime SPI base (#3352) and per-registration cleanup-hook fix (#3400): - yarn.lock: regenerated so it reconciles main's dependency bumps (notably oxc-parser 0.139.0 -> 0.140.0) with the example deps; `yarn install --immutable` is now clean. - examples/napi WASI binding surfaces and the type-def snapshot: regenerated so every flavor carries main's createErroringReadableStream export (the carried #3353 surfaces predated it). Produced via `yarn workspace @examples/napi regenerate` and `ava --update-snapshots`; not hand-edited. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
Reconcile the stacked non-threaded-WASI work with the squash-merged AsyncRuntime SPI base (#3352) and per-registration cleanup-hook fix (#3400): - yarn.lock: regenerated so it reconciles main's dependency bumps (notably oxc-parser 0.139.0 -> 0.140.0) with the example deps; `yarn install --immutable` is now clean. - examples/napi WASI binding surfaces and the type-def snapshot: regenerated so every flavor carries main's createErroringReadableStream export (the carried #3353 surfaces predated it). Produced via `yarn workspace @examples/napi regenerate` and `ava --update-snapshots`; not hand-edited. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
Reconcile the stacked non-threaded-WASI work with the squash-merged AsyncRuntime SPI base (#3352) and per-registration cleanup-hook fix (#3400): - yarn.lock: regenerated so it reconciles main's dependency bumps (notably oxc-parser 0.139.0 -> 0.140.0) with the example deps; `yarn install --immutable` is now clean. - examples/napi WASI binding surfaces and the type-def snapshot: regenerated so every flavor carries main's createErroringReadableStream export (the carried #3353 surfaces predated it). Produced via `yarn workspace @examples/napi regenerate` and `ava --update-snapshots`; not hand-edited. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
* test(examples): carry the custom-async-runtime example (moved from the SPI PR during its minimal rewrite) The example previously lived on the full custom-async-runtime SPI branch. Its threadless-WASI build and test lanes are this PR's feature proof, so the example moves here, adapted to the minimal async-runtime SPI: - the removed napi helpers (spawn_on_custom_runtime, spawn_blocking_on_custom_runtime, try_block_on_custom_runtime, try_start/try_shutdown_async_runtime, JoinError) are replaced by example-local equivalents driven through the backend's own scheduler - probes of the old lifecycle-hardening machinery (transition barriers, reentrancy gates, sticky shutdown, Tokio retirement, terminal finalizers, cancellation-order fixtures) are dropped together with pure-runtime-lifecycle.mjs, runtime-lifecycle-helper.mjs and src/cancellation_order.rs - assertions now track the minimal SPI semantics: deferred registration errors surface on the first runtime-backed operation, a failed start rolls back through shutdown without failing the module load, every environment registration restarts the backend, and within_runtime_if_available stays Tokio-backed in combined builds Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * feat(cli): support non-threaded WASI targets * feat(cli): migrate WASI loaders to emnapi v2 * fix(cli): always spawn cargo metadata with the host cargo binary `createCargoMetadataInvocation` honored $CARGO, but $CARGO only overrides the cargo/cross binary spawned for the actual build. The android-build tests from main poison $CARGO with a nonexistent path to prove no real build is spawned, so `cargo metadata` at the start of `buildProject` failed with 'cargo metadata failed to run' on every native CI lane. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * fix(build): export emnapi v2 env management functions for WASI targets @emnapi/core v2 acquires `exports.emnapi_create_env` / `exports.emnapi_delete_env` during `napiModule.init()` and calls the former to allocate the native environment. Without the explicit `--export` link args the archive-defined functions are GC'd by wasm-ld and every WASI addon fails to load with 'TypeError: _emnapi_create_env is not a function' (the 'Test node wasi target' job failure). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * build: work around [email protected] packaging gaps (TEMPORARY) The published [email protected] cannot support this PR yet, see vendor/emnapi/README.md for the exact upstream requirements: - `lib/wasm32-wasip1/libemnapi.a` is missing entirely, so every non-threaded WASI build aborts in `setWasiEnv`. - `lib/wasm32-wasip1-threads/libemnapi-napi-rs-mt.a` references the env cleanup hooks through the `env` import module instead of `napi`, producing duplicate imports rejected by examples/napi/wasi-cleanup-hook-link/check-imports.mjs. - The @emnapi/core TSFN plugin and napi_get_{typedarray,dataview,arraybuffer}_info capture heap views across operations that can grow (and thereby detach) a non-shared wasm memory. Vendor archives rebuilt from the C sources shipped inside the npm package (vendor/emnapi/build.mjs documents the flags), install them via postinstall + explicit CI steps (CI installs with --mode=skip-build), and carry the JS fixes as a yarn patch. Everything is version-pinned and hard-fails on an emnapi upgrade so the workarounds cannot outlive the alpha. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * fix(cli,wasm-runtime): restore threadless WASI runtime behavior on emnapi v2 Two behaviors were lost in the emnapi v2 loader migration: - Single-threaded builds link an emnapi archive whose C async-work and threadsafe-function implementations are unconditional napi_generic_failure stubs, so module registration died creating the Custom GC TSFN. Re-export @emnapi/core's asyncWork/tsfn plugins from @napi-rs/wasm-runtime and wire them into every non-threaded loader (node cjs, browser, workerd-deferred) and the custom-async-runtime fixture loader. - emnapi v2's Context constructor unconditionally registers a process.once('beforeExit') listener on Node that suppressDestroy() does not remove. Restore the capture-and-remove machinery in the eager node loader and the deferred loader's managed context so createInstance never leaves process-level listeners (workerd loader contract, checked by the create-npm-dirs workerd test and published-emnapi-v2-lifecycle spec). Regenerate the committed examples/napi loader artifacts and update the cli test mocks of @napi-rs/wasm-runtime to export the plugin symbols. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * test(examples): align WASI tests and snapshots with the emnapi v2 loaders - Rewrite the threaded-browser-artifact rollback test against the consolidated emnapiContextLifecycle mechanism (the old __wasiInitializationWorkers machinery is gone; the new loader keeps the same guarantees: workers tracked and terminated on rollback and disposal, context destroyed and awaited before worker termination). - Regenerate the stale values.spec.ts.snap: the emnapi v2 migration removed the @emnapi/*-stock devDependencies and updated the .md mirror but not the binary snapshot ava actually compares against. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * build: verify vendored emnapi archives against a committed manifest build.mjs now records manifest.json (pinned emnapi version, wasi-sdk version, sha512 of every npm-shipped file the archives are built from, sha512 + ar member list of each archive). install.mjs re-verifies all of it before copying, on every machine and every CI lane that consumes the archives, and hard-fails on drift or tampering. CI does not rebuild the archives byte-for-byte (wasi-sdk is not provisioned on the consuming lanes, and clang output is only stable against the exact recorded SDK; a local rebuild with wasi-sdk 32.0 reproduces the committed blobs bit-for-bit). The semantic import-module property is functionally verified in CI by the cleanup-hook import check and the native-lane wasip1 build test. Residual risk (a commit that regenerates blobs and manifest together) is documented in the README. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * test(examples): assert disposal chains context destruction before worker termination The rollback path already required the generated Promise.resolve(destroyResult).catch(...).then(finish) chain; the disposal path only asserted index ordering inside __startWasiDisposal, which a started-but-not-awaited destroy would satisfy. Require the thenable chain there too, and document why a destroy rejection intentionally skips worker termination (disposal retry keeps the binding alive; executable counterpart in wasi-deferred-dispose-failure). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * docs(wasm-runtime): document the plugin requirement for raw instantiate callers Raw instantiateNapiModule(Sync) callers instantiating a single-threaded napi-rs wasm must pass the re-exported emnapi plugins; without them instantiation fails with a LinkError naming the missing import. Threaded builds link the C implementations and are unaffected. This mirrors the upstream @emnapi/core v2 plugin split (v1 bundled the implementations). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * ci: record the vendor/emnapi postinstall in the script-jail lock The root postinstall now runs `node vendor/emnapi/install.mjs` (vendored emnapi WASI archive verification + copy), so the committed script-jail lock drifted and the audit job failed. Regenerate it with the same pinned tooling and configuration the workflow uses (script-jail v0.2.10, docker backend, spoof linux/x64). The new entries are exactly the install script's observed behavior and nothing broader: - external_reads: the five vendor/emnapi files plus the two directory lookups ($REPO/vendor, $REPO/vendor/emnapi) - escaped_writes: the two <CROSS_PACKAGE> archive copies into $NODE_MODULES/emnapi/lib/wasm32-wasip1{,-threads}/ - spawn_attempts: `node vendor/emnapi/install.mjs` Verified locally: `check` mode re-runs the sandboxed audit and exits 0 against this lock, and the regenerated content matches the drift diff from CI run 29182709223 byte-for-byte (modulo the canonicalized generated_at timestamp). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * fix(build): keep thread-safe functions as JS plugin imports on threaded WASI The vendored `libemnapi-napi-rs-mt.a` was built from the full `emnapi` gyp source list, so it contained the C implementations of `threadsafe_function.c` and `async_work.c`. The linker extracts them (the Rust side references `napi_create_threadsafe_function` etc.), making TSFN/async-work wasm-local and silently shadowing the `@emnapi/core` v2 JavaScript plugin protocol that napi-rs is written against (upstream main links emnapi v1's *basic* flavor, `emnapi-basic-mt`, for exactly this reason). This broke the browser TSFN abort tests deterministically on any clean CI build: the test fixture instruments `importObject.napi.napi_call_threadsafe_function` and the plugin struct offsets (`wasi-worker-browser.mjs`), but the wasm never imported those functions, so `releaseBoundedTsfnNativeWait` timed out waiting for `NATIVE_QUEUE_CONFIRMED` (deferred-abort scenario) and the post-native scenario drained the bounded queue through the uninstrumented C path. - vendor/emnapi/build.mjs: build BOTH archives from the `emnapi_basic` gyp source list (no `async_work.c` / `threadsafe_function.c` in either threading mode) and add the `emnapi_basic` thread sources (`src/thread/async_worker_create.c`, `src/thread/async_worker_init.S`) to the threaded archive — the async-worker bootstrap the JS `asyncWork` plugin needs, matching v1's published `libemnapi-basic-napi-rs-mt.a` member list. `crates/build/src/wasi.rs` already exports `emnapi_async_worker_create` / `emnapi_async_worker_init` via `--export-if-defined` for these. - cli templates: wire `plugins: [asyncWork, tsfn]` unconditionally — the threaded node/browser loaders and both WASI worker templates now provide the JavaScript implementations too (previously threadless-only), since every thread that instantiates the module must resolve the TSFN imports. - examples/napi/build.mjs: teach the browser TSFN instrumentation markers about the new `plugins:` line and regenerate the committed loaders. Verified locally: threaded browser suite 26/26 full-suite runs green (8 tests each, including the two owner-agent TSFN abort tests that failed twice in CI run 29184777431), node WASI example suite green (296 passed), custom-async-runtime wasi + wasi-threads + browser fixtures green after a forced relink, and the napi3/napi4 cleanup-hook import checks pass against the rebuilt archive. The non-threaded archive rebuilds bit-identically. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * chore(examples,cli): adapt carried surfaces to the minimal SPI base and regenerate artifacts The minimal async-runtime SPI base (PR #3352 rewrite) removed the fallible lifecycle helpers, the lifecycle state machine, the TSFN exception-identity hardening, and the napi_prepare_wasm_env_cleanup wasm hook. Adapt the carried surfaces accordingly without touching crates/napi: - examples/custom-async-runtime: spawn/block/blocking wrappers now drive the example's own executor directly; lifecycle wrappers call the infallible start/shutdown SPI; drop probes that asserted removed crates/napi behavior (admission gates, TSFN thrown-value identity, wrap-slot preservation, dispose-time settlement of pending promises). - examples/napi: reduce build.mjs and the WASI specs to the surface that exists on the minimal base; regenerate loaders, typings and snapshots. - cli + crates/backend typegen: adopt the PR #3353 typegen surface coherently (Buffer type imports, centralized JSON escaping, iterator typings); the wasm env-cleanup call in loaders stays behind a typeof guard so it is a no-op until the hook exists. - examples/napi/src/class.rs: use 'declare class' in ts_return_type so the generated d.ts compiles under strict top-level declaration rules. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * test(examples): align explicit-shutdown assertions with the self-healing SPI base The rebased base restarts an idle backend on the next napi dispatch (ensure_started) and drains the lazily-created Tokio runtime at shutdown, so the stopped-runtime rejection and Tokio-backed context-entry assertions no longer describe the contract. Assert the restart (start metric + resolved promise) instead, and drop the now-dead stopped-iterator helper. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * test(examples): drop the unused readFileEventually helper Its callers were removed by the minimal-SPI adaptation commit; oxlint (--deny-warnings) fails the Lint job on the dead declaration. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * test(examples): re-stop the backend before each restart scenario The dispatch-driven self-heal grows startCalls before the worker-restart and explicit-start scenarios run, so comparing them against the older afterShutdown snapshot could pass even if the scenario started nothing. Shut the backend down again before each scenario and compare against a snapshot taken immediately before the action. Also assert runtimeContextAdd right after the self-heal: since the SPI base restores the drained Tokio peer on dispatch-driven self-heal, a successful start leaves both halves live. Calling it after shutdown but before any dispatch would still abort (inherited semantics). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * test(examples): assert the flavor-specific root artifacts per CI lane The minimal SPI base no longer merges natively-gated exports (like fetch) into WASI outputs, so the root index.d.cts only contains 'export declare function fetch(' when the native pass produced it. The checked-in roots are the native ones (regenerateArtifacts restores them), but the 'Test node wasi target' job regenerates the roots with the wasm32-wasip1-threads build right before running this spec, which drops the export and points browser.js at the threaded flavor. Assert the state each lane actually produces, keyed off WASI_TEST like the rest of the suite. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * test(examples): align the workerd dispose scenario with best-effort disposal The minimal SPI base dropped the env-cleanup preparation hook that settled pending napi promises before context destroy, so disposal no longer cancels in-flight promises; awaiting one across dispose() hung the workerd request until the runtime cancelled it (500), with the wasm side panicking at deferred.rs 'Call threadsafe function in JsDeferred failed'. Restoring that hook is a recorded napi-side follow-up. Reshape /dispose-reload to the contract this base documents: settle in-flight work before disposing and assert it completed, and keep pending-across-dispose coverage best-effort by firing a never-settling call that is recorded but never awaited in the response path. The scenario still asserts dispose + reload yields fresh exports and that new calls work. The stranded call may be cancelled or stay pending forever, but must never resolve with a value and must not prevent dispose or reload. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * docs(cli): scope the WASI disposal promise-settling to the preparation hook On the minimal SPI base the generated binaries do not export napi_prepare_wasm_env_cleanup (crates/build links it with --export-if-defined), so disposal cannot settle still-pending napi-rs promises. State the real contract: disposal releases the instance; pending promises are settled only when the binary exports the preparation hook (planned napi-side follow-up), otherwise they may remain pending and callers should settle work before disposing. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * ci: run the native custom-async-runtime lane in the wasi job The dedicated job only exercised the WASI modes and the example workspace is excluded from the root yarn test, so the native duplicate-registration, start-error, worker-reload and termination-loop scenarios ran nowhere in CI. Build and run the native lane in the same job before the WASI builds overwrite the shared root artifacts. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * fix(cli): use bigint/string file identity in the filesystem transaction journal The filesystem-transaction journal captured file and parent dev/ino from a non-bigint stat() and stored them as JSON numbers, then re-validated them on recovery with Number.isSafeInteger. On Windows a 64-bit NTFS file reference (ino) or volume serial (dev) frequently exceeds Number.MAX_SAFE_INTEGER, so the non-bigint read is imprecise, Number.isSafeInteger returns false, and recovery throws "Invalid file state in filesystem transaction journal" (flaky under the 400-file crash-recovery test on x86_64-pc-windows-msvc). Capture dev/ino from stat(..., { bigint: true }) at every journal identity source (openFileSystemTransactionIdentity, snapshotFileSystemTransactionInput source/destination, captureTransactionParentIdentity) and persist them as exact decimal strings, and compare the parent identity with a bigint stat at both the in-process (assertTransactionParentUnchanged) and recovery (assertFileSystemTransactionJournalParentUnchanged) checks so capture and compare share one representation. normalize now accepts either a decimal string or an exact (safe, non-negative) number and canonicalises both to a string, so existing numeric journals still recover while imprecise values are still rejected rather than allowed to false-match a different inode. The mode field and the reconciliation-lock identity subsystem are unchanged. No journal version bump: the reader stays backward compatible (numeric journals canonicalise to the same string form), which the v1/v2/v3 recovery fixtures require, so nothing is mis-parsed. Adds deterministic tests that force a >2^53 identity through the journal+recover path (accept/round-trip and no-false-match), which fail against the previous Number.isSafeInteger code and pass now. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * fix(cli): use string identity in the transaction cleanup unlink guard The failed-snapshot cleanup guard in snapshotFileSystemTransactionInput compared the destination's dev/ino with the lossy Number fields of lstat(). On Windows two distinct NTFS inodes past 2**53 (e.g. 2**53 and 2**53+1) collapse onto a single JS double, so a successor file that replaced the transaction-owned pathname could be wrongly unlinked - destroying a file the transaction never owned. This is the same "successor replaced our artifact" threat already handled correctly with string identity in the preparing-artifact cleanup path. Capture the destination's exact 64-bit identity once from the open handle (decimal strings) and gate the unlink on that string identity via the new snapshotLeftoverIsTransactionOwned predicate, re-reading the current file with a bigint stat. Also convert the source preflight's expectedStats comparison to exact 64-bit identity (affectedStats now holds bigint stats) so a Number-colliding external replacement of the source is detected as a conflict instead of being silently adopted. The fail-closed change-detection checks that only throw and the reconciliation-lock subsystem are deliberately left on Number equality. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * fix(cli): re-bind transaction source identity to the opened descriptor `snapshotFileSystemTransactionInput` validated the source's exact bigint identity only in the pre-open preflight; the single post-open gate compared the opened handle's Number `dev`/`ino` against the pre-window Number stat, not the caller's `expectedStats`. A successor whose 64-bit `dev`/`ino` collapse onto the same JS double (two distinct inodes past 2 ** 53) swapped into the pre-open window would be opened, pass the lossy Number check, and be snapshotted and recorded as the original. Re-bind the exact identity to the pinned descriptor: after `open`, when `expectedStats` is provided, `stat({ bigint: true })` the handle and raise a `fileSystemTransactionConflictError` unless its exact bigint `dev`/`ino` match. This completes the exact-identity binding 2496eb9 started and cannot newly accept anything (it only rejects), so callers without `expectedStats` are unaffected. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * fix(cli): gate transaction retire and recursive removal on exact bigint identity `fileSystemTransactionStateMatches` authorized `retireFileSystemTransactionState` (rename to a unique retired path + post-rename revalidation) and, through it, the recursive `rm(..., { recursive: true })` of the retired tree. It compared the Number `dev`/`ino` of live `Stats`, so a successor directory whose distinct 64-bit `dev`/`ino` collapse onto the same JS double (past 2 ** 53) passed both the pre- and post-rename checks and had its entire tree deleted. The structural mitigation (unique retire path + post-rename revalidation) was already present; only the comparison precision was lossy. Take `BigIntStats` and compare exact decimal strings (the pattern 2496eb9 already used for `pathsReferToSameDirectoryEntry`), and thread `{ bigint: true }` through every feeder: the candidate, sibling, journal and published captures plus the two re-reads inside the retire helper. No feeder reads `mode`/`size`/numeric `dev`, so no coercion is needed. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * fix(cli): preserve failed-snapshot leftovers whose identity fstat failed 2496eb9 hoisted the second (bigint identity) fstat on the exclusively created ('wx') snapshot handle out of the record block so it ran unconditionally, and folded "no first fstat" and "identity fstat failed" into one condition that unconditionally unlinked the leftover. When the first fstat succeeded but the bigint fstat failed (`destinationStats` defined, `destinationIdentity` undefined), the cleanup deleted a leftover whose ownership it could not prove. Extract the cleanup decision into a pure `failedSnapshotLeftoverCleanupAction` predicate and fail closed: only unconditionally unlink when no identity was ever captured; when the identity fstat failed, PRESERVE the leftover for the sibling scavenger; otherwise verify exact string identity before unlinking (owned-branch behavior unchanged). Also document the inherent two-syscall lstat-then-unlink pathname race in the owned branch: exact string identity narrows precision false-matches but cannot close the between-syscall window; a structural retire-by-rename fix is left as a follow-up rather than attempted in this PR. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * chore: regenerate lockfile and example artifacts after rebase onto main Reconcile the stacked non-threaded-WASI work with the squash-merged AsyncRuntime SPI base (#3352) and per-registration cleanup-hook fix (#3400): - yarn.lock: regenerated so it reconciles main's dependency bumps (notably oxc-parser 0.139.0 -> 0.140.0) with the example deps; `yarn install --immutable` is now clean. - examples/napi WASI binding surfaces and the type-def snapshot: regenerated so every flavor carries main's createErroringReadableStream export (the carried #3353 surfaces predated it). Produced via `yarn workspace @examples/napi regenerate` and `ava --update-snapshots`; not hand-edited. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * test: trim internal-tooling test suites to main's baseline The branch grew ~24k lines of tests for internal tooling: the pre-publish pipeline, packed-tarball CLI internals, build.mjs orchestration, patched-emnapi lifecycle guards, and hostile-lifecycle failure injection for the wasi loaders. Internal tools do not need exhaustive suites; the package manager already enforces patch application, and the loaders keep one eager and one deferred before-exit smoke plus the public Buffer API coverage. Ballooned pre-existing cli specs are restored to main's versions verbatim; create-npm-dirs/new/artifacts keep only the minimal delta the non-threaded wasi CLI behavior requires (engine floor, scaffold gitattributes, artifact source completeness). The test-cli-node-baselines workflow job existed only to run the deleted raw-cli harness and is removed with its needs entry; typescript-legacy was only used by deleted typegen additions. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * feat(wasi): consume released emnapi 2.0.0-alpha.3 wasip1 archives - bump emnapi/@emnapi/core/@emnapi/runtime to 2.0.0-alpha.3 and @emnapi/wasi-threads to 2.0.1 (deps + root resolutions); the release ships the complete wasip1 archive sets, so the vendored overlay, postinstall hook, CI install steps, and the @emnapi/core memory-view yarn patch are all removed - link libemnapi-basic-napi-rs.a for non-threaded wasi (basic composition: async work + TSFN stay JS plugin imports) and keep libemnapi-napi-rs-mt.a for threads (now the full C composition with in-archive async_work/threadsafe_function; only the two env-cleanup hooks are imported from the `napi` wasm module) - CLI preflight checks libemnapi-basic-napi-rs.a for wasm32-wasip1 - .script-jail.lock.yml postinstall profile hand-updated (vendored archive reads/writes/spawn removed); the docker-backend audit in CI validates it in check mode Co-Authored-By: Claude Fable 5 <[email protected]> * fix(napi): route remove_env_cleanup_hook through the wasm napi import module add_env_cleanup_hook resolves through #[link(wasm_import_module = "napi")] on wasm, but remove_env_cleanup_hook still went through sys, emitting an env-module import for the same symbol. The emnapi wasip1 archives bind their own cleanup-hook references to the napi module, so a wasm addon calling remove ended up importing napi.napi_add_env_cleanup_hook next to env.napi_remove_env_cleanup_hook: registration and removal targeted different implementations and a "removed" hook still fired at env teardown. Mirror the add side: declare the import in the wasm napi extern block and split Env::remove_env_cleanup_hook into the same native / wasm / wasm-noop arms. Verified by extending the wasi cleanup-hook link probe to call remove: both wasm32-wasip1 and wasm32-wasip1-threads now import exactly napi.napi_{add,remove}_env_cleanup_hook, with zero env-module hook imports and no cross-module duplicate imports. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(examples): restore fetch in the committed native binding surfaces The emnapi alpha.3 commit (a75bfa2) validated the released archives with a direct `build --target wasm32-wasip1 --profile wasi` run, which always rewrites index.cjs/index.d.cts (build.mjs passes --js/--dts unconditionally and only restores the native root outputs under --regenerate-all). The wasm-flavored metadata lacks the cfg(not(target_family = "wasm")) items, so `fetch` and `RequestInit` vanished from the committed files. The Linux docker test lanes consume these files as committed (they download only the prebuilt *.node artifacts), so async-exit.js failed at ESM instantiate ("Named export 'fetch' not found") and index.d.cts no longer matched the type-def snapshot. Lanes that run a full build regenerate the files and were unaffected. Restore the native-build blobs from 41600e7, whose regenerate run produced them with the rebased CLI; the restored index.d.cts is byte-identical to the committed ava snapshot content. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(cli): drop the stray brace that disabled the node_modules export guard resolveLegacyPackageTarget filters require.resolve results so a legacy main/module/types/browser entry that realpaths into node_modules (for example a symlinked entry file) is not emitted as a generated root export target: npm pack never ships node_modules, so such a target is broken for consumers. The guard's prefix string contained a literal 'node_modules}' (template typo), making the prefix '<root>/node_modules}/' unmatchable, so ./node_modules/... targets leaked into the generated exports map. Remove the stray brace so the guard matches real <root>/node_modules/ resolutions and the original legacy value is preserved instead. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * fix(cli): write the threadless WASI facade exports back to their source map only planThreadlessWasiRootFacade builds the facade export map from publishConfig.exports when the package defines one, but applyThreadlessWasiRootFacade then wrote that map to both the top-level exports field and publishConfig.exports. Since the applied manifest is synced back into the real package.json (stageRootReleasePlan -> syncThreadlessWasiRootFacadeManifest -> commitPrePublishFileSystemTransaction), the publish-only map clobbered the package's local/dev exports. Write the facade result back to whichever map it was built from - publishConfig.exports when that was the source, top-level exports otherwise - mirroring reconcileThreadlessWasiRootFacade, which already reconciles the two maps separately on removal. Packlist validation is unaffected: collectRootPackagePathReferences walks publishConfig.exports as well. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * fix(cli): compare filesystem identity as bigint across reconciliation and transaction guards The reconciliation lock/reclaim/candidate subsystem captured and compared ownership identity on numeric Stats.dev/ino, and the transaction snapshot / file-identity flows still used numeric stats for their path-vs-handle continuity checks. Past Number.MAX_SAFE_INTEGER (Windows NTFS file IDs and volume serials) two distinct filesystem objects collapse onto one JS double, so a replaced anchor, lock root, lock/reclaim/candidate metadata file, or snapshot source/destination could pass an ownership or continuity gate it should fail. Factor a single statIdentitiesMatch helper over bigint stats and route every dev/ino comparison in both subsystems through it (or through the decimal strings already derived from bigint stats). The reconciliation lock key now interpolates a bigint inode, so it stays exact past 2 ** 53; for inodes at or below Number.MAX_SAFE_INTEGER the rendered key is unchanged. Non-identity continuity fields move to their bigint forms (mtimeNs/ctimeNs are strictly more precise than the float mtimeMs/ctimeMs they replace). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * fix(cli): retire failed-snapshot leftovers by rename before deleting them The failed-snapshot cleanup guard verified ownership with an lstat of the destination pathname and then unlinked the same pathname — a TOCTOU window the code itself documented as a known limitation: a successor swapped onto the pathname between the two syscalls was deleted even though the transaction never owned it. Close the window with the subsystem's existing retire idiom (retireExactFileSystemTransactionPath / restoreUnexpectedFileSystemTransactionRetirement): atomically rename the leftover to a unique process-private sibling, revalidate the retired entry against the recorded 64-bit decimal-string identity, and unlink only a revalidated match — the retired name is unreachable to other writers, so the unlink deletes exactly the revalidated inode. A mismatched entry is hard-linked back to the destination, or preserved at the retired name when an even newer successor already reoccupied the pathname. The race window is covered deterministically in tests through the onBeforeRetire seam, which swaps a distinct inode onto the pathname between the ownership pre-check and the retirement rename. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * fix(cli): fall back to the module version export for emnapi v1 packages emnapi v1 @emnapi/core and @emnapi/runtime do not list ./package.json in their export maps, so the package.json subpath require threw a bare ERR_PACKAGE_PATH_NOT_EXPORTED before the descriptive version-mismatch error could fire for stale installs. Try the package.json subpath first (works on the pinned 2.0.0-alpha.3) and fall back to the module's own version export (works on v1). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * ci: do not persist checkout credentials in the custom async runtime wasi job The job only builds and tests; it never pushes, so the checkout token does not need to persist in the local git config (zizmor artipacked). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * chore(examples): regenerate WASI artifacts and values snapshot after rebase onto main Main added the type-tag surface (#3405); the rebase text-merged its export lines into the threaded WASI loaders but could not update the embedded artifact-metadata export lists, the wasip1 flavor loaders, or the binary AVA snapshot. Regenerated via yarn regenerate and a native values.spec.ts snapshot update so every flavor exports TypeTagA, TypeTagB and makeTypeTagA consistently. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * fix(cli): reject engines.node ranges disjoint from the WASI Node.js floor restrictWasiNodeEngine fell back to the entire WASI-supported range when the declared engines.node was valid but disjoint from it (e.g. ">=21 <22" or "<20"), so create-npm-dirs and pre-publish published metadata claiming support for Node.js versions the package explicitly excluded. Fail with an error naming both ranges instead. Malformed ranges still fall back to the WASI floor. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda * fix(cli): match generated .d.cts WASI loader typings in GENERATED_WASI_BINDING The d\.[ct]s branch only matched literal d.ts/d.cs, so the generated binary.wasi.d.cts / binary.wasip1.d.cts loader typings (already listed in WASI_CI_ARTIFACT_PATTERNS and written to .gitattributes by this file) were neither skipped by copyDirectory nor stripped by updateGeneratedWasiAttributes. Use the d\.[cm]?ts idiom shared with TYPE_DEF_FILE. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda --------- Co-authored-by: Claude Fable 5 <[email protected]>
The bug
napi_register_module_v1runs once per env — the main thread, everyworker_threadsworker (own V8 isolate + env), and every Electron renderer reload (env destroyed + recreated). On each call it:MODULE_COUNT(fetch_add(1)), andstart_async_runtime()(which lazily (re)creates the process-global shared runtime).Teardown is refcounted: the env cleanup hook
thread_cleanupdoesMODULE_COUNT.fetch_sub(1)and only callsshutdown_async_runtime()when the count reaches zero — i.e. the last live env.The cleanup hook was installed behind a process-wide one-shot gate (
ENV_CLEANUP_HOOK_ADDED: RwLock<bool>) that was set once and never reset, so it registered for the first registration only. Every additional or recreated env bumpedMODULE_COUNTbut registered no matching cleanup hook, so the count could never return to zero:shutdown_async_runtimewas never called on those envs' unload, so the runtime's backend threads/tasks outlived the addon image.The fix
Register the cleanup hook on every registration instead of once.
One subtlety makes a naive "always register" wrong: the same addon can be (re)loaded into the same env —
__tests__/unload.spec.jsdeletes therequirecache and re-requires the addon, sonapi_register_module_v1runs twice in one env. Node'snapi_add_env_cleanup_hookasserts every(fn, arg)pair is unique within an env (AddEnvironmentCleanupHook→CHECK(result.second)), so re-adding(thread_cleanup, null)aborts the process:So each registration is handed a distinct, never-dereferenced cookie (a monotonic counter cast to
*mut c_void) instead of a sharednull.thread_cleanupignores its arg — the cookie only keeps the(fn, arg)pairs unique. One hook per registration also keepsMODULE_COUNTbalanced (one decrement per increment), so the last env's teardown still shuts the runtime down exactly once.Verification
Reproduced the crash and the fix locally against the built
napi-examplesaddon (node v24,tokio_rt), mirroringunload.spec.js:cargo build -p napi --features tokio_rt/ default /--features fullbuild clean;cargo clippy -p napi --features tokio_rtreports no new warnings inmodule_register.rs.Scope
async-runtimeis not a feature onmain(it is introduced by #3352), so this fixes the pre-existingtokio_rtpath here. Split out of the #3352 review (codex,module_register.rs:577); when #3352 rebases, itsany(feature = "tokio_rt", feature = "async-runtime")cfg-widening of this block inherits the corrected per-registration behavior for free.🤖 Generated with Claude Code
Summary by CodeRabbit