Skip to content

feat: first-party shared async runtime (napi-async-runtime + @napi-rs/async-runtime) - #3393

Merged
Brooooooklyn merged 22 commits into
mainfrom
feat/shared-async-runtime
Jul 21, 2026
Merged

Brooooooklyn merged 22 commits into
mainfrom
feat/shared-async-runtime

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Jul 12, 2026 •

Copy link
Copy Markdown
Member

Stacked on #3353. Part of the pluggable async runtime effort (#3351, rolldown#9464).

This adds a first-party, reusable implementation of the AsyncRuntime SPI, extracted from Rolldown's production scheduler, so any napi-rs package can run multi-threaded on Node.js/browser and single-threaded on Cloudflare Workers without depending on tokio:

  • napi-async-runtime (crates/async-runtime): the shared scheduler — one pool for async polling + CPU work + bounded blocking IO, MultiThread and CurrentThread flavors, JS-host-relayed timers on single-thread, generation-quiescent shutdown. Scheduler is napi-free behind default-features = false; the default napi feature adds the SPI adapter (task-host/timer-host ABI v4, configureAsyncRuntime/metrics exports) and a host-called install(options).
  • @napi-rs/async-runtime (async-runtime/): the JS host protocol — CurrentThread task host + timer relay (contract v4), workerd per-instance variants.
  • examples/shared-async-runtime: end-to-end proof, including a threadless-WASI lane where the real adapter drives the real JS hosts (10 integration tests).

Wire protocol, export names, and contract version (4) are identical to Rolldown's current in-tree implementation, so Rolldown can consume this crate without ABI changes.

Note: RFC #3351 listed "bundling a specific third-party executor" as a non-goal. This PR deliberately revisits that as a separate opt-in crate — napi itself stays executor-free; the RFC text should be amended when this is reviewed.

Test summary: 318 Rust tests (default features) / 286 (napi-free), 40 JS package tests, 10 WASI integration tests, no tokio in either feature set.

🤖 Generated with Claude Code

https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda


Note

High Risk
New core async scheduling and JS↔Rust host lifecycle affect every binding that opts in; regressions can stall timers, leak process handles, or break WASI/threadless lanes, though coverage is heavy and the SPI remains optional.

Overview
Introduces an opt-in, tokio-free shared async runtime for napi-rs addons: the Rust crate napi-async-runtime (scheduler + optional N-API AsyncRuntime adapter) and the npm package @napi-rs/async-runtime (host contract v4 for CurrentThread task/timer registration).

installCurrentThreadHosts wires Node-style bindings to native exports via reserve → register → liveness, with deduplication, rollback on failure, and disposers that still clear armed timers when unregister throws. registerWorkerdCurrentThreadTaskHost / registerWorkerdTimerHost cover per-instance workerd loaders. BindingMismatchError (ERR_NAPI_ASYNC_RUNTIME_BINDING_MISMATCH) surfaces contract/version mismatches.

Workspace membership adds crates/async-runtime and examples/shared-async-runtime. CI gains napi-async-runtime (tokio-free cargo tree gate, tests, WASI checks) and test-shared-async-runtime-wasi; both gate the aggregate done job. .github/format-staged-rust.mjs groups staged .rs files by package edition before rustfmt, fixing lint-staged when edition-2024 sits beside 2021 crates.

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

Summary by CodeRabbit

  • New Features
    • Introduced @napi-rs/async-runtime with consolidated exports for runtime configuration/metrics plus CurrentThread and timer hosting (including Workerd host registration).
    • Added a shared-async-runtime example with native and threadless WASI coverage.
  • Bug Fixes
    • Improved staged Rust formatting to correctly format files across multiple Rust editions.
  • Tests
    • Added end-to-end test suites covering host registration/disposal, timer relay scheduling/cancellation, and adapter/WASI integration.
  • Documentation
    • Documented the shared, tokio-free async runtime and its N-API adapter behavior.
  • Chores
    • Extended CI to run new WASI-focused async-runtime lanes and aggregate results.

