Repository navigation
refactor(oneshot): remove unbounded waker handoff wait - #138
Merged
Merged
Conversation
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
marked this pull request as draft
August 5, 2026 02:04
tisonkun
marked this pull request as ready for review
August 6, 2026 10:21
There was a problem hiding this comment.
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 inRecv::pollandRecv::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: usingOrdering::AcqRelfor the synthetic CLAIMED transition is stronger than the production sender ordering and can hide missing-acquire regressions. Align the synthetic sender toRelease+ explicitAcquirefence 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.
Signed-off-by: tison <[email protected]>
Signed-off-by: tison <[email protected]>
Signed-off-by: tison <[email protected]>
Signed-off-by: tison <[email protected]>
Signed-off-by: tison <[email protected]>
Signed-off-by: tison <[email protected]>
Signed-off-by: tison <[email protected]>
Signed-off-by: tison <[email protected]>
Signed-off-by: tison <[email protected]>
Signed-off-by: tison <[email protected]>
Signed-off-by: tison <[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.
Summary
Motivation
The original waiting path used this handoff:
RECEIVINGRECEIVINGtoAWAKINGand took the wakerMESSAGEorDISCONNECTEDIf
Recv::pollorRecv::dropobservedAWAKINGbetween steps 2 and 3, it calledspin_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
pollordropcan 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:
EMPTYRECEIVINGAWAKINGMESSAGEDISCONNECTEDThe principal transitions are:
DISCONNECTEDis 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 publicis_closedmethods remain unchanged for compatibility; #141 tracks aligning those predicate names in a future breaking release.Non-blocking
AWAKINGhandlingWhen
pollobservesAWAKING, the sender owns the previously registered waker and the current poll may carry a different waker. The receiver therefore callscx.waker().wake_by_ref()and returnsPoll::Pendingimmediately. 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 ofpollwaits for sender progress and the latest context remains scheduled.When
Recv::dropobservesAWAKING, it attemptsAWAKING -> DISCONNECTEDand returns after transferring allocation cleanup to the sender. The sender's final swap distinguishes the outcome:AWAKINGmeans the receiver remains responsible for the allocation, so the sender wakes the stored wakerDISCONNECTEDmeans cancellation transferred cleanup, so the sender drops any accepted message and deallocates the channelThe sender's initial read-modify-write remains the send linearization point:
EMPTY -> MESSAGEorRECEIVING -> AWAKINGaccepts the value, while observingDISCONNECTEDreturnsSendError<T>. If cancellation happens after the contendedRECEIVING -> AWAKINGtransition,sendstill returnsOk(()); 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:
RECEIVINGperforms a conditional Acquire fence before taking itRelaxed 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:
ManuallyDropmarks consuming endpoint operations that take over destructor responsibilityBox<Channel<T>>from the originalNonNull, rather than deriving unique allocation ownership from a shared&Channel<T>Boxis also the unwind guard when dropping a message whose destructor panicsThe shared state machine and storage remain in
oneshot/mod.rs; endpoint APIs and cleanup paths now live insender.rsandreceiver.rsso each side's ownership transitions can be audited independently.Why keep the inline design
AtomicWakeradds another registration protocol but does not solve channel-allocation lifetimeUsing the existing
AWAKINGownership 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:Pendingbefore the sender resumes and wakes the current contextThe remaining tests cover send/receive ordering, disconnect behavior, waker replacement,
SendError<T>ownership, exactly-once message destruction, and concurrentpoll/try_recvcompletion. Test support uses the standardWaketrait rather than a hand-written unsafeRawWaker.Performance
Divan was run with
--sample-size 20000 --sample-count 2000. Each value is the mean of three alternating run medians againstmainat7609cac; Linux arm64 runs were pinned to one VM vCPU.mainpoll_before_sendsend_before_pollpoll_before_sendsend_before_pollThe 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
mainperformance envelope; the earlier bounded-spin prototype showed a repeatable double-digit Linux regression and was discarded.Verification
cargo x lintcargo test --workspace --all-featurescargo +1.85.0 test -p mea oneshot -- --test-threads=1cargo +nightly miri test -p mea owns_waker --all-features