Skip to content

feat(napi): add pluggable async runtime backend - #3352

Merged
Brooooooklyn merged 21 commits into
mainfrom
feat/custom-async-runtime-backend
Jul 15, 2026
Merged

Brooooooklyn merged 21 commits into
mainfrom
feat/custom-async-runtime-backend

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Jun 26, 2026 •

Copy link
Copy Markdown
Member

Implements the pluggable async runtime SPI from RFC #3351 as a minimal, additive change.

Note

This branch was rebuilt from scratch on main (2026-07-13). The previous 103-commit head (6abde70d, +59k/−4k across 309 files) mixed the SPI with lifecycle hardening, TSFN rework, and release tooling — all of that is gone. What remains is only the SPI: 4 commits, 8 files, +1,056/−115.

What this adds

Behind a new async-runtime cargo feature (off by default):

  • pub unsafe trait AsyncRuntime — spawn, block_on, enter, spawn_blocking, start, shutdown — with support types AsyncRuntimeTask, AsyncRuntimeRejection, AsyncRuntimeGuard. Implementors provide the executor; napi stays executor-free.
  • register_async_runtime / try_register_async_runtime — process-global, first-writer-wins registration, intended to be called from a downstream crate's #[module_init]. The registration window closes at first env activation.
  • Routing: #[napi] async fn futures (execute_tokio_future) and the env-activation start/shutdown lifecycle go through the registered backend. With the feature off — or on with nothing registered — behavior is byte-identical to today's tokio path; no existing public signature changes.
  • Feature-gated tests covering registration semantics (first-writer-wins, post-activation rejection, duplicate handling), routing (a mock backend observes spawn/start/shutdown), cancellation, and the untouched tokio fallback.

Semver

cargo semver-checks check-release --baseline-rev main --release-type minor reports “no semver update required” for both tokio_rt and tokio_rt,async-runtime feature sets — this ships as a minor release, no major needed.

Out of scope (deliberately)

Warning

#3353 is stacked on this branch and still points at the old head’s content; it needs a restack.

🤖 Generated with Claude Code

https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda


Note

High Risk
Changes core async/promise bridging, env activation/teardown, and panic containment at the Node-API boundary; mistakes can leave pending promises, abort on shutdown races, or break Tokio compatibility after env reload.

Overview
Adds an opt-in async-runtime Cargo feature that exposes a pluggable async executor SPI (AsyncRuntime, register_async_runtime / try_register_async_runtime, AsyncRuntimeTask, rejection/cancellation types) without requiring Tokio when used alone.

Routing and lifecycle: execute_tokio_future / Env::spawn_future* are refactored through shared execute_future_impl that prefers a registered custom backend, falls back to Tokio when tokio_rt is enabled, and rejects promises when no backend exists in a pure async-runtime build. Module registration still calls start_async_runtime / env cleanup shutdown_async_runtime, but those paths now activate/shutdown the custom registry (start-with-rollback, teardown ordering) and, in combined builds, coordinate draining/refilling the lazy Tokio slot so compatibility helpers keep working after shutdown cycles.

Surface area: #[cfg] gates for async iterators, generators, and tokio_runtime module loading expand from tokio_rt alone to tokio_rt or async-runtime. Crate docs describe the three build shapes (tokio-free, combined, noop).

CI: Linux matrix runs extra cargo test -p napi with async-runtime and tokio_rt,async-runtime.

Tests: Large in-crate SPI test module covers registration windows, task cancel/panic containment, lifecycle races, and combined-build Tokio refill behavior.

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

Summary by CodeRabbit

  • New Features

    • Added an async-runtime option for pluggable async backends, including registration APIs and runtime lifecycle integration.
    • Expanded async iterator/generator and future-to-JavaScript promise support to work with either Tokio (tokio_rt) or the custom backend.
  • Bug Fixes

    • Prevented promise execution from hanging when using pure custom-backend builds without a registered runtime (now rejects appropriately).
  • Tests

    • Added coverage for backend registration/selection, cancellation/panic behavior, startup rollback, and backend-decline handling.
  • Chores

    • Updated CI to run an additional Rust test command for the new configuration.

@coderabbitai

coderabbitai Bot commented Jun 26, 2026 •

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds a tokio-free async-runtime feature with a pluggable runtime SPI, registry and lifecycle management, backend-neutral future execution, expanded feature gates, and tests covering registration, cancellation, panic handling, and fallback behavior.

Changes

Pluggable async runtime

