Repository navigation
build: enhance the build pipeline - #9
Merged
Merged
Conversation
Brooooooklyn
force-pushed
the
build-enhance
branch
2 times, most recently
from
February 18, 2020 15:50
90ad01e to
49f6cfc
Compare
Brooooooklyn
force-pushed
the
build-enhance
branch
7 times, most recently
from
February 19, 2020 08:29
a23a190 to
bcad9dd
Compare
Brooooooklyn
force-pushed
the
build-enhance
branch
from
February 19, 2020 09:46
bcad9dd to
48c9a89
Compare
Brooooooklyn
added a commit
that referenced
this pull request
Sep 9, 2026
… 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
Brooooooklyn
added a commit
that referenced
this pull request
Sep 9, 2026
…etachment (#3489) * fix(async-runtime): never drop a rejected CurrentThread runnable inline 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 * fix(async-runtime): defer closed-queue CurrentThread rejections to the 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 * fix(async-runtime): never run the CurrentThread cancellation sweep on 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 * fix(async-runtime): reopen the CurrentThread executor at once after a 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 * docs(async-runtime): state the CurrentThreadTaskDriver::dispatch blocking 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 * test(async-runtime): pin MultiThread closed-queue rejection does not 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 * fix(napi): copy Buffers on threadless wasm so memory growth cannot detach 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 * test(examples): refresh the type def snapshot for wasmMemorySizeBytes 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 * fix(async-runtime): give an ordinary CurrentThread spawn its own continuation `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 * fix(napi): point BufferSlice at the buffer data instead of the napi_value `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 521ef58f (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 * test(examples): skip the BufferSlice DerefMut assertion on WASI The three `BufferSlice::* points at the buffer data` tests added in 1b5fd9b7 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 1b5fd9b7 - 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 1b5fd9b7 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 * fix(napi): only copy Buffers where wasm memory is not shared a0f1a7ee 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: d83b9e10 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 * fix(async-runtime): give a CurrentThread wake's terminal failure its 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 * fix(async-runtime): hand a nested CurrentThread retirement request back 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 * perf(async-runtime): bound the CurrentThread retirement loop on a waker'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 * fix(async-runtime): leave a CurrentThread retirement offer the budget 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 * fix(async-runtime): leave a continuation when the host services the final 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 --------- Co-authored-by: Claude Fable 5.1 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
No description provided.