Skip to content

refactor(oneshot): remove unbounded waker handoff wait - #138

Merged
tisonkun merged 21 commits into
mainfrom
codex/redesign-oneshot-handoff
Aug 8, 2026
Merged

tisonkun merged 21 commits into
mainfrom
codex/redesign-oneshot-handoff

Conversation

@tisonkun

@tisonkun tisonkun commented Aug 5, 2026 •

Copy link
Copy Markdown
Member

Summary

  • remove the unbounded receiver-side spin while a oneshot sender owns the registered waker
  • preserve the existing single allocation, inline message and waker slots, five state values, and public API
  • make the state, memory-ordering, and cleanup-ownership handoffs explicit without adding a reference count or another synchronization primitive
  • separate the sender and receiver implementations and add focused regression, ownership, and concurrency coverage

Motivation

The original waiting path used this handoff:

  1. the receiver initialized the inline waker and published RECEIVING
  2. the sender changed RECEIVING to AWAKING and took the waker
  3. the sender published MESSAGE or DISCONNECTED
  4. the sender woke the waker it had taken

If Recv::poll or Recv::drop observed AWAKING between steps 2 and 3, it called spin_loop() until the sender published the terminal state. The sender normally completes this short critical section quickly, but that is a latency expectation rather than a progress guarantee: the sender may be descheduled while an async runtime worker spins and waits for that same sender to run.

This is not necessarily a permanent protocol deadlock under a fair scheduler, but a single poll or drop can block for an unbounded time. A runtime-agnostic primitive should not rely on scheduler fairness or a bound on another thread's suspension. The implementation from which this module is derived makes the same assumption in its poll path and drop path.

State and ownership model

This change does not add a state or alter the existing numeric encodings. The names describe the protocol that is already visible in the sender and receiver operations:

State Published invariant
EMPTY no message or waker is published to the other endpoint
RECEIVING the receiver has published an initialized inline waker; either endpoint may atomically claim it
AWAKING the sender exclusively owns the published waker and any message it is preparing to publish
MESSAGE the sender has published an initialized message and no longer accesses the channel
DISCONNECTED no message can subsequently be received; the transition determines which endpoint owns remaining cleanup

The principal transitions are:

receiver registers:             EMPTY -> RECEIVING
send without a waiter:          EMPTY -> MESSAGE
sender drop without a waiter:   EMPTY -> DISCONNECTED
sender observes a waiter:       RECEIVING -> AWAKING -> MESSAGE | DISCONNECTED
receiver reclaims its waker:    RECEIVING -> EMPTY
receiver cancels a handoff:     AWAKING -> DISCONNECTED

DISCONNECTED is also used as the cancellation handoff marker. Once one endpoint obtains exclusive ownership of the message and allocation, the state is no longer observable and has no further meaning.

Internal state and error terminology consistently uses DISCONNECTED. The public is_closed methods remain unchanged for compatibility; #141 tracks aligning those predicate names in a future breaking release.

Non-blocking AWAKING handling

When poll observes AWAKING, the sender owns the previously registered waker and the current poll may carry a different waker. The receiver therefore calls cx.waker().wake_by_ref() and returns Poll::Pending immediately. The sender still publishes the terminal state and wakes the registered waker. A redundant wake is possible only in this contended window, but no invocation of poll waits for sender progress and the latest context remains scheduled.

When Recv::drop observes AWAKING, it attempts AWAKING -> DISCONNECTED and returns after transferring allocation cleanup to the sender. The sender's final swap distinguishes the outcome:

  • replacing AWAKING means the receiver remains responsible for the allocation, so the sender wakes the stored waker
  • replacing receiver-written DISCONNECTED means cancellation transferred cleanup, so the sender drops any accepted message and deallocates the channel

The sender's initial read-modify-write remains the send linearization point: EMPTY -> MESSAGE or RECEIVING -> AWAKING accepts the value, while observing DISCONNECTED returns SendError<T>. If cancellation happens after the contended RECEIVING -> AWAKING transition, send still returns Ok(()); the sender disposes of the already accepted message on the receiver's behalf.

Memory ordering and allocation ownership

The protocol uses release/acquire handoffs only where non-atomic data or allocation ownership crosses endpoints:

  • the receiver publishes the initialized waker with Release; a sender that observes RECEIVING performs a conditional Acquire fence before taking it
  • the sender publishes the initialized message or disconnect with Release; a receiver performs Acquire before accessing the message or reclaiming the allocation
  • receiver cancellation publishes cleanup transfer with Release; the sender performs Acquire only when its final swap observes that transfer

Relaxed operations only select a state-machine branch or perform a receiver-local terminal update; they do not make a message, waker, or allocation available to the other endpoint. No sequentially consistent operation is required. The common sender path remains one release read-modify-write, with Acquire fences paid only on branches that consume receiver-published ownership.

The unsafe ownership mechanics were made explicit at the same time:

  • ManuallyDrop marks consuming endpoint operations that take over destructor responsibility
  • deallocation reconstructs Box<Channel<T>> from the original NonNull, rather than deriving unique allocation ownership from a shared &Channel<T>
  • the reconstructed Box is also the unwind guard when dropping a message whose destructor panics
  • every unsafe channel helper documents its slot initialization, exclusive ownership, synchronization, and provenance requirements