@coderabbitai

coderabbitai Bot commented Jul 12, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Adds a shared napi-async-runtime Rust crate with N-API CurrentThread host integration, JavaScript and Workerd host bridges, a shared-runtime native/WASI example, public package surfaces, edition-aware formatting, and CI coverage.

Changes

Async runtime integration

Layer / File(s) Summary
Runtime package and public API
Cargo.toml, crates/async-runtime/*, async-runtime/*
Adds the workspace crate, scheduler exports, N-API callback types, package entrypoints, TypeScript contracts, binding mismatch errors, and consumed API signature checks.
N-API scheduler adapter
crates/async-runtime/src/adapter.rs
Implements runtime configuration and metrics, CurrentThread task/timer host registration, callback relays, eviction, lifecycle handling, and adapter tests.
CurrentThread JavaScript host installer
async-runtime/current-thread-hosts.cjs, async-runtime/current-thread-hosts.test.js
Adds validated, deduplicated task/timer host installation with chunked timers, rollback, cancellation fallback, and idempotent disposal.
Workerd task and timer bridges
async-runtime/workerd-*.cjs, async-runtime/workerd-hosts.test.js
Adds Workerd task and timer registration, scheduling, cancellation, rollback, disposal, and compatibility tests.
Shared runtime example and WASI behavior
examples/shared-async-runtime/*
Adds async, sleeping, racing, and blocking N-API exports with native smoke tests and threadless WASI end-to-end tests.
Formatting and release validation
.github/format-staged-rust.mjs, .github/workflows/test-release.yaml, package.json
Adds edition-aware staged Rust formatting and release jobs covering native and WASI runtime builds and tests.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related issues

Possibly related PRs

  • napi-rs/napi-rs#3111 — Both changes adjust WASI-related async runtime workflow validation.
  • napi-rs/napi-rs#3353 — Both changes add WASI async-runtime CI jobs and include them in final workflow aggregation.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 88.31% 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 clearly matches the main change: introducing first-party shared async runtime packages.
✨ 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/shared-async-runtime

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/non-threaded-wasi branch 4 times, most recently from 3126249 to 80c2746 Compare July 15, 2026 11:47
@Brooooooklyn
Brooooooklyn force-pushed the feat/shared-async-runtime branch from 6d6ad3b to 56e32d5 Compare July 15, 2026 12:28
@Brooooooklyn
Brooooooklyn force-pushed the feat/non-threaded-wasi branch from 969bd84 to 7aaa1bb Compare July 18, 2026 16:21
@Brooooooklyn
Brooooooklyn marked this pull request as ready for review July 21, 2026 01:53
@cursor

cursor Bot commented Jul 21, 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_7430bacc-43dd-4f8c-90af-76c19b7e7bbd)

@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: 5f211d59a2

ℹ️ 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 cli/package.json Resolved
@Brooooooklyn
Brooooooklyn force-pushed the feat/non-threaded-wasi branch from f1937b3 to 6929536 Compare July 21, 2026 02:55
@Brooooooklyn
Brooooooklyn force-pushed the feat/shared-async-runtime branch from 5f211d5 to 0800058 Compare July 21, 2026 02:57
@cursor

cursor Bot commented Jul 21, 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_c8f3f67c-ae72-43d4-af17-a0b0d32dfd88)

@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: 0800058536

ℹ️ 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/build/src/wasi.rs Resolved
Comment thread cli/src/utils/misc.ts Resolved
@Brooooooklyn
Brooooooklyn force-pushed the feat/shared-async-runtime branch from 0800058 to 59c283f Compare July 21, 2026 03:06
@cursor

cursor Bot commented Jul 21, 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_eadaa90a-4ec6-44a7-9b99-4bc9b9fd9b68)

@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: 59c283f8a4

ℹ️ 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 async-runtime/workerd-timer-host.cjs Resolved
Comment thread async-runtime/current-thread-hosts.cjs Resolved
@cursor

cursor Bot commented Jul 21, 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_37af5542-0fb8-48ff-aa25-20a6d918d2ce)

@cursor

cursor Bot commented Jul 21, 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_ba9819ed-7ade-4156-b6f6-a283ead16210)

@Brooooooklyn
Brooooooklyn force-pushed the feat/non-threaded-wasi branch from 4a50232 to 13eb972 Compare July 21, 2026 05:10
@Brooooooklyn
Brooooooklyn force-pushed the feat/shared-async-runtime branch from bff693c to 68387fb Compare July 21, 2026 05:14
@cursor

cursor Bot commented Jul 21, 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_f78b3cf5-51da-484b-a98f-3cdbcad29c95)

@Brooooooklyn
Brooooooklyn force-pushed the feat/non-threaded-wasi branch from 13eb972 to b487f53 Compare July 21, 2026 05:42
Base automatically changed from feat/non-threaded-wasi to main July 21, 2026 05:58
Brooooooklyn and others added 4 commits July 21, 2026 15:09
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
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
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
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
Brooooooklyn and others added 9 commits July 21, 2026 15:09
…tive 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
…ws 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
…dows 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
…ed-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
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
…ha.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.
…SI 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
… 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
…isposal

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
@Brooooooklyn
Brooooooklyn force-pushed the feat/shared-async-runtime branch from 68387fb to 7241650 Compare July 21, 2026 07:13
@cursor

cursor Bot commented Jul 21, 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_bc628fc0-85d7-4a41-8fb1-6b11738f2887)

@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: 7241650ade

ℹ️ 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 async-runtime/current-thread-hosts.cjs 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.

Actionable comments posted: 1

🧹 Nitpick comments (3)
async-runtime/workerd-timer-host.cjs (1)

32-42: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Validate registerTimerHost up front for a consistent contract error.

The method-availability guard omits registerTimerHost, yet it's the core registration call used later at Line 216 (binding.registerTimerHost). The sibling task host validates its registerCurrentThreadTaskHost before use. When registerTimerHost is missing, the code still reserves a registration first and then surfaces a generic "not a function" error instead of the intended contract-mismatch TypeError. Capture and validate it alongside the others (and use the captured local at Line 216).

♻️ Proposed change
   const reserveCurrentThreadHostRegistration = Reflect.get(
     binding,
     'reserveCurrentThreadHostRegistration',
   )
+  const registerTimerHost = Reflect.get(binding, 'registerTimerHost')
   const unregisterTimerHost = Reflect.get(binding, 'unregisterTimerHost')
   if (
     typeof getCurrentThreadTaskHostContractVersion !== 'function' ||
     typeof isCurrentThreadHostRegistrationActive !== 'function' ||
     typeof reserveCurrentThreadHostRegistration !== 'function' ||
+    typeof registerTimerHost !== 'function' ||
     typeof unregisterTimerHost !== 'function'
   ) {

And at Line 216:

-    Reflect.apply(binding.registerTimerHost, binding, [
+    Reflect.apply(registerTimerHost, binding, [
       ...registration,
       schedule,
       cancel,
     ])
🤖 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 `@async-runtime/workerd-timer-host.cjs` around lines 32 - 42, Update the
method-availability guard in the timer-host setup to capture
binding.registerTimerHost and validate it alongside the other required methods,
so missing support throws the existing contract-mismatch TypeError before
reserving a registration. In the later registration call within the timer-host
flow, use the captured registerTimerHost local instead of accessing
binding.registerTimerHost directly.
examples/shared-async-runtime/test-wasi.mjs (1)

274-282: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Reinstalled host is never disposed at end of test.

Every other host lifecycle in this file is torn down via disposeHosts(), but the final reinstall disposer from this test is never called. Confirm installCurrentThreadHosts doesn't retain a handle that could keep the process/test runner alive; otherwise call the returned disposer in a finally/test.after().

🤖 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 `@examples/shared-async-runtime/test-wasi.mjs` around lines 274 - 282, Update
the “disposer tears down and a reinstall recovers” test to invoke the disposer
returned by installCurrentThreadHosts(binding) after the assertions, using
finally or the test’s cleanup hook so cleanup occurs even when assertions fail.
Preserve the existing reinstall and recovery checks.
.github/workflows/test-release.yaml (1)

829-835: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Cache doesn't cover target/.

This job compiles the crate across 4 target/feature combinations plus 2 native test runs; caching only ~/.cargo/registry and ~/.cargo/git (unlike test-freebsd at Line 771, which also caches target) leaves every incremental compilation artifact to be rebuilt from scratch on each run.

🤖 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 around lines 829 - 835, Update the
“Cache cargo” step in the release workflow to include the workspace target
directory in the actions/cache path alongside ~/.cargo/registry and
~/.cargo/git, matching the existing test-freebsd cache coverage.
🤖 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.

Inline comments:
In @.github/workflows/test-release.yaml:
- Around line 818-845: Update the checkout step in the napi-async-runtime job to
disable persisted Git credentials by configuring actions/checkout with
persist-credentials set to false, matching the existing
test-shared-async-runtime-wasi and test-custom-async-runtime-wasi jobs.

---

Nitpick comments:
In @.github/workflows/test-release.yaml:
- Around line 829-835: Update the “Cache cargo” step in the release workflow to
include the workspace target directory in the actions/cache path alongside
~/.cargo/registry and ~/.cargo/git, matching the existing test-freebsd cache
coverage.

In `@async-runtime/workerd-timer-host.cjs`:
- Around line 32-42: Update the method-availability guard in the timer-host
setup to capture binding.registerTimerHost and validate it alongside the other
required methods, so missing support throws the existing contract-mismatch
TypeError before reserving a registration. In the later registration call within
the timer-host flow, use the captured registerTimerHost local instead of
accessing binding.registerTimerHost directly.

In `@examples/shared-async-runtime/test-wasi.mjs`:
- Around line 274-282: Update the “disposer tears down and a reinstall recovers”
test to invoke the disposer returned by installCurrentThreadHosts(binding) after
the assertions, using finally or the test’s cleanup hook so cleanup occurs even
when assertions fail. Preserve the existing reinstall and recovery checks.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 81e97e51-04b4-4337-9934-da53d14e4618

📥 Commits

Reviewing files that changed from the base of the PR and between b5ecfa3 and 7241650.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (28)
  • .github/format-staged-rust.mjs
  • .github/workflows/test-release.yaml
  • Cargo.toml
  • async-runtime/binding-mismatch-error.cjs
  • async-runtime/current-thread-hosts.cjs
  • async-runtime/current-thread-hosts.test.js
  • async-runtime/index.cjs
  • async-runtime/index.d.ts
  • async-runtime/index.js
  • async-runtime/package.json
  • async-runtime/workerd-hosts.test.js
  • async-runtime/workerd-task-host.cjs
  • async-runtime/workerd-timer-host.cjs
  • crates/async-runtime/Cargo.toml
  • crates/async-runtime/README.md
  • crates/async-runtime/build.rs
  • crates/async-runtime/src/adapter.rs
  • crates/async-runtime/src/async_runtime.rs
  • crates/async-runtime/src/js_callback.rs
  • crates/async-runtime/src/lib.rs
  • crates/async-runtime/tests/consumed_api.rs
  • examples/shared-async-runtime/.gitignore
  • examples/shared-async-runtime/Cargo.toml
  • examples/shared-async-runtime/build.rs
  • examples/shared-async-runtime/package.json
  • examples/shared-async-runtime/src/lib.rs
  • examples/shared-async-runtime/test-wasi.mjs
  • package.json

Comment thread .github/workflows/test-release.yaml Resolved
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
@cursor

cursor Bot commented Jul 21, 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_56f7075e-5168-45c0-ac88-c372f9dd67f1)

@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: 5f14e9eab1

ℹ️ 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 async-runtime/workerd-timer-host.cjs 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)
async-runtime/current-thread-hosts.test.js (1)

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

Consider asserting the leaked timer stays pending at the host level.

This test proves the unregister throw is surfaced and the relay rejects, but never checks host.pending.size after dispose() runs. Since both clearTimeout and handle.close() throw here, host.clearTimeout is never reached, so the fake host should still show the timer as pending — directly confirming the "cannot release" scenario the test name describes, rather than inferring it only from the console message text.

♻️ Suggested addition
   assert.deepEqual(await relayOutcome, {
     rejected: true,
     error: reported[0],
   })
+  // The host-level timer was never actually cleared, since neither
+  // clearTimeout nor handle.close() succeeded.
+  assert.equal(host.pending.size, 1)
 })
🤖 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 `@async-runtime/current-thread-hosts.test.js` around lines 801 - 853, Add an
assertion in the disposal test after calling dispose that verifies the fake
timer host’s pending collection still contains the scheduled timer, using
host.pending.size. Keep the existing error, logging, unregister, and relay
outcome assertions unchanged.
🤖 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 `@async-runtime/current-thread-hosts.test.js`:
- Around line 801-853: Add an assertion in the disposal test after calling
dispose that verifies the fake timer host’s pending collection still contains
the scheduled timer, using host.pending.size. Keep the existing error, logging,
unregister, and relay outcome assertions unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 055891bb-45ea-4ba2-abf8-4c913fc5e74d

📥 Commits

Reviewing files that changed from the base of the PR and between 7241650 and 5f14e9e.

📒 Files selected for processing (2)
  • async-runtime/current-thread-hosts.cjs
  • async-runtime/current-thread-hosts.test.js
🚧 Files skipped from review as they are similar to previous changes (1)
  • async-runtime/current-thread-hosts.cjs

Brooooooklyn and others added 2 commits July 21, 2026 17:38
…ter 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
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
@cursor

cursor Bot commented Jul 21, 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_82d4f46c-a698-4590-a6f8-f3b43d6f4b37)

@chatgpt-codex-connector

Copy link
Copy Markdown

💡 Codex Review

https://github.com/napi-rs/napi-rs/blob/977433486d86dcf9c53dd7dc243e26c751ffd10d/crates/async-runtime/src/async_runtime.rs#L3949
P2 Badge Avoid parking a native CurrentThread host on its own timer

When a native addon selects CurrentThread and has only the calling Node environment registered, a synchronous block_on(sleep_until(...)) reaches this branch with threadless == false and parks indefinitely. The timer relay is queued through that environment's TSFN/setTimeout, but its event loop cannot service the callback while the same thread is parked; the default park_deadline is None, so no diagnostic interrupts the deadlock. Treat same-host timer waits as non-parkable or otherwise arrange an independent timer wake for this supported native CurrentThread configuration.

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

@Brooooooklyn

Copy link
Copy Markdown
Member Author

Re: the CurrentThread same-host timer parking review (crates/async-runtime/src/async_runtime.rs#L3949) — verified by reading the full control flow and by a watchdog reproduction.

Verdict: OUT OF SCOPE. The raw mechanism reproduces (a block_on on the sole env's own JS event-loop thread does park forever), but that is an unsupported misuse the crate already names a hazard — not a reachable production path, and the suggested remedy is not implementable at this layer without regressing the legitimate case. No code change.

Wake path at L3949 (native CurrentThread, block_on(sleep_until))

poll Sleep  → arms setTimeout on EVERY live timer-host env  (L9017-9029; drivers.live())
Pending, queue empty, no permit → PARK DECISION            (L3932)
self.threadless == false on native (const L199)  → skip the certain-panic (L3949-3953)
self.park_deadline == None (default)             → parker.park()  (L3959)
parker.park() == plain condvar wait              (L5941-5984)  ← no event-loop pump
WAKE = unpark() from the timer waker, fired when SOME env's setTimeout runs
       on THAT env's loop, cross-thread → notify_one() wakes the parked thread.

Two terminal cases, and the runtime cannot tell them apart:

(A) host loop runs CONCURRENTLY (another env / thread services setTimeout)
        → timer fires  → unpark → block_on returns.        [legit; the design's assumption]
(B) SOLE registered env AND block_on runs on that env's OWN event-loop thread
        → its setTimeout is queued on the loop this thread just blocked
        → never fires  → parks forever.                    [the claim]

TimerDriver carries no thread identity (trait TimerDriver, L7624: register/cancel/is_live/on_swept only), so the runtime has no way to know a driver's callback loop is the parked thread. It therefore cannot single out (B) without also breaking (A).

Watchdog harness (native CT, threadless=false, park_deadline=None, single live host)

CONTROL  host loop concurrent (StubHostTimerDriver, helper OS thread)
         block_on(sleep_until(now+50ms))  → returned in 148ms   (NO deadlock)
CLAIM    sole host = the parked thread's own loop (never fires independently)
         block_on(sleep_until(now+50ms))  → HUNG past 3s watchdog (DEADLOCK)

Both ran against the existing suite (318 tests) and were then reverted (no tree change). The control proves the harness observes the difference; the difference is entirely whether a concurrent thread delivers the wake. The existing test current_thread_park_deadline_with_live_host_timer_does_not_panic (L30364) already pins case (A) as legitimate — it must keep parking and waking.

Why out of scope (not a PR-contract defect)

  1. No production path hits it. #[napi] async fn → execute_future_impl spawns and returns a Promise (crates/napi/src/tokio_runtime.rs, return Ok(promise_value)); it never block_ons the JS thread. The only block_on(sleep_until) in the tree is a Node-less native cargo test in examples/shared-async-runtime that runs the MultiThread default, not CurrentThread on a JS thread. The JS host package (@napi-rs/async-runtime) only installs a task host + (relayId, ms) => Promise setTimeout relay — it never drives block_on synchronously.

  2. The shape is self-contradictory by design. Native CurrentThread is driven cooperatively by the JS event loop — host turns via TSFN (adapter.rs, drive_current_thread_tasks) and the setTimeout timer relay (async_runtime.rs:6543-6546). A synchronous block_on on that thread blocks both; nothing (tasks, timers, TSFN callbacks) can progress — timers are just one instance.

  3. Already documented and detectable. This exact shape is named in the diagnostics: "the block_on-awaiting-JS hazard … a block_on on the JS thread awaiting a JS continuation that can only run once this thread returns to the event loop" (CurrentThreadDeadline, L309-318; see also L236-242). The opt-in park_deadline surfaces it as the typed CurrentThreadDeadline panic. The default None (silent park) is the deliberate "a legitimately long park must never panic a production build" choice (L2597-2600).

  4. The suggested remedy is not implementable here. "Treat same-host timer waits as non-parkable" requires knowing the driver's loop is the parked thread — information TimerDriver does not carry — and would misfire on the legitimate concurrent-host park (A). The threadless-wasm certain-panic is only sound because wasm has provably no second thread; native cannot borrow that proof.

Net: the diagnostic correctly declines to panic here (native threadless == false); the only gap is that a caller who blocks the sole env's own event loop gets a silent park under the default, which is the documented park_deadline-off tradeoff, not a bug in this park decision. Recommend closing as out-of-scope / working-as-designed; if extra safety is wanted it belongs in host-facing docs ("do not block_on a runtime future on the CurrentThread host's event-loop thread") rather than in the L3949 park logic.

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