Repository navigation
fix: CurrentThread waker-stack deadlocks and threadless-wasm Buffer detachment - #3489
Conversation
…ne on the waker's thread Cancelling queued work after a terminal host-dispatch failure drops each runnable with no executor lock held, but the drop itself can run inside a foreign lock: dropping task A's runnable closes A and notifies its awaiter, and when that awaiter is a `futures::Shared` its notifier wakes every registered waker while holding its own `wakers` mutex. If one of those wakers belongs to a parked, unscheduled task B, `async-task` schedules B, `CurrentThreadExecutor::schedule` sees `cancelling_failed_dispatch` and dropped B's runnable right there. B's future owns a clone of the same `Shared`, whose destructor re-locks `wakers` on the same thread, so the thread hangs forever. rolldown hit exactly this on `ROLLDOWN_RUNTIME=single` when a `worker_threads` Worker running watch mode was terminated with the debounce timer armed: the env cleanup hook unregisters the only task driver, the coordinator runnable is cancelled, and the Worker never leaves `node::FreeEnvironment`. `schedule` now defers such runnables into `CurrentThreadQueue::rejected` (guarded by the existing queue mutex) instead of dropping them, and the cancellation sweep drains that list on its own stack after releasing every lock, looping because each drop can reject more. The executor is reopened while holding the queue lock, which `schedule` also holds when it consults the flag, so nothing can land in the list after the final drain. `begin_shutdown` takes the list too, in case a sweep races shutdown. The `queue.closed` reject branch keeps dropping inline: `close_and_abort` has already scheduled every registered task by then, and deferring there would hold `GenerationWorkGuard`s that `wait_until_idle` waits on. The new unit test reproduces the shape with a real `Shared` and fails with a 5-second timeout instead of hanging on the unfixed code. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
…e shutdown side The previous commit left the `queue.closed` reject branch dropping the runnable inline, arguing `close_and_abort` had already scheduled every registered task. That misses a wake that is already in flight when shutdown starts: `async-task` sets SCHEDULED before it invokes the schedule closure, so a waker thread can be descheduled between that CAS and the executor's queue lock. The abort `close_and_abort` issues for the same task then coalesces with the in-flight wake and returns, and `begin_shutdown` closes the queue without waiting for the closure to land. When the closure resumes it is rejected by the closed queue and, if the waker was `futures::Shared`'s notifier (still holding `wakers`), dropping the future inline re-locks `wakers` from its `Shared` clone and hangs; the task's `GenerationWorkGuard` never retires, so `wait_until_idle` hangs with it. `schedule` now parks closed-queue rejections in `queue.rejected` too and wakes the generation's idle waiter. The executor is attached to its `GenerationWork` by the backend, and `RuntimeBackend::wait_until_idle` retires the parked runnables on its own stack, on every iteration, until the generation is idle; `notify_idle_waiters` publishes under the state lock so the check cannot miss a late arrival. `wait_until_scheduler_idle` and the executor's destructor drain the list for executors that are torn down without a backend, so no runnable (and no guard) can outlive the executor. The regression test pauses B's schedule closure inside the Shared notifier while `begin_shutdown` runs, and timed out on the previous commit. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (1)
Included review availability: Your plan provides up to 8 included reviews per hour; 7 remain after this review. 📝 WalkthroughWalkthroughThe runtime defers rejected runnable destruction until a clean stack. Threadless WASI buffers use live copied storage across memory growth. WASI bindings expose linear-memory size, and regression tests verify rejection handling and buffer validity. ChangesAsync runtime rejection handling
Threadless WASI buffer handling
Priority: ➖ Normal Estimated code review effort: 5 (Critical) | ~120 minutes Severity of issue fixed: Medium Merge Risk: ⚪ Minimal · up to BufferSlice reads remain validated across native and WASI targets; only WASI mutation visibility is excluded because copied mirror buffers do not reflect Rust writes back to JavaScript. No merge-blocking risk remains. Sequence Diagram(s)sequenceDiagram
participant Waker
participant CurrentThreadExecutor
participant Host
participant CurrentThreadQueue
Waker->>CurrentThreadExecutor: schedule runnable
CurrentThreadExecutor->>Host: dispatch host turn
Host-->>CurrentThreadExecutor: terminal dispatch failure
CurrentThreadExecutor->>CurrentThreadQueue: move work to rejected lists
CurrentThreadExecutor->>Host: reopen and notify idle waiters
Host->>CurrentThreadExecutor: clean host turn
CurrentThreadExecutor->>CurrentThreadQueue: retire rejected work
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 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 |
… a waker's stack The two previous commits stopped `schedule` from dropping a rejected runnable inline, but the terminal-failure sweep itself could still run on the waker's stack. `schedule` publishes a host dispatch whenever it queues work, and if the host fails that delivery before `dispatch` returns (a threadsafe function that is closing does exactly this while an env tears down) and fails the one replacement the same way, `publish_host_dispatch` enters the terminal transition and ran `cancel_work_after_host_dispatch_failure_claimed` right there. When the waker was `futures::Shared`'s notifier, still holding `wakers`, dropping a queued task that owns a clone of that `Shared` re-locked `wakers` on the same thread and hung; deferring into `queue.rejected` did not help because the sweep's own drain loop dropped the deferred runnable on that stack too. Every waker reaches the executor through `schedule`, so a thread-local depth (`CurrentThreadScheduleScope`) now marks stacks that may belong to a waker. A terminal transition reached at nonzero depth only publishes the closed state: `cancelling_failed_dispatch` stays set (schedules keep deferring, no dispatch is published) and the sweep is parked in `failed_dispatch_sweep_pending`. Clean stacks reclaim it: every host entry point (`complete_current_thread_task_delivery`, which also covers a driver unregistration that carries no failure, `cancel_host_dispatch`, `request_drain_if_queued` for a re-registering host) when not inside `schedule`, and unconditionally `begin_shutdown`, the generation's idle wait (which now also treats a parked sweep as deferred work, so the queued `GenerationWorkGuard`s cannot outlive `wait_until_idle`), `wait_until_scheduler_idle` and the executor's destructor. Reclaiming is a single compare-exchange, so a sweep runs at most once and reopens the executor exactly as before. Runnables are `Send`, but running the sweep on a helper thread was rejected: the crate has no such worker, threadless builds have no second thread, and host-affine futures must keep being destroyed on host or shutdown threads. The new unit test ports the reviewer's reproduction with a driver that fails accepted deliveries synchronously and timed out on the previous commit. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
… waker-stack terminal failure
The previous commit parked the terminal-failure cancellation sweep when the
transition was reached on a waker's stack and left the executor closed
(`cancelling_failed_dispatch` set) until a clean stack reclaimed the sweep.
That has no continuation of its own: with the driver still registered and
healthy again, every later `schedule` took the closed branch, was deferred
into `queue.rejected` and published no host delivery, so neither the
pre-failure work nor anything submitted afterwards ever ran. Only an
unprompted external entry (`request_current_thread_task_drain`, an
unregistration, shutdown) could reopen it; the previous regression test
supplied exactly such a drain and masked the stall.
The transition now moves instead of parking. Under the queue lock it moves
the queued runnables (with their `queued_runnables` debit) and the queued
blocking jobs into `queue.rejected` / `queue.rejected_blocking`, and then:
* on a clean stack it drops that work right there, with the executor
still closed so the tasks those drops wake are rejected and cancelled
with it, and reopens under the queue lock once nothing remains. This
is the ordering terminal cancellation always had; the timer-relay and
Shared-awaiter tests depend on it (queued work and everything it wakes
settle at once, no later host work is published);
* on a waker's stack it drops nothing and reopens immediately. The next
submission takes the ordinary path and publishes its own delivery, and
the moved work is cancelled by `retire_rejected_work` on the next clean
stack: the host turn that services that delivery
(`drive_admitted_host_turn`), any other host entry point (delivery
completion, unregistration, `cancel_host_dispatch`,
`request_drain_if_queued`), or the shutdown side (`begin_shutdown`, the
generation's idle wait, `wait_until_scheduler_idle`, the destructor).
The moved runnables keep their `GenerationWorkGuard`s, so the transition
notifies idle waiters and the idle wait retires rejected work exactly as it
did for closed-queue rejections. The drain loops terminate: each drop closes
one task for good, and a nested transition needs two more host-failed
deliveries of its own.
Deleted: `failed_dispatch_sweep_pending`, `run_pending_failed_dispatch_sweep`
and its `_off_waker_stack` twin, `CurrentThreadDispatchCancellationGuard::
defer`, `has_deferred_shutdown_work` / `retire_deferred_shutdown_work`, and
the `_claimed` split of the transition. `has_rejected_runnables` /
`retire_rejected_runnables` became `has_rejected_work` /
`retire_rejected_work`, which also cover the rejected blocking jobs. The
thread-local schedule depth stays: it is what tells the two branches apart
and gates the host-entry drains.
Tests: a fourth regression test ports the reviewer's reproduction (driver
stays registered, turns healthy, no drain request); it failed on the
previous commit with three deliveries instead of four. The third test now
observes the cancellation through a host turn instead of the drain request.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
…king contract `dispatch` is called from `schedule`, which may be a waker's stack while the waker's producer holds a lock (`futures::Shared` wakes under `wakers`). A terminal delivery failure cancels the rejected work on the stack of the thread that failed it, and a rejected future's destructor may re-lock that same mutex. A driver whose `dispatch` blocks its caller on the thread that later fails the delivery (spawn a helper that calls `fail_current_thread_task_delivery`, then join it) therefore deadlocks, on this branch and on every earlier release alike. Document the contract on the trait method: return promptly, never wait on another thread, in particular not on the one that will acknowledge or fail the delivery. Failing synchronously from inside `dispatch` on the calling thread is handled (the executor treats that stack as a possible waker's and defers the cancellation), and so is failing or acknowledging later from any thread. The Node-API driver in `adapter.rs` already satisfies this: one nonblocking threadsafe-function call, `false` at once on `napi_closing`. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
…drop inline
Audit of every place the MultiThread executor drops a `Runnable` or a
blocking job outside of running it, prompted by the PR note that
`MultiThreadExecutor::schedule` "still has a closed-queue inline drop":
* `MultiThreadExecutor::schedule` has no closed-queue branch for runnables
at all. Every runnable goes to the worker's LIFO slot or to the injector
(`push_to_queue_and_wake`), stop published or not. The only inline drop
on the submission side is `schedule_blocking_result`'s closed
`blocking_queue` branch, which destroys a blocking closure and its
result sender on the `spawn_blocking` caller's stack; the runtime's own
wakers never reach it (`Waker::wake` -> `WeakRuntimeExecutor::schedule`
-> `MultiThreadExecutor::schedule`), and dropping the sender only wakes
the awaiting task, which is a push, not a drop.
* A runnable that lands after `begin_shutdown` is cancelled when a drainer
(or a cooperative `block_on` driver) claims it under the published stop:
`claim_runnable` / `claim_fifo_runnable` -> `RunnableClaim::Cancel` ->
`cancel_runnable`, on that claimer's own stack, never the waker's.
* `begin_shutdown` drops the queued blocking jobs on the shutdown caller's
stack; shutdown from runtime work is rejected before that.
* The executor's implicit `Drop` (injector, blocking queue) runs after the
generation is idle, i.e. after every task future is gone, so no runnable
can still be queued and no waker can still reach `schedule`.
So the CurrentThread bug shape (a wake already SCHEDULED but not yet at the
queue when shutdown closes it, resumed under `futures::Shared`'s `wakers`
lock, and the rejected future re-locking it from its destructor) has no
MultiThread counterpart: the late runnable is accepted and cancelled
elsewhere. This test transposes the CurrentThread regression test one to
one and passes on the current tree. Two throwaway runs back the pin: with a
CT-style inline drop added to `schedule` behind `stop.is_stopping()` the
test times out after 5 s, and with `cancel_runnable` instrumented the real
cancellation is logged on pool worker `mt-inline-drop-0`
(`ON_POOL_WORKER` set), not on the waker thread.
No production code changes.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
…tach them `Test custom async runtime on wasm32-wasip1` has been red on every branch since 2026-09-07: `examples/napi/wasi-public-surface/test.mjs` asserted `'' !== 'Hello world'` for a `Buffer` the addon had just returned. Root cause is an asymmetry inside emnapi. `napi_create_external_arraybuffer` copies the bytes into a JS-owned `ArrayBuffer`, but `napi_create_external_buffer` is implemented as a *view* over wasm linear memory. A threadless wasm target has a non-shared memory, and the spec says every `memory.grow` on a non-shared memory detaches the previous `ArrayBuffer`. So any `Buffer` that JS is still holding across an allocation that grows the heap silently becomes a zero-length view: `.length` reads 0 and `.toString()` reads `''`, with no error anywhere. Threaded wasm targets use a shared memory whose old views stay valid, so they are unaffected. Whether a grow lands between the call that returned the `Buffer` and the read is a layout lottery: it depends on where `__heap_base` falls relative to a 64 KiB page boundary. The `encoding_rs` 0.8.40 bump added 16 bytes of `.rodata`, which shifted `__heap_base` just enough that the first heap allocation now crosses a page and grows the memory. That is a layout shift, not an `encoding_rs` defect - the bug was latent in every earlier build and the bump only exposed it. The fix adds a `create_external_buffer` wrapper in `crates/napi/src/bindgen_runtime/js_values/buffer.rs`. Under `cfg(all(target_family = "wasm", not(target_feature = "atomics")))` it returns `napi_no_external_buffers_allowed` instead of calling into emnapi, so the three call sites - `BufferSlice::from_data`, `BufferSlice::from_external` and `Buffer::to_napi_value` - take the `napi_create_buffer_copy` fallback they already carry for Electron. The result is a JS-owned, growth-immune `Buffer`. No new code path is introduced; each fallback still reclaims its leaked `Box` exactly once, and the `BUFFER_DATA` double-use registry is `not(target_family = "wasm")` so it is untouched. Typed arrays and `ArrayBuffer` need no change because their emnapi entry point already copies. The two `crates/napi/src/env.rs` sites are deliberately left alone: their fallback reuses the `result_data` pointer returned by `napi_create_buffer_copy`, which on emnapi points at a runtime-owned mirror rather than at the caller's allocation, so routing them through the same wrapper would hand out a pointer with the wrong ownership. `examples/napi` gains a `wasmMemorySizeBytes()` export. The workerd growth fixture used to measure linear memory as `getBuffer().buffer.byteLength`; now that a threadless `Buffer` is a copy, that probe no longer mirrors the wasm memory, so it reads `core::arch::wasm32::memory_size(0)` through the addon instead. Three regression tests hold a `Buffer` across a deliberate `memory.grow` and assert it still reads `'Hello world'`: the node spec `__tests__/wasi-buffer-public-api.spec.ts`, the browser fixture `wasi-public-surface/browser/test.mjs`, and the workerd fixture `wasi-public-surface/workerd/worker.mjs`. All three fail on the unfixed tree and pass with the fix. Co-Authored-By: Claude Opus 5 (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_32fd5d21-2cea-4bd0-969d-a057809d63b7) |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a0f1a7eec0
ℹ️ 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".
The previous commit adds a `wasmMemorySizeBytes()` export to `examples/napi` so the workerd growth fixture can read the size of wasm linear memory without going through a `Buffer`. The `values` spec snapshots the whole generated type definition file, so every native lane failed on "should generate correct type def file". Regenerated with `ava -u`; the only change is the new declaration and its doc comment. Co-Authored-By: Claude Opus 5 (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_808bf1bc-c043-4fb6-8092-96f73183bcc0) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cbd6e9b64f
ℹ️ 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".
…inuation `async-task` runs one scheduler callback for two different things: a wake, which any `Waker` can raise from any stack, and the very first schedule of a freshly submitted task, which `spawn` makes on its caller's own stack. The previous commit entered `CURRENT_THREAD_SCHEDULE_DEPTH` around all of `schedule`, so it could not tell them apart and treated both as a waker's stack. The interleaving that leaves: `spawn` queues the runnable and publishes a host dispatch; the host accepts the callback and fails the delivery before `dispatch` returns (a threadsafe function that is closing does exactly this), and fails the one replacement the same way. `publish_host_dispatch` reaches the terminal transition still inside that submission's `schedule` frame, sees a nonzero depth, moves the runnable into `queue.rejected`, reopens and returns. No host turn ever ran, `complete_current_thread_task_delivery` has already been called, and nothing else reaches `retire_rejected_work`: without a later submission, an explicit drain, an unregistration or shutdown, the returned `JoinHandle` stays pending forever and its `GenerationWorkGuard` stays active. Reproduced through the public API with a plain `spawn` from the main thread, no waker and no `futures::Shared` anywhere: dispatches=2, queued_runnables=0, handle pending, future destructor never run. The depth counter now marks only the frames a waker could have entered. `schedule` (the `async-task` callback, reachable from any `Waker::wake`) keeps entering the scope; `schedule_submission`, called only by `RuntimeBackend::schedule_submission` for a task's first schedule, does not. A submission's terminal failure therefore cancels its rejected work right there -- the only continuation it has -- while a genuine wake still defers, because the waker's producer may hold a mutex the destructors re-lock (`futures::Shared` wakes under its `wakers` lock). The wake-stack branch is untouched, so the executor still reopens at once instead of stalling a healthy, still-registered driver. Nesting stays conservative: a submission made from inside a wake frame does not clear the outer scope, so the depth stays nonzero and the transition still defers. Co-Authored-By: Claude Opus 5 (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_acce9a15-ca78-416f-b97f-df5277618835) |
…alue
`BufferSlice`'s three constructors built `inner` from `buf`, the `napi_value`
out-param, instead of from the buffer's data pointer. Since `raw_value` got the
same variable, `inner.as_ptr() == raw_value` on every path, so `Deref`,
`DerefMut`, `AsRef` and `AsMut` addressed the handle, not the bytes: on native
Node the V8 handle slot (reads return garbage), on wasm32-wasip1 the emnapi
handle id, i.e. linear-memory address 9.
This affects every constructor on every platform - native, Electron, threaded
and threadless wasm alike - not only the threadless-wasm copy fallback added
earlier on this branch. `FromNapiValue` was already correct, because it reads
through `napi_get_buffer_info`; the constructors simply disagreed with the
reader. `Buffer::to_napi_value`'s fallback only produces a `napi_value` and
builds no slice, so it was never affected.
Pointer now used per path:
from_data external ok -> the `Vec`'s `inner_ptr`
copy fallback -> `napi_get_buffer_info` on the new buffer
from_external external ok -> the caller's `data`
copy fallback -> `napi_get_buffer_info` on the new buffer
copy_from -> `napi_get_buffer_info` on the new buffer
The copy paths deliberately do not use `napi_create_buffer_copy`'s
`result_data` out-param, even though `env.rs` can. Under emnapi that pointer is
wrong: `napi_create_buffer_copy` allocates the copy as a JS-owned `ArrayBuffer`,
writes a lazily-mirrored wasm address into `result_data`, and only afterwards
copies the bytes into the `ArrayBuffer` - so `result_data` points at a still
zero-filled mirror. `napi_get_buffer_info` is the call that refreshes that
mirror, which makes it the only pointer that is correct on every target. It is
also what `FromNapiValue` uses, so constructors and reader now agree by
construction. The dead `result_ptr` in `copy_from` is gone with it.
Ownership is unchanged: `from_data`'s external path still `mem::forget`s the
`Vec` and its fallback still does not; `from_external`'s fallback still calls
`finalize` exactly once, promptly, after the copy; the copied region is never
freed from Rust and no owning container is built over it; `raw_value`, `len`
and the `len == 0` empty case are untouched.
Regression tests in `examples/napi` cover all three constructors on both lanes.
`bufferSlice*ReadBack` returns what Rust reads back through `Deref` and is
asserted on native (values.spec.ts) and on threadless wasm
(wasi-buffer-public-api.spec.ts, the only lane that runs the
`napi_create_buffer_copy` fallback for all three constructors). Before the fix
these read V8 handle-slot garbage on native and NUL bytes on wasm.
`bufferSlice*Mutated` writes through `DerefMut` and asserts JS sees it; that is
native-only, because emnapi's mirror is a one-way JS-to-wasm sync, so writes
through a copied buffer are dropped there - the long-standing "modifications may
be lost" caveat.
This is a pre-existing defect introduced by commit 521ef58 (PR #2263), not by
this branch. It is fixed here because the reviewer surfaced it on this PR and
the maintainer asked for one PR rather than a split.
Co-Authored-By: Claude Opus 5 (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_362178bc-585d-4351-8fe7-dc84722bed08) |
The three `BufferSlice::* points at the buffer data` tests added in 1b5fd9b fail the `Test node wasi target` job. That job builds `--target wasm32-wasip1-threads --profile wasi` and builds no native artifact, so `index.cjs` falls through to its first WASI candidate, `./example.wasi.cjs` - the threaded `wasm32-wasi` flavor. Only the second assertion fails: `readBack()` returns `'Hello world'` on every lane, while `mutated()` returns `'Hello world'` instead of `'hello world'`. The write is lost inside emnapi, not in `buffer.rs`. In `@emnapi/[email protected]`, `dist/emnapi-core.js`: `napi_get_buffer_info` (1874) delegates to `napi_get_typedarray_info` (1777), which resolves the data pointer with `emnapiExternalMemory.getViewPointer(v, true)` (1853). `getViewPointer` (1192) returns a real linear-memory address only when the view's storage is `wasmMemory.buffer`; otherwise it calls `getArrayBufferPointer(buffer, shouldCopy = true)` (1102), which mallocs a wasm-side mirror and re-copies JS into it on every access. Nothing ever copies the mirror back, so a `DerefMut` write through that pointer is dropped. Both wasm flavors take that branch, not only the threadless one. `create_external_buffer` gates the zero-copy path on `not(target_feature = "atomics")`, and `atomics` is an unstable target feature that rustc never surfaces to `cfg` - `rustc --print cfg --target wasm32-wasip1-threads` does not emit it, as `crates/async-runtime/build.rs` already records. So the threaded target reports `napi_no_external_buffers_allowed` too and all three constructors take the `napi_create_buffer_copy` fallback, which allocates the copy as a JS-owned `ArrayBuffer`. Measured against `example.wasi.cjs`: each returned Buffer's `.buffer.byteLength` is 11, not the ~1 GiB shared `wasmMemory.buffer`. The lost write is a platform property of any `BufferSlice` on wasm, not something the constructors introduced. A temporary probe export that lowercased byte 0 of a `BufferSlice` received as a function ARGUMENT - pure `FromNapiValue`, untouched by 1b5fd9b - reported len 11 and left the caller's Buffer at `'Hello world'` on the threaded WASI lane, while the same probe on darwin-arm64 produced `'hello world'`. That matches the existing `mutate TypedArray` / `mutate ArrayBuffer` tests, which have long been skipped outright under `WASI_TEST`. Only the write-visibility assertion is therefore gated, with the file's existing `if (!process.env.WASI_TEST)` convention. `readBack()` and `Buffer.isBuffer(value)` still run on every lane: reading the buffer data back through `Deref` is exactly the regression 1b5fd9b pins, and it has to stay asserted on wasm, where the old code addressed an emnapi handle id. `wasi-buffer-public-api.spec.ts` needs no gate - it only asserts the read direction - but its comment claimed the threadless lane was the only one running the `napi_create_buffer_copy` fallback. Corrected there as well. Co-Authored-By: Claude Opus 5 (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_ad624dca-8076-4798-b205-7ef86f5e9324) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d83b9e1016
ℹ️ 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".
a0f1a7e gated `create_external_buffer`'s `napi_no_external_buffers_allowed` fallback on `all(target_family = "wasm", not(target_feature = "atomics"))`, meaning to hit only threadless wasm. The gate misfired: rustc does not surface `target_feature = "atomics"` on wasm32-wasip1-threads either. `rustc --print cfg` for wasm32-wasip1 and wasm32-wasip1-threads is byte-identical, so `not(atomics)` was true on both and the threaded lane took the copy path too. Replace the second half of the condition with `not(napi_wasi_threads)`, a first-party cfg now emitted from crates/napi/build.rs off the exact cargo TARGET, the same trick crates/async-runtime/build.rs already uses for `napi_runtime_wasi_threads`. The condition is now "wasm AND the memory is not shared", where shared means `target_feature = "atomics"` (wasm32-unknown-unknown built with the atomics RUSTFLAGS) or the threads target. Restored on wasm32-wasip1-threads: `BufferSlice::from_data` and `from_external` are zero-copy views over `wasmMemory.buffer` again, so they cost no copy per Buffer and a Rust `DerefMut` write reaches JS. Verified with a probe on example.wasi.cjs: their storage is the 1075904512-byte SharedArrayBuffer and the mutated buffer reads back "hello world", where before it was an 11-byte JS-owned ArrayBuffer reading "Hello world". wasm32-wasip1 is unchanged: still an 11-byte copy, still immune to `memory.grow` detaching it. Test re-gating: d83b9e1 skipped the `DerefMut` write assertion in values.spec.ts under `WASI_TEST`, correct while both wasm lanes copied. It now runs on the threaded lane and skips only the threadless flavor, told apart by `NAPI_RS_WASI_FLAVOR === 'wasm32-wasip1'` -- the only way to reach that flavor, since the loader tries example.wasi.cjs first, and the discriminator wasi-eager-before-exit.spec.ts already uses. `copy_from` stays skipped on both wasm lanes: it calls `napi_create_buffer_copy` unconditionally and never goes through `create_external_buffer`. A new assertion pins the storage kind itself (`value.buffer instanceof SharedArrayBuffer` iff zero-copy) so a gate that silently reverts fails loudly instead of skipping. A `BufferSlice` received from JS remains a one-way mirror on every wasm target and is not asserted. Co-Authored-By: Claude Opus 5 (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_08ba6964-823a-4c6c-b801-fd7d36039d42) |
…own continuation
`6d452174` gave an ordinary submission a continuation; a genuine wake still
had none. The interleaving:
* a task is delivered, driven and parks on a wakeable (`futures::Shared`, a
oneshot, a timer);
* its waker fires. `schedule` enters `CurrentThreadScheduleScope`, queues the
runnable and publishes a host dispatch;
* the host fails that delivery before `dispatch` returns (a closing
threadsafe function, or any SPI host taking the synchronous-failure option
`CurrentThreadTaskDriver::dispatch` documents), and fails the one
replacement the same way;
* `publish_host_dispatch` reaches the terminal transition at nonzero depth.
It moves the runnable into `queue.rejected`, reopens, notifies generation
idle waiters and returns -- correctly dropping nothing on a stack that may
be under a foreign lock.
What it left behind was nothing at all. The transition consumed the executor's
one outstanding host request (`dispatch_pending` is 0) and emptied the queue,
so `has_serviceable_work` is false and neither `request_drain_if_work_remains`
nor a later wake of an already-parked task publishes again. During normal
operation there is no generation idle waiter either. The moved runnable kept
its `JoinHandle` and its `GenerationWorkGuard` until some unrelated entry
happened to arrive: a later submission, a drain request, an unregistration or
shutdown. Reproduced through the public API with a CurrentThread driver, a
task parked on a `futures::channel::oneshot` and no activity after the wake:
dispatches during the wake = 2, queued_runnables = 0, handle pending, the
future's destructor never run.
The waker-stack branch now publishes one fresh host dispatch for itself after
it reopens. A host turn is precisely the clean stack that retires the moved
work -- `drive_admitted_host_turn` calls `retire_rejected_work_off_waker_stack`
before it polls anything -- and the executor is already open, so this takes the
ordinary publication path and cannot starve a healthy registered driver. A
thread-local one-shot (`CURRENT_THREAD_RETIRING_REJECTED_WORK`) bounds it: that
publication calls the driver again, so a runnable another thread queues
meanwhile can drive a nested terminal transition on this same stack, and
without the one-shot a producer could recurse the stack without bound. It is
thread-local, not per-executor, because the bound it enforces is a stack bound
and a transition on another thread must keep its own continuation.
Nothing is destroyed on the waker's stack: this adds no `retire_rejected_work`
call. A nested transition inside the new publication still sees the outer
`CurrentThreadScheduleScope` and takes the waker branch, and the
`complete_current_thread_task_delivery` the driver runs there reaches only
`retire_rejected_work_off_waker_stack`, which returns at nonzero depth.
Rejected alternatives:
* Retiring at the end of the OUTERMOST `schedule` frame, when the depth
counter returns to zero. The stated grounds -- async-task's wake callback
returns to its caller before the caller releases its lock -- is exactly why
this does not work: `futures::Shared` calls `wake` on each awaiter from
inside its notify loop while holding `wakers`, so depth 0 at scope exit is
still under that mutex, and a rejected future owning a `Shared` clone
re-locks it on drop. That is the deadlock `8565a599` and `09905d45` fixed.
* Handing the rejected work (and `rejected_blocking`) to another thread.
Runnables are `Send`, but threadless wasm has no second thread and
host-affine futures must be destroyed on a host or shutdown thread. Already
rejected in `09905d45` for the same reasons.
When the host never recovers, the new publication fails or reports no live
driver, and that is terminal by construction: the queue is empty, so
`begin_host_dispatch_failure_transition_locked` reserves no replacement and no
further publication follows. The work then waits for the next host that
registers (`request_drain_if_queued` retires before it publishes) or for
shutdown. That is the honest limit of a host-driven executor: with no host
there is no stack on which user futures may be destroyed.
Tests: a fifth regression test parks B on a `futures::Shared`, loses exactly
the wake's publication and its one replacement, and then lets the host service
only the delivery the transition published for itself -- no later submission,
no drain request, no unregistration, no shutdown. It saw three deliveries
instead of four on the previous commit and B never settled. The two existing
waker-stack tests now count that extra self-published delivery.
Co-Authored-By: Claude Opus 5 (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_2730fede-3c0b-485e-a2d2-bd50f9677dcd) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: fc4d8e3bda
ℹ️ 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".
…ck to its owner `fc4d8e3b` gave a waker-stack terminal failure a continuation: it publishes one fresh host dispatch for itself, and the host turn that services it is the clean stack on which `retire_rejected_work` cancels the moved work. That publication calls the host driver again, so a thread-local one-shot (`CURRENT_THREAD_RETIRING_REJECTED_WORK`) bounds it -- and the one-shot DISCARDED a nested request instead of handing it back: thread W (waker) | thread T (producer) --------------------------------------+------------------------------------ Shared notifier wakes B -> schedule | publish D1 ................. fails | publish D2 (replacement) ... fails | terminal #1: B -> queue.rejected, | reopen (drop nothing here) | retirement scope ENTER, publish D3 ---+--> schedule(C) -> queue.runnables | request_drain -> Coalesced (D3) D3 fails, has_serviceable_work(C) | publish D4 (replacement) ... fails | terminal #2: C -> queue.rejected, | reopen | retirement scope already ACTIVE | -> return, publishing NOTHING | Four deliveries during the wake, all lost, no host turn ran, `dispatch_pending` back to 0 and `has_serviceable_work` false -- so nothing published again. Both B's and C's runnables stayed in `queue.rejected` with their `JoinHandle`s pending, their futures never destroyed and their `GenerationWorkGuard`s live, even though the host was healthy for its very next delivery. Measured on `fc4d8e3b`: dispatches during the wake = 4, terminal transitions = 2 (both on the waker's stack), discarded retirement requests = 1, host turns = 0, `queued_runnables` = 0, neither handle settled, neither future dropped. The nested transition now records its request in `CURRENT_THREAD_REJECTED_WORK_RETIREMENT_REQUESTED` and the frame that owns the publication loops: it publishes, and after its own publication has fully unwound it takes the flag and publishes again while rejected work remains. Nothing is destroyed on the waker's stack -- this adds no `retire_rejected_work` call, and the continuation is still a published host dispatch retired later at depth 0 by `drive_admitted_host_turn`. Termination. Each turn makes exactly one publication. Another turn happens only if a nested terminal transition ran inside it, which needs the host to fail two more deliveries AND at least one runnable or blocking job newly queued in that window; with an empty queue the first failure reserves no replacement, so no transition and no request follow. Rejected work is never re-scheduled while it waits (`async-task` keeps such a task SCHEDULED because its runnable still exists, so its wakers are no-ops), so every turn consumes one distinct live task or blocking job and none can supply a second. The first publication the host accepts ends the loop, because an accepted delivery fails nothing. A permanently dead host therefore exits after one turn, with the work waiting for the next registering host or for shutdown -- the limit already documented on this branch: with no host there is no stack on which user futures may be destroyed. The stack does not grow either way: the nested call returns at once and the retry is a loop in the owner frame, so at most two transition frames are live. Design. The flag stays thread-local, next to the one-shot it repairs, because the bound being enforced is a STACK bound: only a nested call on this same stack would recurse. A terminal transition on another thread finds the one-shot clear and keeps publishing its own continuation, which is correct -- its stack is its own. Rejected: moving the pending-request flag onto the executor. It would have turned that self-contained cross-thread continuation into a hand-off to a frame on another thread, which needs a release-then-recheck dance to close the set-vs-clear window and can publish a spurious extra delivery when both threads service the same flag -- two atomics and a lost-request proof, for a case that was not broken. It also would not have covered what a plain executor flag is sometimes credited with: a nested transition for a DIFFERENT executor on this stack still finds the thread-local one-shot held and records nothing anyone services, because a per-executor flag has no owner frame to drain it. Covering that needs per-(thread, executor) keying; I found no path to it in this crate (it takes two CurrentThread executors whose host dispatch callbacks interleave on one stack) and left it out rather than widen this fix. Tests: a sixth regression test drives exactly the interleaving above -- B parks on a `futures::Shared`, a producer thread queues C from inside the retirement turn's publication through a driver hook, the host loses all four deliveries and is healthy from the fifth -- and then services only that fifth delivery. It saw five deliveries instead of six on the previous commit and neither B nor C ever settled. Co-Authored-By: Claude Opus 5 (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_0ff5602f-d411-44d5-ade9-7d138d8ef6f8) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e2a8ed9c0d
ℹ️ 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".
…er's stack `e2a8ed9c` made the frame that owns a waker-stack retirement publication loop while nested terminal transitions kept handing requests back. Its termination argument -- every turn permanently consumes one distinct live task, because rejected work is never re-scheduled while it waits -- is true, and bounds the loop by the number of live tasks. A producer that keeps submitting makes that number unbounded in wall clock: thread W (waker) | thread T (producer) --------------------------------------+------------------------------------ Shared notifier wakes B -> schedule | publish D1 ---------------------------+--> schedule(C1) -> queue.runnables host fails D1 synchronously | request_drain -> Coalesced (D1) publish D2 (replacement) -------------+--> schedule(C2) host fails D2 synchronously | terminal #1: C1,C2 -> queue.rejected, | reopen (drop nothing here) | retirement turn 1: publish D3 --------+--> schedule(C3) host fails D3, sees C3 serviceable | publish D4 (replacement) -------------+--> schedule(C4) host fails D4 | terminal #2 -> request handed back | retirement turn 2: publish D5 --------+--> ... and so on, forever Every turn is two more host callbacks and two more producer submissions, and the producer's own drain request coalesces behind the publication already in flight, so it never blocks and never runs dry. Measured on `e2a8ed9c` with a driver that fails every delivery synchronously from inside `dispatch` and one producer thread queueing a runnable during every publication: 64 submissions gave 65 deliveries inside one wake, 1024 gave 1025, 32768 gave 32769 -- exactly 1:1 -- and a producer left running for a fixed window held the single `schedule` callback for the length of that window (50ms -> 51ms, 100ms -> 112ms, 200ms -> 204ms, 400ms -> 432ms). That callback is `futures::Shared`'s notify loop, so its `wakers` mutex is held for the whole time; any producer lock beneath the waker is held with it. This is latency and lock hold, not a deadlock: reachable only for an SPI host that fails deliveries synchronously from inside `dispatch`, since the built-in Node-API host returns `false` when the environment is closing (adapter.rs:654-676) and only ever fails a delivery from the threadsafe-function callback on the JS thread (adapter.rs:455-473) -- `false` yields `Unavailable`, which does not reach the terminal transition at all. The owner frame now publishes at most `REJECTED_WORK_RETIREMENT_ATTEMPTS` = 8 times. Two turns are all the known interleaving needs (one nested transition, which `e2a8ed9c`'s test pins); 8 leaves slack for a short burst of genuinely racing submissions, and caps this stack at 16 host callbacks -- a small constant to run under a foreign lock. Measured after: 18 deliveries (2 + 2*8) and ~0.3ms, for every producer budget and window tried, including 100M submissions and a 400ms window. End state after exhaustion. The budget is only reached through a publication the host FAILED -- an accepted delivery fails nothing and leaves no request -- so the executor is reopened, the queue is empty, `dispatch_pending` is 0 and the moved work waits in `queue.rejected`. That is exactly the dead-host end state this branch already documents: the work waits for the next depth-0 entry, every one of which retires rejected work (a host turn, a delivery ack/fail/unregistration, `cancel_host_dispatch`, a re-registering host, `begin_shutdown`, the generation's idle wait, `wait_until_scheduler_idle`, the destructor). And the producer that drove the budget to exhaustion supplies that entry itself while it keeps running: each further submission takes the ordinary `schedule_runnable` path, which publishes its own dispatch because `draining` is false, so a host that recovers is found by the next submission instead of by a ninth attempt on the waker's stack. Neither earlier defect returns: no sweep and no runnable drop is added to any waker-reachable stack, and the loop still publishes for every request it can service. Rejected alternatives: a time budget -- it leaves the number of host callbacks open, pins nothing an assertion can check, and reads a clock on a stack meant to do as little as possible; yielding the thread -- it does not release the producer's mutex, which is the thing being held; parking the leftover request on the executor for the next depth-0 entry -- those entries already retire `queue.rejected` unconditionally, so the flag would buy nothing the producer's own publication does not. Tests: a seventh regression test drives the interleaving above with a producer budget far larger than the loop can spend, asserts the wake makes exactly 2 + 2*REJECTED_WORK_RETIREMENT_ATTEMPTS deliveries while the producer is still willing to submit, and then shows nothing is stranded -- one more ordinary submission publishes its own dispatch, the healthy host services it, and that host turn retires everything the wake moved aside. It saw 4097 deliveries instead of 18 on `e2a8ed9c`. Co-Authored-By: Claude Opus 5 (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_075b00f7-8d0d-4bcc-a7f7-405c353b9715) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: fd47142960
ℹ️ 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".
… cannot swallow `fd471429` capped the waker-stack retirement turns at `REJECTED_WORK_RETIREMENT_ATTEMPTS` and argued that exhausting the budget strands nothing, because the producer that drove it to exhaustion supplies the next continuation itself with its next ordinary submission. It does not, if it has just made its last one: thread W (waker) | thread T (producer, budget 18) -------------------------------------+------------------------------------ ... turns 1..7 ... | ... C3..C16 ... turn 8: publish D17 -----------------+--> schedule(C17) -> queue.runnables host fails D17, sees C17 serviceable | request_drain -> Coalesced (D17) publish D18 (replacement) -----------+--> schedule(C18) <- its last one host fails D18 synchronously | (producer now quiescent) terminal #9: C18 -> queue.rejected, | reopen, request handed back | budget spent: the loop falls through | and the scope destructor clears it | Measured on `fd471429` with a host that refuses exactly those 18 deliveries and is healthy from the next one: 18 deliveries during the wake, `dispatch_pending` 0, `queued_runnables` 0, `queue.rejected` holding B and every C, B's `JoinHandle` pending, its future never dropped, its `GenerationWorkGuard` still active -- and not one delivery afterwards, with the driver registered and healthy for its very next one. The same end state was reachable with no producer at all, and after ONE turn rather than eight. A turn was driven by a thread-local flag that only a NESTED terminal transition set. An offer the host simply refused with an empty queue reserves no replacement, so it reached no transition and set no flag, and the owner frame returned with seven attempts unspent. Measured: 3 deliveries during the wake, everything else identical. Design. Both routes leave the identical executor state -- work parked in `queue.rejected`, no dispatch outstanding -- so the mechanism now reads that state instead of remembering a request. `needs_rejected_work_retirement_dispatch` is the whole condition a turn acts on, and it is checked before every turn: a nested transition changed exactly those two things (it moved more work aside and consumed the dispatch), so re-reading them is the same as being told. `CURRENT_THREAD_REJECTED_WORK_RETIREMENT_REQUESTED` and `CurrentThreadRejectedWorkRetirementScope::take_request` are deleted with it; nothing can discard a request that no longer exists. That alone fixes the refused-offer route and makes both routes one route, but it does not fix the interleaving above, because the budget still cuts. So the budget is given the narrower job it can actually do, and what it may not swallow is separated out. It bounds the turns a PRODUCER can inflate -- each is two host callbacks and two producer submissions, and without a cap the turns tracked the producer exactly (32768 submissions, 32769 deliveries in one wake; a 400ms producer held the `futures::Shared` `wakers` mutex for 432ms). After them, `publish_final_rejected_work_retirement` makes one offer that nothing can inflate: it holds the terminal-cancellation claim across the host callback, so `schedule` parks a racing runnable in `queue.rejected` instead of queueing it, and `begin_host_dispatch_failure_transition_locked` reserves no replacement while the claim is held. One host callback, no nested transition, no recursion, no budget of its own. Then it reopens under the queue lock and notifies idle waiters, the way the transition does. Rejected alternative: a sticky "retirement needed" flag on the executor, consulted by every publication path and cleared when the work is retired at a depth-0 safe point. It would delete neither the one-shot nor the budget -- a flag does not stop a nested transition from recursing the stack -- and it does not fix this finding at all: in the interleaving above nothing enters the executor again, so nothing consults the flag. Only a delivery is a continuation here. Also rejected: making EVERY turn a claimed one, which is uninflatable for the same reason it cancels a runnable that races it -- paying that for the ordinary turns would undo what `5857092f` reopened the executor for; and raising the cap, which only moves the boundary to the next delivery. End state. The wake now leaves either a dispatch outstanding or a host that refused the last delivery it was offered with nothing able to interleave with it. Nothing is destroyed on any waker-reachable stack: this adds no `retire_rejected_work` call, and a nested transition inside any of these publications still takes the waker branch. Deliveries during one wake go from `2 + 2*ATTEMPTS` to `2 + 2*ATTEMPTS + 1`, still a small constant under a foreign lock and still independent of the producer. When the host refuses the final offer too, the work waits undropped for the next host that registers or for shutdown -- the honest limit of a host-driven executor, now reached only after the host has refused every offer. Tests: the bound test no longer makes a submission of its own after the cap, which is what used to supply the continuation the code should have left; it asserts the new bound, that no dispatch is outstanding, and that `wait_until_idle` retires the work with no `GenerationWorkGuard` left. Two new tests take its place from the other side: one drives the interleaving above and lets the host accept only the final offer (18 deliveries instead of 19 before this commit, and B never settled), and one refuses the wake's publication, its replacement and the first offer with no producer at all, accepting the second (3 instead of 4). The two tests whose host refuses everything now count the extra turns. Co-Authored-By: Claude Opus 5 (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_bed2848b-02bc-437a-af9f-e7a0356c1d67) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6cfe200235
ℹ️ 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".
…inal offer inline
`6cfe2002` makes one last retirement offer after the attempt budget, with the
terminal-cancellation claim held so nothing can inflate it, and then reopens and
returns. A driver may claim, drive and acknowledge a delivery from inside
`dispatch` -- the registry supports that synchronous completion, and
`RacingTaskDriver` in this module's tests drives one inline -- and on THIS offer
such a turn can do nothing at all:
* it runs on the wake's own stack, so `drive_admitted_host_turn`'s
`retire_rejected_work_off_waker_stack` returns at nonzero schedule depth;
* the claim is still held, so `take_runnable` returns `None` and it drains
nothing either.
All it does is consume `dispatch_pending`. The offer then reopened the executor,
notified idle waiters and returned with no dispatch outstanding and
`queue.rejected` still holding the wake's runnable. Measured before this commit,
with a host that refuses the wake's publication, its one replacement and all
eight budgeted turns and then claims, drives and acknowledges the final offer
inside `dispatch`: 11 deliveries during the wake, `dispatch_pending` 0,
`queued_runnables` 0, B's `JoinHandle` pending, its future never dropped, its
`GenerationWorkGuard` still active -- and not one delivery afterwards, with the
driver registered and healthy for its very next one.
An offer the host ACCEPTED but could not act on leaves exactly the state a
REFUSED one leaves, so it is owed exactly the same thing, and the condition this
branch already reads off the executor says so:
`needs_rejected_work_retirement_dispatch` -- work parked and no dispatch
outstanding. So `publish_final_rejected_work_retirement` now reports whether the
host accepted its delivery, and an accepted offer whose dispatch was consumed is
followed by one ordinary publication. The executor is open again by then, which
is what `5857092f` reopened it for, so this takes the ordinary path. A refused
offer still leaves nothing behind, so no test whose host refuses everything
changes its delivery count.
Termination. It is one publication, not a loop, and the frame is returning. A
terminal transition nested inside it finds `CURRENT_THREAD_RETIRING_REJECTED_WORK`
held by this frame and publishes nothing, so at most its own one reserved
replacement follows it. Measured with the host refusing every delivery from the
inline service onwards: exactly 12 deliveries during the wake, and the wake
returned.
Nothing is destroyed on any waker-reachable stack: this adds no
`retire_rejected_work` call. The producer bound is untouched -- the budget still
caps the turns a producer can inflate, and this publication is as uninflatable as
the offer it follows, because it is made once.
End state. A host that consumes this publication on the waker's stack too has
never left that stack, and that is the limit this branch already documents: with
no host turn on a clean stack there is nowhere to destroy a user future, and the
work waits for the next host that registers or for shutdown.
Tests: a new regression test drives exactly this interleaving and then services
only the publication the consumed offer left behind, on a clean stack -- no
submission after the wake, no drain request, no unregistration, no shutdown. It
saw 11 deliveries instead of 12 before this commit and B never settled.
Co-Authored-By: Claude Opus 5 (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_87d8a40d-a737-4b73-8d6a-c474001d0198) |
Three statements named versions the branch has since moved past. - implementation.md: the plugin-error invariant said it depends on the workspace's `napi 3.12.1` registry pin. The root Cargo.toml pins `napi 3.12.7`, which is also what §9 of the same doc states. Now 3.12.7. - implementation.md: the WASI async-work drain credited the `napi_wasm_async_work_pending` / `napi_wasm_cancel_pending_async_work` exports to napi 3.12.7 / napi-build 2.4.4. Those releases carry them, but did not add them: both are absent from napi 3.12.5 and napi-build 2.4.2, and first appear in napi 3.12.6 / napi-build 2.4.3 (see napi-rs/napi-rs#3528). The 3.12.6 and 3.12.7 copies of `crates/napi/src/bindgen_runtime/module_register.rs` are identical, as are the 2.4.3 and 2.4.4 copies of `crates/build/src/wasi.rs`. Reworded to credit the adding release and say the pinned one carries it unchanged. - experimental-async-runtime.md: the "Worker teardown with an armed watch debounce" warning said the fix ships when napi-async-runtime 0.2.1 lands. It landed. napi-rs/napi-rs#3489 (merged 2026-09-09, bbebbb4baa6ec378bd280216c5eb2a337db4942a) names this exact scenario in its commit body, and crates/async-runtime/CHANGELOG.md lists it under 0.2.1 (2026-09-10). Rolldown pins 0.2.2 (crates/rolldown_utils/Cargo.toml), so the fix is in. Replaced the warning with a short past-tense note. No rolldown test covers this path, so none is cited: async-runtime-worker-teardown.test.ts runs MultiThread with a pending loader task, not an armed debounce. Also corrected the vendored-adapter paragraph in implementation.md. It said `RolldownAsyncRuntime` exists because 0.2.0 has no public API for installing the adapter from a downstream crate, and would be deleted when 0.2.1 exposed one. `napi_async_runtime::install` is public in 0.2.0 already (src/adapter.rs), so that was never the reason. The real constraint is the feature gate: `install` sits behind the crate's default `napi` feature, which also compiles the adapter's own `#[napi]` exports under names rolldown_binding already defines — `BindingRuntimeFlavor`, `BindingRuntimeOptions`, `BindingRuntimeConfig`, `BindingRuntimeMetrics`, `BindingHostRegistration`, `getAsyncRuntimeMetrics`. The pin therefore keeps `default-features = false`. The vendored struct is still method-for-method identical to 0.2.2's `SharedAsyncRuntime` (only the name, comment wording and rustfmt line breaks differ), so the doc now points at 0.2.2 rather than 0.2.0. No code change. Docs only; `just lint-repo` passes. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
Problem
On the CurrentThread executor,
CurrentThreadExecutor::scheduledropped a rejected runnable inline on the waker's thread when the queue was closed or a failed host dispatch was being cancelled. A waker can be invoked while its producer holds a mutex:futures::future::Sharedwakes its awaiters under itswakerslock. If the rejected future owns a clone of that sameShared, its destructor re-lockswakerson the same thread and the thread deadlocks.Found while reviewing rolldown/rolldown#10268 (deep review, finding L4-1):
ROLLDOWN_RUNTIME=single,watch()inside aworker_threadsWorker, a file change arms the debounceSleep, thenworker.terminate()/ in-workerprocess.exit(). The Worker thread never leavesnode::FreeEnvironment:Reproduced deterministically (5/5, 7/7, 5/5 across independent runs; symbolized stack in the debug build). MultiThread is immune because it never drops a runnable inline in
schedule.Fix
Commit 1 — the
cancelling_failed_dispatchreject branch pushes the runnable into a newqueue.rejectedlist under the queue lock instead of dropping it.cancel_work_after_host_dispatch_failure_claimeddrains that list outside any lock in a loop (each drop may reject more) and clears the cancelling flag under the queue lock only when the list is empty, so no runnable can be rejected after the final sweep.Commit 2 — the
queue.closedbranch had the same hazard through a narrower race (found by adversarial review): a wake already markedSCHEDULEDbut not yet at the queue lock coalesces with shutdown'sclose_and_abort, the queue closes, and the resumed wake dropped inline under the notifier lock. It now defers too. The executor holds itsGenerationWork(ArcSwapOption, attached byRuntimeBackend::new/from_executor); a rejected push notifies the idle waiters under the state lock, andRuntimeBackend::wait_until_idleusesGenerationWork::wait_until_idle_retiring, which drainsqueue.rejectedon every iteration without holding a lock, so deferred runnables cannot pin aGenerationWorkGuardpast shutdown.begin_shutdown,wait_until_scheduler_idle, andDrop for CurrentThreadExecutordrain as well.Commits 3 + 4 — the sweep itself could still run on a waker's stack (found by adversarial review, confirmed with a standalone repro).
schedulepublishes a host dispatch whenever it queues work; if the host fails that delivery beforedispatchreturns (a closing threadsafe function does this while an env tears down) and fails the replacement the same way,publish_host_dispatchentered the terminal transition and ran the cancellation sweep right there, dropping the queued runnable under the notifier lock. A thread-local depth counter now bracketsschedule, and the terminal transition has two orderings of the same steps: on a clean stack (depth 0) it drops the queued work and reopens, as before; on a waker's stack (depth > 0) it moves the queued runnables and pending blocking jobs intoqueue.rejected/rejected_blockingwithout dropping anything, reopens the executor at once, and returns. The moved work is dropped later on a clean stack: the next host turn before it runs tasks, delivery ack/fail/unregister,cancel_host_dispatch, re-registration,begin_shutdown,wait_until_idle_retiring,wait_until_scheduler_idle,Drop. Work submitted after the failure takes the normal path and publishes a fresh delivery, so a driver that stays registered and recovers is never stalled (commit 3 alone parked the sweep until the next host entry, which a healthy driver never produces; commit 4 replaces that).The inline-poll design at the existing comment is untouched.
queued_runnablesstays balanced: −1 at push time in both reject branches, no second decrement at retire.Tests
Four regression tests reproduce the interleavings with a 5 s timeout instead of a hang (task A with a
SharedJoinHandle, parked task B awaiting a clone; the second test blocks B's schedule closure on a barrier while shutdown closes the queue; the third uses a fake host that fails every delivery beforedispatchreturns; the fourth keeps that host registered, lets it recover, and requires a submission after the failure to be delivered and run without any external drain):current_thread_failed_dispatch_cancellation_does_not_drop_rejected_runnable_inlinecurrent_thread_shutdown_does_not_drop_in_flight_rejected_runnable_inlinecurrent_thread_synchronous_dispatch_failure_does_not_sweep_on_the_waker_stackcurrent_thread_submission_after_waker_stack_failure_is_delivered_to_a_healthy_hostEach fails on the commit before its fix and passes here (20/20 runs each).
cargo test -p napi-async-runtime: 331 passed, 1 ignored (+consumed_api1).cargo fmtclean,cargo +1.88.0 checkOK, no new clippy warnings.End to end: rolldown built against this branch, hang harness on the exact shipped release profile — CurrentThread terminate ×5, self-exit ×3, main ×1, early-terminate ×3, MultiThread ×3 after commit 2; CurrentThread terminate ×3, self-exit ×2, MultiThread ×2 after commits 3 and 4 each: all exit;
just test-async-runtime(both flavors) green. The standalone synchronous-failure repro hangs on commit 2 and exits on commits 3 and 4; the healthy-driver repro stalls on commit 3 and completes on commit 4.Also in this PR: threadless-wasm
BufferdetachmentThe
Test custom async runtime on wasm32-wasip1job went red on every branch on 2026-09-07, atexamples/napi/wasi-public-surface/test.mjs:222with'' !== 'Hello world'. It is not a scheduler problem and not a CI flake.emnapi implements
napi_create_external_bufferas a view over wasm linear memory, whilenapi_create_external_arraybuffercopies into a JS-ownedArrayBuffer. Threadless wasm memory is not shared, so everymemory.growdetaches the previousArrayBufferand aBufferthat JS still holds silently becomes zero length:Whether a grow lands between the call that returned the
Bufferand the read is a layout lottery.encoding_rs 0.8.40(published 2026-09-07, pulled in through the untrackedCargo.lockby the defaultlatin1feature) adds 16 bytes of.rodata, which shifted__heap_baseand cut the post-init dlmalloc headroom from about 20 KiB to a few hundred bytes, so the grow moved into the test window. That is not anencoding_rsdefect, and pinning it is not a fix: the headroom is not monotonic in the layout.The fix routes the three
Buffercreation sites (BufferSlice::from_data,BufferSlice::from_external,Buffer::to_napi_value) through their existingnapi_no_external_buffers_allowed→napi_create_buffer_copyfallback, the same path Electron already uses, on wasm targets whose linear memory is not shared. Threaded wasm keeps the zero-copy path, because shared memory grows without detaching the views already handed out. Telling the two apart takes more thantarget_feature = "atomics": rustc emits byte-identical cfg sets for the two WASI targets and sets that feature on neither, socrates/napi/build.rsemits a first-party cfg from the exact cargo target, the patterncrates/async-runtime/build.rsalready uses. An earlier commit on this branch gated on the feature alone, which quietly made the threaded lane copy as well; the tests now assert the storage kind per lane, so a reverted gate fails instead of passing silently. The twoEnv::create_buffer_with_*sites inenv.rsare deliberately left alone: their fallback reuses theresult_datapointer fromnapi_create_buffer_copy, which on emnapi is a runtime-owned mirror.The workerd
/growthfixture measured linear memory throughgetBuffer().buffer.byteLength, which the fix invalidates, soexamples/napigains awasmMemorySizeBytes()export and the fixture reads memory through it. Three regression tests hold aBufferacross a forced grow and assert it still readsHello world: the node spec, the browser fixture and the workerd fixture. Without the fix the node spec seeslength 0, the browser lane reproduces the exact CI assertion, and the workerd lane fails on the held buffer; with it all three pass, and the collateral WASI specs plus oxlint stay green.Also in this PR
CurrentThreadTaskDriver::dispatchstating the blocking contract:dispatchmust return promptly and must never wait on the thread that will acknowledge or fail the delivery. A review harness that joins such a helper insidedispatchdeadlocks onorigin/main, on crates.io 0.2.0 and on this branch alike; the napi adapter and rolldown's host call the threadsafe function in nonblocking mode and returnfalsesynchronously, and with that shape the harness passes on every revision.MultiThreadExecutoraudited for the same shape:schedulehas no closed-queue branch (always LIFO slot or injector push); late runnables are cancelled by the drainer between polls, never on a waker's stack. Pinned bymulti_thread_shutdown_does_not_drop_in_flight_rejected_runnable_inline(a CT-style inline drop added to MTscheduleas a mutation makes it fail in 5 s).Review round
The Codex connector raised three P1 findings. Each was verified before anything was changed.
Lock-order inversion in the idle wait: refuted. The claim was that
wait_until_idle_retiringholds theGenerationWorkstate mutex whilehas_deferredtakes the queue mutex, against aschedulethat holds the queue and then notifies. Both notify sites release the queue guard first, at thedrop(queue)beforenotify_idle_waitersin the reject branch and in the terminal transition. Enumerating all thirteen queue lock sites and all seven state lock sites gives a one-directional graph, state to queue only. A temporary detector that counted queue guards per thread and probed every state site ran the whole suite with zero inversions, a negative control with an injectedstatelock under the queue lock fired as expected, and inverting the detector's own predicate failed six tests, which shows the probe was live.An ordinary spawn could stall forever: confirmed and fixed. If both host publications fail synchronously during a plain
spawn, the runnable was moved torejectedand the executor reopened, but no host turn ever followed and the delivery had already completed, so nothing reachedretire_rejected_workand the returnedJoinHandlestayed pending with its generation guard held. The depth scope was too coarse: it wrapped every call intoschedule, including a submission on its own caller's stack.async-taskuses one callback for a wake and for a task's first schedule, and only the wake can arrive under a foreign lock, so the two are now separate.CurrentThreadExecutor::schedule, the async-task callback, keeps the scope;schedule_submission, reached only fromRuntimeBackend::schedule, does not. Nesting stays conservative, because a submission inside a wake frame still sees a nonzero depth. A regression test drives the ordinary-spawn case through the production path and fails without the fix.BufferSlicepointed at thenapi_value: confirmed, and wider than reported. The reviewer read it as a defect in the two copy fallbacks. It is older and it is everywhere: all three constructors builtinnerfrombuf, thenapi_valueout-parameter, on the external-success path as well, andcopy_fromhas no fallback at all yet captured aresult_datapointer at line 214 and never used it. A probe comparinginner.as_ptr()againstnapi_get_buffer_infoshowsinnerequal to the v8 handle slot on native Node and equal to the emnapi handle id, literally address 9, on wasm; reading through it returns garbage on both.FromNapiValue for BufferSlicewas always correct, so the constructors disagreed with the reader. Fixing only the fallbacks would have left native, Electron and threaded wasm broken while looking fixed, so all five sites now resolve the pointer the same way the reader does.The prescribed remedy, capturing
result_datafromnapi_create_buffer_copy, was measured and does not work under emnapi: that call allocates a JSArrayBuffer, mallocs a wasm-side mirror forresult_data, and only then copies the bytes into theArrayBuffer, leaving the mirror zero filled.napi_get_buffer_infois what re-syncs the mirror, so it is the only pointer correct on every target. One consequence is documented in the tests: emnapi's mirror is one-way, so a write throughDerefMutnever reaches JS when the bytes are JS-owned. That covers every copied buffer and everyBufferSlicereceived from JS, on both wasm lanes. Read-back is asserted everywhere, because it is the regression being pinned. Write visibility is asserted on native, and on threaded wasm for the two constructors that stay zero-copy there.copy_fromcopies unconditionally on every target, which the tests now encode.Not in this PR
🤖 Generated with Claude Code
https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
Summary by CodeRabbit
New Features
wasmMemorySizeBytes()to report current WebAssembly memory size.Bug Fixes
Tests
Note
High Risk
Changes CurrentThread shutdown, dispatch-failure, and idle-wait semantics plus NAPI buffer ownership on wasm—core concurrency and memory-safety paths tied to real production deadlocks.
Overview
Fixes CurrentThread executor deadlocks and stranded tasks when runnables are rejected during shutdown, terminal host-dispatch failure, or a closing queue—especially on waker stacks (e.g.
futures::Sharedholdingwakers). Rejected work is deferred intoqueue.rejected/rejected_blockingand cancelled only on clean stacks (retire_rejected_work, host turns, delivery completion, shutdown idle wait).scheduleis wrapped in thread-local depth tracking;schedule_submission(firstspawnschedule) can cancel inline when both host deliveries fail. Waker-stack terminal failures get a bounded retirement path (request_rejected_work_retirement, final offer) so work is not dropped under foreign locks andJoinHandles do not hang forever.Separately, threadless WASI wasm no longer uses zero-copy
napi_create_external_bufferviews that break aftermemory.grow;create_external_bufferandBufferSliceconstruction use copy fallbacks andnapi_get_buffer_infofor the live byte pointer.napi_wasi_threadscfg distinguishes threaded WASI from threadless targets. Tests andwasmMemorySizeBytes()cover buffer survival and scheduler interleavings.Reviewed by Cursor Bugbot for commit 82b7ba5. Bugbot is set up for automated code reviews on this repo. Configure here.