The shared state machine and storage remain in oneshot/mod.rs; endpoint APIs and cleanup paths now live in sender.rs and receiver.rs so each side's ownership transitions can be audited independently.

Why keep the inline design

  • a separate AtomicWaker adds another registration protocol but does not solve channel-allocation lifetime
  • an atomic boxed waker or tagged pointer makes exchange straightforward at the cost of another allocation on the waiting path
  • endpoint reference counting removes the cleanup handoff but adds read-modify-write operations to both endpoints
  • bounded spinning still relies on an arbitrary budget and regressed the uncontended benchmark in the local prototype

Using the existing AWAKING ownership phase keeps the original layout and hot paths while removing the progress dependency from receiver operations.

Regression coverage

The two central regression tests pause a synthetic sender immediately after RECEIVING -> AWAKING. They verify that:

  • a repoll returns Pending before the sender resumes and wakes the current context
  • receiver drop returns before the sender resumes and transfers cleanup
  • the stored waker, accepted message, and allocation each retain exactly one owner across both races

The remaining tests cover send/receive ordering, disconnect behavior, waker replacement, SendError<T> ownership, exactly-once message destruction, and concurrent poll/try_recv completion. Test support uses the standard Wake trait rather than a hand-written unsafe RawWaker.

Performance

Divan was run with --sample-size 20000 --sample-count 2000. Each value is the mean of three alternating run medians against main at 7609cac; Linux arm64 runs were pinned to one VM vCPU.

Platform Scenario main This PR Change
Apple M4, macOS arm64 poll_before_send 21.25 ns 20.36 ns -4.2%
Apple M4, macOS arm64 send_before_poll 19.12 ns 18.63 ns -2.6%
Apple M4, Linux arm64 VM poll_before_send 10.57 ns 10.64 ns +0.6%
Apple M4, Linux arm64 VM send_before_poll 8.217 ns 8.288 ns +0.9%

The Linux differences are below 1%. The macOS process-level results varied more between runs, so the negative values are evidence against a regression rather than a claimed stable speedup. The selected protocol remains within the main performance envelope; the earlier bounded-spin prototype showed a repeatable double-digit Linux regression and was discarded.

Verification

  • cargo x lint
  • cargo test --workspace --all-features
  • cargo +1.85.0 test -p mea oneshot -- --test-threads=1
  • cargo +nightly miri test -p mea owns_waker --all-features
  • repeated alternating benchmarks on macOS arm64 and a CPU-pinned Linux arm64 VM
  • CI on Linux, macOS, and Windows with stable Rust and MSRV 1.85

Transfer cancellation cleanup through the existing handoff state instead of adding endpoint reference counts. Keep poll and drop bounded, preserve the latest-waker contract, and use conditional acquire fences on sender slow paths.
@tisonkun
tisonkun marked this pull request as draft August 5, 2026 02:04
@tisonkun tisonkun changed the title fix(oneshot): remove unbounded waker handoff wait refactor(oneshot): remove unbounded waker handoff wait Aug 6, 2026
@tisonkun
tisonkun marked this pull request as ready for review August 6, 2026 10:21
@tisonkun
tisonkun requested a lite review from Copilot August 6, 2026 10:21

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR refactors the mea::oneshot channel’s receiver-side polling and drop behavior to remove an unbounded busy-wait during waker handoff, by treating the intermediate “sender owns waker” phase as a short-lived ownership invariant (CLAIMED) rather than something the receiver waits to leave.

Changes:

  • Reworked oneshot state machine naming (REGISTERED/CLAIMED/READY/CLOSED) and updated sender/receiver protocols to avoid unbounded spinning in Recv::poll and Recv::drop.
  • Added helper routines (take_waker_and_publish, schedule_repoll, discard_sent_message) to make ownership transfer and cleanup explicit.
  • Added deterministic regression tests covering the two previously-blocking interleavings when the sender is paused after claiming the waker.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.

File Description
mea/src/oneshot/mod.rs Refactors the oneshot state machine and handoff protocol to eliminate receiver-side unbounded waiting while preserving layout/fast paths.
mea/src/oneshot/tests.rs Adds regression tests for the “sender paused while owning waker” interleavings in poll and drop paths.
Suppressed comments (1)

mea/src/oneshot/tests.rs:412

  • Same as in poll_returns_while_sender_owns_waker: using Ordering::AcqRel for the synthetic CLAIMED transition is stronger than the production sender ordering and can hide missing-acquire regressions. Align the synthetic sender to Release + explicit Acquire fence immediately before taking the waker/publishing the terminal state.
    // Pause the synthetic sender in CLAIMED immediately after it claims the stored waker.
    assert_eq!(
        channel.state.fetch_add(1, Ordering::AcqRel),
        super::REGISTERED
    );

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread mea/src/oneshot/tests.rs Resolved
Comment thread mea/src/oneshot/mod.rs Resolved
Comment thread mea/src/oneshot/mod.rs Resolved
@tisonkun
tisonkun merged commit 78e5e3c into main Aug 8, 2026
9 checks passed
@tisonkun
tisonkun deleted the codex/redesign-oneshot-handoff branch August 8, 2026 07:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants