Repository navigation
feat: first-party shared async runtime (napi-async-runtime + @napi-rs/async-runtime) - #3393
Conversation
📝 WalkthroughWalkthroughAdds a shared ChangesAsync runtime integration
Estimated code review effort: 5 (Critical) | ~120 minutes Possibly related issues
Possibly related PRs
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
3126249 to
80c2746
Compare
6d6ad3b to
56e32d5
Compare
969bd84 to
7aaa1bb
Compare
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_7430bacc-43dd-4f8c-90af-76c19b7e7bbd) |
There was a problem hiding this comment.
💡 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".
f1937b3 to
6929536
Compare
5f211d5 to
0800058
Compare
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_c8f3f67c-ae72-43d4-af17-a0b0d32dfd88) |
There was a problem hiding this comment.
💡 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".
0800058 to
59c283f
Compare
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_eadaa90a-4ec6-44a7-9b99-4bc9b9fd9b68) |
There was a problem hiding this comment.
💡 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".
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_37af5542-0fb8-48ff-aa25-20a6d918d2ce) |
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_ba9819ed-7ade-4156-b6f6-a283ead16210) |
4a50232 to
13eb972
Compare
bff693c to
68387fb
Compare
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_f78b3cf5-51da-484b-a98f-3cdbcad29c95) |
13eb972 to
b487f53
Compare
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
…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
68387fb to
7241650
Compare
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_bc628fc0-85d7-4a41-8fb1-6b11738f2887) |
There was a problem hiding this comment.
💡 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".
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (3)
async-runtime/workerd-timer-host.cjs (1)
32-42: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winValidate
registerTimerHostup 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 itsregisterCurrentThreadTaskHostbefore use. WhenregisterTimerHostis missing, the code still reserves a registration first and then surfaces a generic "not a function" error instead of the intended contract-mismatchTypeError. 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 winReinstalled host is never disposed at end of test.
Every other host lifecycle in this file is torn down via
disposeHosts(), but the finalreinstalldisposer from this test is never called. ConfirminstallCurrentThreadHostsdoesn't retain a handle that could keep the process/test runner alive; otherwise call the returned disposer in afinally/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 winCache doesn't cover
target/.This job compiles the crate across 4 target/feature combinations plus 2 native test runs; caching only
~/.cargo/registryand~/.cargo/git(unliketest-freebsdat Line 771, which also cachestarget) 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
⛔ Files ignored due to path filters (1)
yarn.lockis excluded by!**/yarn.lock,!**/*.lock
📒 Files selected for processing (28)
.github/format-staged-rust.mjs.github/workflows/test-release.yamlCargo.tomlasync-runtime/binding-mismatch-error.cjsasync-runtime/current-thread-hosts.cjsasync-runtime/current-thread-hosts.test.jsasync-runtime/index.cjsasync-runtime/index.d.tsasync-runtime/index.jsasync-runtime/package.jsonasync-runtime/workerd-hosts.test.jsasync-runtime/workerd-task-host.cjsasync-runtime/workerd-timer-host.cjscrates/async-runtime/Cargo.tomlcrates/async-runtime/README.mdcrates/async-runtime/build.rscrates/async-runtime/src/adapter.rscrates/async-runtime/src/async_runtime.rscrates/async-runtime/src/js_callback.rscrates/async-runtime/src/lib.rscrates/async-runtime/tests/consumed_api.rsexamples/shared-async-runtime/.gitignoreexamples/shared-async-runtime/Cargo.tomlexamples/shared-async-runtime/build.rsexamples/shared-async-runtime/package.jsonexamples/shared-async-runtime/src/lib.rsexamples/shared-async-runtime/test-wasi.mjspackage.json
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
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_56f7075e-5168-45c0-ac88-c372f9dd67f1) |
There was a problem hiding this comment.
💡 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".
There was a problem hiding this comment.
🧹 Nitpick comments (1)
async-runtime/current-thread-hosts.test.js (1)
801-853: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider 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.sizeafterdispose()runs. Since bothclearTimeoutandhandle.close()throw here,host.clearTimeoutis 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
📒 Files selected for processing (2)
async-runtime/current-thread-hosts.cjsasync-runtime/current-thread-hosts.test.js
🚧 Files skipped from review as they are similar to previous changes (1)
- async-runtime/current-thread-hosts.cjs
…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
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_82d4f46c-a698-4590-a6f8-f3b43d6f4b37) |
💡 Codex Reviewhttps://github.com/napi-rs/napi-rs/blob/977433486d86dcf9c53dd7dc243e26c751ffd10d/crates/async-runtime/src/async_runtime.rs#L3949 When a native addon selects ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
Re: the CurrentThread same-host timer parking review ( Verdict: OUT OF SCOPE. The raw mechanism reproduces (a Wake path at L3949 (native CurrentThread,
|
Stacked on #3353. Part of the pluggable async runtime effort (#3351, rolldown#9464).
This adds a first-party, reusable implementation of the
AsyncRuntimeSPI, 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,MultiThreadandCurrentThreadflavors, JS-host-relayed timers on single-thread, generation-quiescent shutdown. Scheduler is napi-free behinddefault-features = false; the defaultnapifeature adds the SPI adapter (task-host/timer-host ABI v4,configureAsyncRuntime/metrics exports) and a host-calledinstall(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 —
napiitself 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-APIAsyncRuntimeadapter) and the npm package@napi-rs/async-runtime(host contract v4 for CurrentThread task/timer registration).installCurrentThreadHostswires 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/registerWorkerdTimerHostcover per-instance workerd loaders.BindingMismatchError(ERR_NAPI_ASYNC_RUNTIME_BINDING_MISMATCH) surfaces contract/version mismatches.Workspace membership adds
crates/async-runtimeandexamples/shared-async-runtime. CI gainsnapi-async-runtime(tokio-freecargo treegate, tests, WASI checks) andtest-shared-async-runtime-wasi; both gate the aggregatedonejob..github/format-staged-rust.mjsgroups staged.rsfiles by package edition beforerustfmt, 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
@napi-rs/async-runtimewith consolidated exports for runtime configuration/metrics plus CurrentThread and timer hosting (including Workerd host registration).