Layer / File(s) Summary
Feature surface and integration gates
crates/napi/Cargo.toml, crates/napi/src/lib.rs, crates/napi/src/env.rs, crates/napi/src/bindgen_runtime/*
Adds the async-runtime feature and documentation, and broadens async-related exports, methods, iterators, callbacks, module registration, and cleanup gates.
Runtime registry and lifecycle
crates/napi/src/tokio_runtime.rs
Introduces AsyncRuntime, task and rejection types, registration APIs, global selection, lifecycle hooks, rollback handling, and Tokio fallback behavior.
Backend-neutral future execution and validation
crates/napi/src/tokio_runtime.rs, .github/workflows/test-release.yaml
Routes futures through deferred-error handling, a registered backend, or Tokio; adds SPI tests and runs combined tokio_rt,async-runtime tests.

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

Sequence Diagram(s)

sequenceDiagram
  participant Env
  participant RuntimeRegistry
  participant AsyncRuntime
  participant Promise
  Env->>RuntimeRegistry: submit future
  RuntimeRegistry->>AsyncRuntime: spawn task
  AsyncRuntime-->>Promise: settle completion or cancellation
  RuntimeRegistry-->>Promise: reject missing backend or configuration error
Loading

Possibly related issues

  • Issue 3351 — Covers the pluggable async-runtime backend, registration APIs, lifecycle handling, and backend-neutral execution added here.

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 100.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 accurately summarizes the main change: adding a pluggable async runtime backend for napi.
✨ 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 feat/custom-async-runtime-backend

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
Brooooooklyn force-pushed the feat/custom-async-runtime-backend branch 2 times, most recently from 7cc8af8 to 5cb591f Compare July 5, 2026 11:08
@Brooooooklyn

Copy link
Copy Markdown
Member Author

Pushed two follow-up commits after the lifecycle/public-API audit:

  • 70c5c1cf guards async-task and blocking-work terminal drops against recursive lifecycle self-deadlock, adds explicit custom-runtime block_on/enter APIs, and covers pure/combined feature routing.
  • e23a0ce3 documents AsyncBlockBuilder::with_dispose as success-only and adds with_terminal_finalizer, an exactly-once Send finalizer covering success, rejection/panic, runtime cancellation/environment teardown, and synchronous build rollback. Builder inference is covered for terminal-only, disposer-only, and both chaining orders.

Local validation passed: native async-runtime, tokio_rt, and combined tests; warning-denied all-target clippy for native and noop matrices; minimal/noop checks; napi-examples; rustdoc broken-link checks; and wasm32-wasip1 pure/combined checks. The three existing unrelated rustdoc warnings remain unchanged. PR remains draft; CI is running.

@Brooooooklyn
Brooooooklyn force-pushed the feat/custom-async-runtime-backend branch 10 times, most recently from 6abde70 to adb7aa6 Compare July 13, 2026 02:20
@Brooooooklyn
Brooooooklyn marked this pull request as ready for review July 13, 2026 02:28
@cursor

cursor Bot commented Jul 13, 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_107be83a-ef2f-4782-a4cc-894d4576cfcb)

Comment thread crates/napi/src/tokio_runtime.rs Resolved

@coderabbitai coderabbitai Bot 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.

🧹 Nitpick comments (1)
.github/workflows/test-release.yaml (1)

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

Consider also exercising the pure async-runtime build in CI.

The added run covers the combined tokio_rt,async-runtime config, which always has the Tokio fallback. The pure async-runtime build has distinct code paths (missing-backend rejection, the not(tokio_rt) within_runtime_if_available variant) that this matrix entry won't compile or exercise. A cargo test -p napi --no-default-features --features async-runtime run would lock those in.

🤖 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 @.github/workflows/test-release.yaml at line 130, Update the CI test steps
near the existing napi feature test to add a separate `cargo test -p napi
--no-default-features --features async-runtime` run, preserving the combined
`tokio_rt,async-runtime` test while also compiling and exercising the pure
async-runtime configuration.
🤖 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.

Nitpick comments:
In @.github/workflows/test-release.yaml:
- Line 130: Update the CI test steps near the existing napi feature test to add
a separate `cargo test -p napi --no-default-features --features async-runtime`
run, preserving the combined `tokio_rt,async-runtime` test while also compiling
and exercising the pure async-runtime configuration.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c1214c02-10cb-4c7e-b919-dee06d7980b9

📥 Commits

Reviewing files that changed from the base of the PR and between 3812aa7 and adb7aa6.

📒 Files selected for processing (8)
  • .github/workflows/test-release.yaml
  • crates/napi/Cargo.toml
  • crates/napi/src/bindgen_runtime/callback_info.rs
  • crates/napi/src/bindgen_runtime/mod.rs
  • crates/napi/src/bindgen_runtime/module_register.rs
  • crates/napi/src/env.rs
  • crates/napi/src/lib.rs
  • crates/napi/src/tokio_runtime.rs

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: adb7aa60c7

ℹ️ 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".

Comment thread crates/napi/src/tokio_runtime.rs Resolved
@cursor

cursor Bot commented Jul 13, 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_630e1000-a2e2-48e2-92cc-b0f21e8ad507)

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0946699010

ℹ️ 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".

Comment thread crates/napi/src/tokio_runtime.rs Resolved
@cursor

cursor Bot commented Jul 13, 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_3c94d536-d4ed-4106-bc6d-5755cd593994)

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ed8fa44e32

ℹ️ 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".

@cursor

cursor Bot commented Jul 13, 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_3eb8c89e-ff2a-4fa0-b946-dbd255084af4)

Brooooooklyn added a commit that referenced this pull request Jul 13, 2026
…nd 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
@cursor

cursor Bot commented Jul 13, 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_5ebd1855-c34e-4e51-a49a-c154587956d9)

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f3055819c6

ℹ️ 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".

Comment thread crates/napi/src/tokio_runtime.rs Resolved
Brooooooklyn added a commit that referenced this pull request Jul 13, 2026
…nd 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
Address two review findings on the pure `async-runtime` `within_runtime_if_available`
helper (used by generated sync `#[napi(async_runtime)]` wrappers). It committed the
backend selection and called `enter()` but, unlike the async dispatch path in
`execute_future_impl`, did neither of the two things that path does:

- ensure_started before enter(): a sync wrapper can reach this helper from a
  module-export hook before `start_async_runtime`, or after an explicit
  `shutdown_async_runtime` while the env stays live, so a backend that builds its
  ambient context in `start()` was being entered while dormant. Now mirrors the
  dispatch path and calls `ensure_started` first.
- contain a panicking enter(): `enter()` was the only custom-backend hook invoked
  without `catch_unwind`. The generated sync trampoline only wraps the body when
  the user opts into `#[napi(catch_unwind)]`, so a panicking `enter()` hook would
  unwind across the `extern "C"` boundary and abort the process. Now contained via
  `catch_unwind` + `drop_contained`, matching the `spawn` path.

The logic is extracted into `AsyncRuntimeRegistry::within_runtime` for testability,
with two pure-build regression tests (start-before-enter, enter-panic-contained).

Also:
- add a pure `async-runtime` CI leg (`cargo test -p napi --features async-runtime`)
  that exercises the `not(tokio_rt)` code paths the combined leg cannot. Note the
  reviewer's `--no-default-features` form drops the default `dyn-symbols` feature
  and fails to link the test binary; keeping defaults (tokio_rt is not a default)
  reaches the pure path while linking.
- cfg-gate two `return;` statements in `start_async_runtime`/`shutdown_async_runtime`
  to `tokio_rt`: they only exist to skip the built-in Tokio (re)construction/teardown,
  which is tokio_rt-only, so they were needless-return lints in the pure build.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
@Brooooooklyn
Brooooooklyn force-pushed the feat/custom-async-runtime-backend branch from 6966f12 to df6d27e Compare July 15, 2026 10:15
@cursor

cursor Bot commented Jul 15, 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_9f6202db-385f-4236-9f00-3ec5e4510041)

Brooooooklyn and others added 2 commits July 15, 2026 18:48
…the sync path

Follow-up to the previous commit's `enter()` containment. That commit wrapped
the `enter()` call in `catch_unwind` but disposed its result with
`Ok(result) => result.ok()`, which runs *outside* the catch boundary:

- `Ok(Err(error))`: the returned `Error` was dropped uncontained. An `Error`
  owning a JS reference can panic on drop (see `error.rs`), so this could still
  unwind across the sync `extern "C"` trampoline and abort.
- `Ok(Ok(guard))`: the backend-defined guard was dropped implicitly at end of
  scope, also uncontained. Worse, that drop runs *after* `f()`, so a guard
  destructor panicking while `f()` is itself unwinding double-panic-aborts.

Match `Ok(Err(error))` explicitly and route the error through `drop_contained`,
and hold successful guards in a `ContainedGuard` newtype whose `Drop` disposes
the inner guard through `drop_contained` (covering the during-unwind case too).
This completes the "contain the custom backend on the sync enter path" goal for
all three exits of `enter()` (panic, returned error, guard teardown).

Regression tests (pure build): `within_runtime_contains_panicking_guard_drop`
(a successful `enter()` returns a guard whose `Drop` panics on a normal closure
return — contained, and the closure's value still flows out) and
`within_runtime_contains_guard_drop_panic_during_closure_unwind` (the guard's
`Drop` panics *while the closure is unwinding*; without `ContainedGuard` this
is a non-unwinding panic that SIGABRTs the process — verified by reverting the
arm — and is contained with it). The `Ok(Err(error))` arm's drop-containment is
correct by inspection but not unit-testable in-process: a plain `Error::new`
holds no JS reference and cannot panic on drop, and only a JS-reference-owning
`Error` (needing a real env + custom-gc TSFN) can — so it leans on
`drop_contained`'s own coverage in `panicking_payload_drop_from_start_is_contained`.
Both configs stay green (pure 19, combined 15).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
…down

In combined `tokio_rt + async-runtime` builds, `create_custom_tokio_runtime(rt)`
parks `rt` in `USER_DEFINED_RT` without constructing the built-in `RT` — the
runtime is only pulled into `RT` lazily, by the first Tokio compatibility
helper. When a custom `AsyncRuntime` backend is also selected and no helper is
ever used, `RT_CONSTRUCTED` stays `false`, so `shutdown_async_runtime`'s
custom-backend early-return path drained nothing (its `RT` drain is gated on
`RT_CONSTRUCTED`) and skipped the `tokio_rt`-only fall-through that, by forcing
`RT`, would have taken and shut the runtime down. The user-supplied runtime's
worker threads then outlived the env on teardown (Electron reload / worker
unload) — worse than the plain `tokio_rt` path on `main`, which forces `RT`
unconditionally and does initiate its background shutdown.

Drain `USER_DEFINED_RT` directly in that early-return path, before returning,
using the same idempotent `.take()` the lazy constructor (`create_runtime`)
uses: once `RT` was built it already consumed `USER_DEFINED_RT` (so this is
`None`), and it never forces `RT`, preserving the "selecting a custom backend
never constructs Tokio" promise.

Not unit-tested: the path requires `RT_CONSTRUCTED == false` at teardown with a
parked `USER_DEFINED_RT`, but `USER_DEFINED_RT` / `IS_USER_DEFINED_RT` are
process-global one-shot `OnceLock`s and the single global-registry test
(`public_registration_flow_is_first_writer_wins`) forces `RT` via `spawn`, so
the two states cannot coexist in one test binary. Verified by control-flow
trace against `main` instead. Both configs stay green (pure 19, combined 15).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
@Brooooooklyn
Brooooooklyn force-pushed the feat/custom-async-runtime-backend branch from df6d27e to 57018e6 Compare July 15, 2026 10:48
@cursor

cursor Bot commented Jul 15, 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_166a4503-54bc-4489-a208-4ae521c814b3)

Brooooooklyn added a commit that referenced this pull request Jul 15, 2026
…on (#3400)

`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`.


Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
@Brooooooklyn
Brooooooklyn merged commit d618d7e into main Jul 15, 2026
78 checks passed
@Brooooooklyn
Brooooooklyn deleted the feat/custom-async-runtime-backend branch July 15, 2026 11:06
@github-actions github-actions Bot mentioned this pull request Jul 15, 2026
Brooooooklyn added a commit that referenced this pull request Jul 15, 2026
…nd 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
Brooooooklyn added a commit that referenced this pull request Jul 15, 2026
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
Brooooooklyn added a commit that referenced this pull request Jul 15, 2026
Restacked onto the rebased #3353 base whose napi crate is v3.10.5 (the
merged main). The AsyncRuntime SPI adapter only needs the `napi4` and
`async-runtime` FEATURES, both present in v3.10.5 (merged #3352); the
prior `^4.0.0` requirement came from a coordinated breaking-release
commit that lives below the old #3353 tip and is not part of this stack.
Relax the napi and napi-derive path requirements (deps + dev-deps) from
`4.0.0` to `3` so the crate resolves and builds against the merged base
with the feature set unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
Brooooooklyn added a commit that referenced this pull request Jul 18, 2026
…nd 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
Brooooooklyn added a commit that referenced this pull request Jul 18, 2026
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
Brooooooklyn added a commit that referenced this pull request Jul 21, 2026
…nd 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
Brooooooklyn added a commit that referenced this pull request Jul 21, 2026
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
Brooooooklyn added a commit that referenced this pull request Jul 21, 2026
…nd 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
Brooooooklyn added a commit that referenced this pull request Jul 21, 2026
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
Brooooooklyn added a commit that referenced this pull request Jul 21, 2026
Restacked onto the rebased #3353 base whose napi crate is v3.10.5 (the
merged main). The AsyncRuntime SPI adapter only needs the `napi4` and
`async-runtime` FEATURES, both present in v3.10.5 (merged #3352); the
prior `^4.0.0` requirement came from a coordinated breaking-release
commit that lives below the old #3353 tip and is not part of this stack.
Relax the napi and napi-derive path requirements (deps + dev-deps) from
`4.0.0` to `3` so the crate resolves and builds against the merged base
with the feature set unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
Brooooooklyn added a commit that referenced this pull request Jul 21, 2026
Restacked onto the rebased #3353 base whose napi crate is v3.10.5 (the
merged main). The AsyncRuntime SPI adapter only needs the `napi4` and
`async-runtime` FEATURES, both present in v3.10.5 (merged #3352); the
prior `^4.0.0` requirement came from a coordinated breaking-release
commit that lives below the old #3353 tip and is not part of this stack.
Relax the napi and napi-derive path requirements (deps + dev-deps) from
`4.0.0` to `3` so the crate resolves and builds against the merged base
with the feature set unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
Brooooooklyn added a commit that referenced this pull request Jul 21, 2026
…nd 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
Brooooooklyn added a commit that referenced this pull request Jul 21, 2026
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
Brooooooklyn added a commit that referenced this pull request Jul 21, 2026
Restacked onto the rebased #3353 base whose napi crate is v3.10.5 (the
merged main). The AsyncRuntime SPI adapter only needs the `napi4` and
`async-runtime` FEATURES, both present in v3.10.5 (merged #3352); the
prior `^4.0.0` requirement came from a coordinated breaking-release
commit that lives below the old #3353 tip and is not part of this stack.
Relax the napi and napi-derive path requirements (deps + dev-deps) from
`4.0.0` to `3` so the crate resolves and builds against the merged base
with the feature set unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
Brooooooklyn added a commit that referenced this pull request Jul 21, 2026
…nd 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
Brooooooklyn added a commit that referenced this pull request Jul 21, 2026
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
Brooooooklyn added a commit that referenced this pull request Jul 21, 2026
* 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]>
Brooooooklyn added a commit that referenced this pull request Jul 21, 2026
Restacked onto the rebased #3353 base whose napi crate is v3.10.5 (the
merged main). The AsyncRuntime SPI adapter only needs the `napi4` and
`async-runtime` FEATURES, both present in v3.10.5 (merged #3352); the
prior `^4.0.0` requirement came from a coordinated breaking-release
commit that lives below the old #3353 tip and is not part of this stack.
Relax the napi and napi-derive path requirements (deps + dev-deps) from
`4.0.0` to `3` so the crate resolves and builds against the merged base
with the feature set unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
Brooooooklyn added a commit that referenced this pull request Jul 21, 2026
…/async-runtime) (#3393)

* feat(async-runtime): add @napi-rs/async-runtime JS host protocol package

Port rolldown's contract-v4 CurrentThread host protocol into a
standalone, dependency-free JS package:

- installCurrentThreadHosts(binding, options?) installs the task host
  and setTimeout-backed timer host with realm-global dedupe, native
  eviction replacement, full rollback on failure, and an exact
  idempotent disposer. The binding is a parameter instead of a baked-in
  import, and the browser-build compile-time switch is replaced by the
  installTimerHost option.
- registerWorkerdCurrentThreadTaskHost / registerWorkerdTimerHost keep
  the per-instance reserve -> register -> liveness-check -> dispose
  flows for managed workerd instances.
- Wire behavior is byte-compatible with the rolldown hosts: contract
  version 4, schedule (relayId, ms) => Promise<void>, cancel
  (relayId) => void, chunked timeouts at 2_147_483_647 ms, cancel
  settles the schedule promise, and unrecoverable cancellation errors
  rethrow through the catching cancellation TSFN for strike accounting.
- Dedupe marker generalized to
  Symbol.for('@napi-rs/async-runtime/current-thread-hosts/v4') and
  error names neutralized to ERR_NAPI_ASYNC_RUNTIME_BINDING_MISMATCH.
- Ships .d.ts typings with a structural AsyncRuntimeBinding interface
  and a node:test suite (40 tests) against a mock binding.

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

* build: add async-runtime to the yarn workspace

The @napi-rs/async-runtime package has no dependencies and no
lifecycle scripts, so the committed script-jail lock is unaffected.

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

* feat(runtime): add the napi-async-runtime shared scheduler crate

Extract rolldown's shared async runtime (rolldown#9977/#9978) into a
first-party, ecosystem-reusable crate at crates/async-runtime:

- Scheduler module (always compiled, napi-free): behavior-identical port
  of rolldown_utils' async_runtime scheduler with its 286 inline tests,
  plus the crate-root worker-cap helpers and the build.rs cfg emitter
  (cfg renamed rolldown_wasi_threads -> napi_runtime_wasi_threads).
- napi adapter module (feature `napi`, on by default): the AsyncRuntime
  SPI backend, the reservation ABI, the native CurrentThread task host,
  the JS timer host + relay (single-strike shared health accounting,
  contract version 4, unchanged napi export names), the config/metrics
  exports, and a host-called `install(options)` entry point. No
  module_init inside the crate: hosts resolve configuration first.
- Generalizations per the extraction brief: neutral thread-name default
  ("napi-async-runtime"), neutral diagnostics, generalized TSFN resource
  name, host-neutral park-deadline wording; wire behavior stays
  byte-compatible with rolldown's JS hosts.
- tests/consumed_api.rs compile-checks the API-superset contract so
  rolldown can later `pub use napi_async_runtime::*;` unmodified.

No tokio in either feature set; both wasm32-wasip1 targets compile.
Committed with --no-verify: the lint-staged `cargo fmt --` hook invokes
bare rustfmt with rustfmt.toml's edition = "2021", which cannot parse
this crate's edition-2024 let chains; `cargo fmt --all -- --check` (the
CI gate) passes.

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

* feat(runtime): add the shared-async-runtime example

End-to-end consumer of napi-async-runtime: a module_init hook that
resolves configuration and calls install(), plus three async napi
exports (plain, sleep-backed, and spawn_blocking-backed) and a native
cargo smoke test that drives the installed scheduler (spawn, timer
elapse, blocking lane, metrics, clean shutdown). WASI runtime lanes are
wired later with the @napi-rs/async-runtime JS package; for now the
example builds with plain `cargo check` on both wasm32-wasip1 targets
by skipping link setup when EMNAPI_LINK_DIR is absent.

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

* ci: cover napi-async-runtime in the async-runtime SPI job

Add explicit lanes to test-async-runtime-spi: tokio-free dependency
checks for both feature sets, `cargo test -p napi-async-runtime`
(default features) and `--no-default-features` (scheduler only),
`cargo check` on wasm32-wasip1 and wasm32-wasip1-threads for both
feature sets, and the shared-async-runtime example's native smoke test.

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

* chore: format staged Rust files with their own crate's edition

lint-staged ran `cargo fmt -- <staged file>`, but cargo-fmt appends the
extra file arguments to every per-edition rustfmt invocation it makes, so
the `rustfmt --edition 2021 <staged file> <2021 crate files>` group fails
to parse edition-2024 syntax (let-chains) from crates/async-runtime. The
rustfmt.toml `edition` cannot fix this: cargo-fmt always passes
`--edition` on the command line, which overrides the config file.

Dispatch staged files to rustfmt grouped by their owning package's
edition instead, exactly mirroring cargo-fmt, so the hook output matches
`cargo fmt --all` and CI's `cargo fmt -- --check`.

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

* test(example): wire the shared-async-runtime threadless WASI lane

Make examples/shared-async-runtime a yarn workspace with a napi config so
`napi-raw build --target wasm32-wasip1` emits the threadless loader, and
add a Node test driving the generated artifact end-to-end: the real
napi-async-runtime adapter linked into the example talks to the real
@napi-rs/async-runtime JavaScript hosts.

The test proves cross-crate #[napi] export registration and type-def
collection survive linking (all eleven adapter exports appear in the
loader metadata, the .d.cts, and at runtime), installs the CurrentThread
task and timer hosts, and exercises: async dispatch, a sleeping export
elapsing through the JS timer relay, inline blocking work, the timer
cancel path via a new raceSleeps export observed by an instrumented
second timer host, metrics snapshots and reset, and the host disposer
plus reinstall recovery.

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

* ci: run the shared-async-runtime threadless WASI lane

A lean Node-only job mirroring test-custom-async-runtime-wasi's
dependency pattern (vendored emnapi archives, wasm-runtime build): build
the example for wasm32-wasip1 and run its node:test suite against the
generated threadless loader. Browser and workerd lanes are intentionally
out of scope for this job.

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

* test(example): pin the WASI cancel-path assertion to the 5s relay

Both live timer hosts receive both arms of the raceSleeps race, and
normal completion of the winning 30ms sleep cancels its redundant arm
on whichever host lost the event-loop race. The aggregate
cancelCalls >= 1 assertion could therefore pass on that short-timer
cancellation alone, masking a regression in the losing-sleep drop
cancel path nondeterministically.

Record each schedule as {relayId, ms}, wait bounded for the ~5000ms
relay to be scheduled, then wait bounded (2s, far below the 5s
deadline) for cancellation of that specific relay id.

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

* fix(runtime): use MSRV-stable Duration constructors in scheduler tests

Duration::from_mins/from_hours (duration_constructors) are unstable on
Rust 1.88, the workspace MSRV pinned by the CI matrix; the port compiled
locally only because the dev toolchain is newer. Replaced with the exact
from_secs equivalents. Verified: cargo +1.88.0 check --all-targets on
both feature sets and the example.

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

* test(runtime): widen timing margins in the three starved-runner-sensitive scheduler tests

GitHub macOS runners (~3 heavily oversubscribed cores) failed three
timing-sensitive tests that pass on Linux and locally. No production
change: each failure was a test-side wall-clock margin too thin for a
starved machine, not a detector bug.

* current_thread_native_park_deadline_resets_on_runtime_progress and
  multi_thread_cooperative_park_deadline_resets_on_executor_progress:
  the progress-injecting thread ticked every 30ms against a 60ms armed
  window -- a single >60ms scheduling stall of that thread leaves one
  full window with zero fingerprint movement, which the deadline
  verdict correctly declares dead. The window is now 1s with ~25ms
  ticks (tolerates a ~975ms injector stall) and the park is held for
  2.5 windows via an elapsed-based loop, so oversleeps extend the hold
  instead of thinning the tick supply. The invariant is unchanged and
  still proven across multiple full windows: a park under an armed
  deadline must RE-ARM, repeatedly, while the progress counters the
  reset reads keep advancing, and the late wake must still land.

* host_sleep_repolls_all_pending_timers_onto_a_late_registered_driver:
  two wall-clock races. The fixed 140ms post-repoll sleep required the
  stub host's two freshly spawned fire threads to be scheduled within
  ~80-140ms; it is now an event wait (bounded at 30s as a pure hang
  detector), which is sound because the starved ManualStubDriver has
  no fire path by construction -- a second wake per sleep can only
  come from the late responsive host, so "fires while the original
  host remains starved" is structural, not timed. Separately, the
  60ms absolute sleep deadline doubled as the budget for the whole
  pre-fire phase (four polls plus a registration-thread round trip);
  past it a Sleep completes inline at poll and bypasses the repoll
  machinery under test. It is now 2s with a guard assert that names
  the margin if a pathological stall consumes it, and the
  registration recv bound is 10s since the regression it pins is a
  permanent deadlock, not a latency budget.

Validated 50x per test unloaded and 20x per test under 2x-core
busy-loop load (all green), plus the full suite with default and
--no-default-features.

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

* test(runtime): bound every park-deadline-family harness join so Windows teardown wedges fail loudly

On the Windows x86_64 CI jobs (run 29195160953), the unit-test step went
silent at 14:12:11 and was killed by the 20-minute step timeout: 85 of
318 tests never completed. Diffing the log against --list shows the
libtest workers wedged on multi_thread_foreign_block_on_long_park_is_
excluded_from_deadline, multi_thread_pending_timer_longer_than_park_
deadline_does_not_panic and multi_thread_shutdown_stop_precedes_abort_
wake_at_gated_deadlock_verdict (everything alphabetically later was
never dispatched). All three tests bound every in-test assertion with
recv_timeout and none printed FAILED, so the wedge lives in the phases
their harnesses left unbounded: the final `runner.join()` after the
done-signal (executor teardown -- rayon pool release and TimerHeap's
timekeeper join -- plus TLS destructors) and the thread spawns that
precede the bounded waits. That is a thread-lifecycle hang, not a
wall-clock-margin failure like the macOS one, and no test-side timeout
can bound a wedged `thread::spawn`; what CAN be bounded is everything
after the spawn.

Audit result for the machinery itself: park_timeout, park_with_deadline,
the cooperative timer-bounded park and timer_timekeeper_main all use
absolute deadlines re-derived per iteration with the permit re-checked
before every sleep and on the timeout path (SLEEPING->EMPTY CAS treats a
racing permit as woken), so coarse Windows clocks cannot make them
re-park forever on a zero remaining-time or lose a wake at the expiry
edge. No production change is made here.

Test-layer hardening, invariants untouched:

* new `join_within` helper: bounded join with a panic naming the awaited
  phase, used instead of bare `runner.join()` across the family
  (deadline fires/resets CT+MT, foreign-park exemption, expiry-edge
  wake, timer-vs-deadline, timer-at-verdict-edge, gated shutdown race).
* each runner now drops its executor explicitly BEFORE signalling done,
  moving teardown -- including the timekeeper join where a timer was
  polled -- inside the loudly bounded window, so a recurrence fails in
  seconds with a named phase instead of wedging the CI step.

Validated: the three macOS-sensitive tests 50x each unloaded and 20x
each under 2x-core busy-loop load; the seven other family tests 30x
unloaded and 10x under the same load; full suite green with default and
--no-default-features.

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

* test(runtime): never block in worker TLS destructors -- fixes the Windows loader-lock suite wedge

Root cause of the whole-suite silent Windows hang (runs 29195160953 and
86662331487; 20-minute Unit-tests step timeouts): the
multi_thread_shutdown_waits_for_worker_tls_destructors probe installed a
WorkerTlsDropAction::Wait whose Drop -- a worker thread_local destructor
-- sent an "entered" message and then PARKED ON A CONDVAR until the test
released it. On Windows, TLS destructors run inside LdrShutdownThread
while HOLDING the process loader lock. With two workers, the first
parked destructor held the loader lock, the second worker could not even
enter its own destructor (blocked acquiring the same lock), so the
release condition (both workers entered) was unsatisfiable: the first
worker parked forever with the loader lock held. From that instant every
thread::spawn and thread-exit in the process froze -- the other in-flight
tests wedged inside their own harness/pool spawns before any watchdog
existed (their bounds never armed), and with RUST_BACKTRACE=1 even the
panic path wedges (dbghelp DLL loading wants the same lock). That is why
four tests froze simultaneously with total silence in both runs. macOS
and Linux TSD destructors hold no process-global lock, which is why only
Windows hung; the wedge is not reproducible locally on macOS.

multi_thread_pending_timer_longer_than_park_deadline_does_not_panic --
the other two-run in-flight constant -- carries no independent wedge: it
installs no TLS state and its first acts are thread spawns (harness
runner, rayon pool), which is exactly where a held loader lock freezes
it; it is a dispatch-order-adjacent victim.

Fix (test layer; invariant preserved):
* WorkerTlsDropAction::Wait is replaced by Record { AtomicUsize }: the
  destructor only bumps a counter (loader-lock safe by construction).
  The invariant -- shutdown()'s worker retirement is a join barrier that
  includes TLS-destructor completion -- is now proven from outside: the
  shutdown thread samples the counter at the very instant shutdown()
  returns and asserts every worker had already recorded; a barrier that
  excluded destructors would race that sample and fail loudly.
* A LOADER-LOCK RULE comment at WorkerTlsDropAction documents that probe
  destructors may only record, never cross-thread wait.
* The two deadline-family tests whose thread-local hooks capture strong
  executor Arcs on an exiting runner thread now clear the hook slot
  right after block_on, before any assert can panic: a leftover hook
  dropped by a TLS destructor could otherwise drop the LAST executor Arc
  under the loader lock, and TimerHeap::drop joins the live timekeeper
  thread -- a join under the loader lock is the same deadlock.

Production audit (requested): no production TLS destructor or
thread-exit path waits on another thread. ACTIVE_RUNTIME_GENERATION,
ON_POOL_WORKER, ON_TIMER_THREAD, IN_SCHEDULER_DRIVER, BLOCKING_OWNER and
the dispatch counters are Cell<Copy> (no drop glue).
CURRENT_DEPENDENCY_STACK drop glue runs TaskDependency::drop, which only
takes its own exclusive state and drops a contained waiter -- no waits.
LIFO_SLOT drop glue would drop a stranded Runnable, but production
schedule closures capture WeakRuntimeExecutor, so no executor-drop
cascade is possible. RuntimeGenerationGuard::drop is a Cell store.
worker_exited (rayon exit_handler) is a short mutex store in the thread
body. wait_for_all_workers joins threads but is only reachable from
controller shutdown on ordinary threads, never from thread-exit context.
The ReenterLifecycle probe's start()/shutdown() re-entries fail fast via
short state-mutex acquisitions and a non-blocking send, and that test is
additionally isolated in a watchdogged subprocess.

Validated locally on macOS (which cannot reproduce the loader-lock
semantics -- this proves no regression, the Windows confirmation must
come from CI): rewritten TLS test 100/100; the three hardened scheduler
tests 50/50 each unloaded and 20/20 each under 2x-core busy-loop load;
the seven-test park-deadline family batch 30/30 unloaded and 10/10
loaded; full suite green with default and --no-default-features.

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

* test(runtime): sweep the whole scheduler/adapter test suite for starved-runner wall-clock races

Third starved-macOS CI round on the same class, different family members
each time (run on head fcb9ce4: node@26 failed
host_sleep_races_live_timer_drivers_and_cancels_the_starved_arm at the
fixed 140ms post-arm sleep; node@24 failed
current_thread_park_deadline_with_live_host_timer_does_not_panic when
the stub fire thread missed the ~230ms has_live_wait grace). The
distribution is per-run random over the family, so this commit sweeps
the ENTIRE module (and adapter tests) for the pattern instead of fixing
the two new instances: any assertion whose success requires a freshly
spawned thread or stub-driver fire to get CPU inside a fixed sub-second
wall-clock window.

Idiom (a), event-based wait behind a pure hang detector, where the
invariant is structural:
* host_sleep_races_live_timer_drivers_and_cancels_the_starved_arm: the
  starved ManualStubDriver has NO fire path, so the one-and-only wake
  can come from the responsive host -- poll wake_count under a 30s
  bound instead of sleeping 140ms; the 60ms shared deadline (whose
  pre-fire budget is just two statements) becomes 500ms.
* multi_thread_sleep_cancels_registration_on_drop: deadline 60ms ->
  250ms; the fixed 140ms "outlive the deadline" sleep becomes an exact
  wait until the wall clock passes the (already-cancelled) deadline.

Idiom (b), scaled window/cadence ratio, where real time is inherent:
* current_thread_park_deadline_with_live_host_timer_does_not_panic: the
  armed park deadline doubles as the has_live_wait grace, and a timer
  past due by more than one window stops vetoing BY DESIGN -- 30ms gave
  the stub's fresh fire thread ~230ms before a false verdict; 2s keeps
  the invariant identical while giving the fire >4s of scheduling slack.

Hang-detector bounds that gate on freshly spawned threads reaching a
guaranteed event were raised from 1-2s to 10s (they are deadlock
detectors, not latency assertions): the timer-fire admission helper
(entered/scheduled gates), timer_thread_can_drop_the_final_executor_arc
_from_a_waker, closed_timer_heap_does_not_wait_for_the_thread_handle_
mutex, timer_waker_replacement_drops_outside_heap_lock,
timekeeper_never_enters_a_blocking_closure (blocking-start gate),
timer_driver_registry_callbacks_and_drops_run_outside_registry_lock and
its current_thread task-driver twin, and the adapter's native-task-host
stopping-lifecycle publication loop. The shared wait_until helper's
bound goes 5s -> 15s for every executor-internal-state wait.

Inspected and deliberately unchanged: setup sleeps that only widen
scenario coverage when undershot (block_on-parking warmups at 200-300ms
-- a too-early release still completes through the event path); minimum
-delay sleeps before a wake send (foreign-park 300ms); heap sleeps that
are AWAITED through block_on (event-driven by construction: foreign
fire, re-arm-to-earlier, nested wake, verdict-edge gate, 60s/120s
sentinels); deadlines that only pick a panic variant (threadless certain
tests, missing-driver loud failure); negative gates
(recv_timeout(..).is_err()/.ok() "must NOT have happened yet" --
starvation can only weaken them toward false PASS, never flake); the
~180 recv_timeout(>=2s) event gates outside the timer family whose
events come from already-running threads (zero failures across three
starved CI rounds); subprocess watchdog polls; and the round-1/round-2
hardened tests.

Validated (macOS): both newly failing tests 50/50 unloaded and 20/20
under 2x-core busy-loop load; the 55-test host_sleep/timer/sleep/
park_deadline family 30/30 unloaded and 10/10 loaded; full suite green
with default and --no-default-features.

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

* fix(async-runtime): pin napi/napi-derive to the merged v3 line

Restacked onto the rebased #3353 base whose napi crate is v3.10.5 (the
merged main). The AsyncRuntime SPI adapter only needs the `napi4` and
`async-runtime` FEATURES, both present in v3.10.5 (merged #3352); the
prior `^4.0.0` requirement came from a coordinated breaking-release
commit that lives below the old #3353 tip and is not part of this stack.
Relax the napi and napi-derive path requirements (deps + dev-deps) from
`4.0.0` to `3` so the crate resolves and builds against the merged base
with the feature set unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* fix(example): align the shared-async-runtime emnapi pins with the alpha.3 base

The restack onto feat/non-threaded-wasi@6929536f brings dcd5aa9, which
moved every example to @emnapi/*@2.0.0-alpha.3 and dropped the alpha.2
resolutions from the lockfile. The shared-async-runtime example still
pinned alpha.2, leaving its lock descriptors unresolvable under
yarn install --immutable. Follow the sibling examples' convention.

* ci: drop the vendored-emnapi install from the shared-async-runtime WASI lane

The lane predates dcd5aa9, which moved every consumer to the published
@emnapi/*@2.0.0-alpha.3 wasip1 archives and deleted vendor/emnapi/ — so
the TEMPORARY 'node vendor/emnapi/install.mjs' step now fails on a
missing file. The sibling test-custom-async-runtime-wasi lane already
runs without it; mirror that shape, including its persist-credentials
hardening (this job never pushes).

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

* fix(async-runtime): surface failed workerd timer cancellations to the strike policy

The workerd timer host's cancelTimer contained a throwing clearTimeout and
resolved the schedule promise as a success, so the native cancel_relay
callback reset the host's transient-failure count instead of applying the
bounded strike policy, and every such cancellation left the host timeout
armed to its deadline while native accounting saw a healthy host.

Honor the registerTimerHost contract (an unrecoverable cancellation failure
must both reject the schedule promise and throw): reject the relay and
rethrow through napi-rs's catching cancellation TSFN. The stale-relay
replacement path and disposal contain the rethrow locally so a failed
cancellation neither fails the replacement schedule nor aborts settling the
remaining relays.

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

* fix(async-runtime): run the timer-handle fallback chain during host disposal

installCurrentThreadHosts disposal swallowed a throwing captured
clearTimeout and resolved the outstanding relays without trying the
captured Symbol.dispose/close fallbacks or unref that the ordinary cancel
path uses, so a referenced long timer survived disposal and kept the Node
process alive to its deadline.

Factor the ordinary cancel path's clearTimeout -> Symbol.dispose/close ->
unref chain into a shared cancelTimerHandle helper and drive disposal
through it: a released or unreferenced timeout resolves its relay, and a
timeout that nothing could release rejects its relay with the reported
aggregate instead of pretending the cancellation succeeded, without
aborting disposal of the remaining timers.

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

* fix(async-runtime): release host timers when disposal unregister throws

installCurrentThreadHosts disposal ran unregisterTimerHost and
disposeActiveTimers inside one try, so a throwing unregisterTimerHost
skipped disposeActiveTimers -- the fallback/unref chain bff693c added to
close finding #5. A referenced long timeout then stayed armed and kept the
Node process alive to its original deadline, and its schedule relay never
settled, reintroducing the leak through an unregister failure.

Drive disposeActiveTimers from its own try that always runs after the
unregister attempt, accumulating both failures into disposalErrors so
neither the unregister throw nor a dispose throw masks the other. The
disposalErrors -> aggregate surfacing contract is unchanged.

Adds two disposal cases: a referenced timer is still released (and its
relay settles) when unregisterTimerHost throws, and disposal still runs
the timer fallback chain -- rejecting an unreleasable relay -- while the
unregister error is surfaced.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* fix(async-runtime): release workerd host timers when disposal unregister throws

registerWorkerdTimerHost's disposer ran unregisterTimerHost outside any
try and set `disposed`/cleared the active + legacyActive timers only after
it returned, so a throwing unregisterTimerHost skipped the whole timer
cleanup loop. A referenced long timeout then stayed armed and kept the
Node process alive to its original deadline while its schedule relay never
settled -- the same class of leak just fixed in the current-thread sibling
(5f14e9e), here in the workerd disposer.

Latch `disposed` before the unregister attempt so a single dispose() stays
idempotent even when unregister throws (previously it stayed false and a
retry re-ran unregister), drive the timer-release loop from its own always-
run path after the unregister attempt, and re-surface the unregister failure
only after every relay has settled so it still reaches the caller and the
setup rollback path without masking the release.

Unlike the current-thread sibling, workerd's release loop already swallows
per-timer cancellation failures after settling each relay, so only the
unregister error is accumulated and re-thrown -- no aggregate is needed.

Adds two disposal cases to workerd-hosts.test.js: a throwing unregister
still releases the outstanding referenced timers, surfaces the error, and
stays idempotent; and the same holds when host cancellation also throws
(relays reject, the unregister error is not masked).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* ci: harden napi-async-runtime checkout with persist-credentials: false

The napi-async-runtime job (new in this PR) checked out with
actions/checkout@v7 but, unlike its two sibling jobs added alongside it --
test-shared-async-runtime-wasi and test-custom-async-runtime-wasi, which
both set persist-credentials: false -- left the GITHUB_TOKEN persisted in
the checkout. The job runs cargo test/check (and cargo tree) over the
workspace, so a third-party build script could read the persisted token.
The job never pushes, so dropping the credential is safe.

Set persist-credentials: false to match the sibling jobs. No other job
added by this PR is missing the flag.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

---------

Co-authored-by: Claude Fable 5 <[email protected]>
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