Repository navigation
refactor(mpsc): replace mutex-backed bounded queue with preallocated slot ring - #465
Merged
Merged
Conversation
biaoma-ty
force-pushed
the
perf/mpsc-bounded-slot-ring
branch
from
November 24, 2026 03:50
d4d7f56 to
f55f7db
Compare
… ring `mpsc::bounded` previously stored buffered messages, permit counts, endpoint liveness, and waiter queues behind one `Mutex<State<T>>` backed by a `VecDeque<T>`, serializing concurrent producers and copying inline payloads while holding the channel lock. Move bounded channel internals to `mpsc::bounded::queue` backed by a preallocated slot ring and atomic permit accounting: - Preallocate `buffer` slots once via `alloc_zeroed` with `ready: AtomicBool` at byte offset `0`, 128-byte payload alignment for payloads `>= 64 B`, and cache-line index swizzling on small power-of-two rings (`>= 64`), paired with a ticketed `Tail` cursor (`AtomicU64` with a `Mutex<u64>` fallback when `not(target_has_atomic = "64")`). - Track free capacity in `permits: AtomicUsize` (using signed `fetch_sub` up to `isize::MAX >> 1` and CAS for larger ZST capacities up to `usize::MAX`), batch receiver-freed credits in `rx_credit` (`16..=32`) with an immediate high-bit flush when senders are queued, and coordinate FIFO wait-queue grants via a `SeqCst` Dekker handshake and `WakerBatch` wakeups outside `control`. - Seal `tail`, clear `rx_credit`, poison `permits`, and store `rx_alive = false` under `control` in `Shared::drop_receiver` before waking queued senders and draining buffered slots outside the lock via `DrainGuard`.
…staging `BoundedSender::send`, `BoundedSender::reserve`, and `BoundedReceiver::recv` previously wrapped their operations in `async fn` and `poll_fn` state machines, staging inline payloads across outer and inner generator frames (inflating `BoundedSender<[u8; 1024]>::send` to `2,072 B`) and copying uninitialized `Result` union bytes on uncontended sends. Replace the `async fn` wrappers with explicit `SendValue`, `Reserve`, and `Recv` `impl Future` types: - Move caller payloads directly from `ManuallyDrop<T>` inside `SendValue` into the claimed ring slot, and encode completion in the `Option` endpoint reference niche (`1,040 B` for `[u8; 1024]`, `24 B` for `usize`, `16 B` for `reserve`, and `8 B` for `recv` on 64-bit targets). - Teach LLVM via `hint::assert_unchecked` that `SendValue::shared` remains `None` across `publish_from_ptr` on the `Ok(())` path so post-await drops fold away without extra stack copies. - Preserve `!Unpin` SemVer parity with `PhantomPinned` and verify it in `compile_fail` doctests alongside `# Panics` documentation for polling after completion.
Expand integration and trait coverage for the bounded slot ring and explicit endpoint futures: - Test non-power-of-two and swizzled capacities, single-slot receiver credit bounds, FIFO grants past `WakerBatch`'s 32-waker inline capacity, exact ZST destructor counts across send/receive/drop/disconnect paths, and poll-after-completion panics on `send`, `reserve`, and `recv` in `mpsc_test`. - Assert `Send` on `mpsc` bounded and unbounded futures over `Send + !Sync` (`Cell<u8>`) payloads in `traits_test`. - Record the `mpsc::bounded` future size and throughput improvements in `CHANGELOG.md`.
biaoma-ty
force-pushed
the
perf/mpsc-bounded-slot-ring
branch
from
November 24, 2026 04:36
f55f7db to
ccd1b65
Compare
Contributor
Author
|
time to run |
…rizable Replace the signed dual-mode `permits` counter and two-step `rx_credit` drain with a monotonic `(acquired, cached_rx_rel, rx_state)` triple backed by a unified `Atomic64` wrapper (`AtomicU64` on 64-bit targets, `Mutex<u64>` fallback where 64-bit atomics are unavailable). Guard `acquired`, `rx_state`, and `tail` against overflowing into their high status bits. Seal `ACQ_CLOSED_BIT` directly in `acquired` before `tail.close()` during `BoundedReceiver::drop` so concurrent non-blocking sends on a non-full channel never transiently observe `TrySendError::Full` during teardown. Use indivisible `compare_exchange_weak` loops in `release_from_receiver` and `release_capacity` with `RX_WAITERS_BIT` and `ACQ_WAITERS_BIT` so released capacity is handed directly to `send_waiters.grant_one()` without exposing free slots to concurrent `try_send` bargers, removing `reclaim_for_waiters` and `WakerBatch`. Signed-off-by: tison <[email protected]>
Replace the binary `AtomicBool` slot readiness flag and `yield_now` spin loop with a three-state `AtomicU8` (`SLOT_EMPTY`, `SLOT_READY`, `SLOT_RX_WAITING`). When a producer has claimed the head ticket via `tail` but has not yet finished copying its payload into the slot, `Recv::poll` now arms `SLOT_RX_WAITING` with `recv_slot_ticket` and returns `Poll::Pending` instead of spinning on the executor thread. Synchronous callers (`BoundedReceiver::try_recv` and `DrainGuard::drain`) wait on a private `Mutex<bool>` + `Condvar` parker so an outer caller's `std::thread::park` token is never consumed. Signed-off-by: tison <[email protected]>
… close Request `align_of::<T>()` from `alloc::alloc_zeroed` and manually offset any additional 128-byte cache-line padding so standard-aligned payloads stay on OS lazy zero-page `calloc` instead of eagerly zero-faulting large rings, while preserving symbolic alignment under Miri. Compact `>= 64 B` slot headers from 128 bytes to `max(16, align_of::<T>())` so `64..=112 B` payloads occupy a single 128-byte cache line instead of two, and remove small-slot index bit-swizzling. Skip destructor traversal in `DrainGuard::drain` for `!needs_drop::<T>()` once no senders remain, and deallocate the slot ring immediately when `BoundedReceiver` finishes draining rather than retaining the buffer until every surviving `BoundedSender` drops. Signed-off-by: tison <[email protected]>
…ment two-phase contract Store staged values in `SendValue`, `BoundedSender::try_send`, and `Permit::send` inside `MaybeUninit<T>` rather than `ManuallyDrop<T>` so moving a completed `SendValue` after ownership moves into the ring remains sound for `Box<T>` (including on pre-1.96 toolchains) and `&mut T`. Implement `Unpin` for `SendValue`, `Reserve`, and `Recv`, replacing `PhantomPinned`, `Pin::get_unchecked_mut`, and `hint::assert_unchecked` with safe `Pin::get_mut` and explicit state clearing. Document the two-step capacity-then-ticket publication contract across `bounded`, `BoundedSender`, `BoundedReceiver`, and `CHANGELOG.md`. Signed-off-by: tison <[email protected]>
tisonkun
force-pushed
the
perf/mpsc-bounded-slot-ring
branch
from
November 24, 2026 12:55
7c97197 to
a985e90
Compare
Member
Bounded
|
| Scenario | Asyncband (main) |
Asyncband (this PR) | PR vs main |
Best ecosystem peer | PR vs best peer |
|---|---|---|---|---|---|
mpsc/bounded/try-roundtrip |
308 ms | 139 ms | 2.22x | flume (344 ms) |
2.47x |
mpsc/bounded/ready-roundtrip |
292 ms | 123 ms | 2.37x | flume (357 ms) |
2.90x |
mpsc/bounded/ready-roundtrip-inline1k |
149 ms | 107 ms | 1.39x | flume (128 ms) |
1.20x |
mpsc/bounded/ready-roundtrip-boxed1k |
61 ms | 49 ms | 1.24x | flume (61 ms) |
1.24x |
mpsc/bounded/tasks-4p1c-cap64-4w-inline1k |
306 ms | 83 ms | 3.69x | tokio (96 ms) |
1.16x |
mpsc/bounded/tasks-4p1c-cap64-4w-boxed1k |
115 ms | 59 ms | 1.95x | tokio (112 ms) |
1.90x |
mpsc/bounded/threads-4p1c-cap64 |
293 ms | 158 ms | 1.85x | tokio (201 ms) |
1.27x |
mpsc/bounded/tasks-1p1c-cap64-4w |
301 ms | 225 ms | 1.34x | flume (381 ms) |
1.69x |
mpsc/bounded/tasks-4p1c-cap64-4w |
299 ms | 256 ms | 1.17x | flume (431 ms) |
1.68x |
mpsc/bounded/tasks-1p1c-cap1024-4w |
184 ms | 75 ms | 2.45x | flume (215 ms) |
2.87x |
mpsc/bounded/tasks-4p1c-cap1024-4w |
297 ms | 255 ms | 1.16x | flume (382 ms) |
1.50x |
mpsc/bounded/tasks-1p1c-cap64-current |
286 ms | 180 ms | 1.59x | flume (372 ms) |
2.07x |
mpsc/bounded/tasks-1p1c-cap1024-current |
264 ms | 161 ms | 1.64x | flume (337 ms) |
2.09x |
mpsc/bounded/tasks-4p1c-cap64-current |
279 ms | 188 ms | 1.48x | flume (381 ms) |
2.03x |
mpsc/bounded/tasks-4p1c-cap1-4w |
366 ms | 337 ms | 1.09x | tokio (364 ms) |
1.08x |
mpsc/bounded/external-receiver-1p1c-cap64-4w |
279 ms | 271 ms | 1.03x | async-channel (259 ms) |
0.96x |
mpsc/reservation/reserve-publish-receive |
280 ms | 87 ms | 3.22x | tokio (326 ms) |
3.75x |
mpsc/reservation/tasks-4p1c-cap1-4w |
338 ms | 331 ms | 1.02x | tokio (369 ms) |
1.11x |
Note: Only tokio provides explicit capacity reservations (reserve / Permit) for the mpsc/reservation/* suite.
2. Internal Backpressure & Cancellation Microbenchmarks (primitives::mpsc::bounded::*)
| Scenario | Asyncband (main) |
Asyncband (this PR) | PR vs main |
|---|---|---|---|
primitives::mpsc::bounded::drain_backpressured_senders/1 |
323 ms | 260 ms | 1.24x |
primitives::mpsc::bounded::drain_backpressured_senders/4 |
261 ms | 214 ms | 1.22x |
primitives::mpsc::bounded::drain_backpressured_senders/16 |
227 ms | 187 ms | 1.21x |
primitives::mpsc::bounded::cancel_backpressured_senders/1 |
429 ms | 364 ms | 1.18x |
primitives::mpsc::bounded::cancel_backpressured_senders/4 |
308 ms | 273 ms | 1.13x |
primitives::mpsc::bounded::cancel_backpressured_senders/16 |
273 ms | 243 ms | 1.12x |
Takeaways
- vs
main: All 24 boundedmpscbenchmarks improve (1.02xto3.69xfaster), led by multi-producer inline 1 KiB transfers (306 ms -> 83 ms,3.69x), permit reservation roundtrips (280 ms -> 87 ms,3.22x), larger-buffer task pipelines (184 ms -> 75 ms,2.45x), and uncontended roundtrips (292 ms -> 123 ms,2.37x). - vs best ecosystem peer: Asyncband leads the fastest external crate (
tokioon contended inline/boxed/OS-thread/cap-1 workloads,flumeon scalar task and roundtrip workloads) in 17 of 18 ecosystem scenarios (1.08xto3.75xfaster), and sits within4%(271 msvsasync-channel259 ms) onexternal-receiver-1p1c-cap64-4w, which is dominated by cross-thread parker wakeups outside the runtime.
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
Improve
mpsc::boundedinline-message throughput and shrink endpoint futures:mpsc::bounded::queue): Replace the mutex-guardedVecDeque<T>with a preallocated raw slot ring, 62-bit monotonic producer acquisition and receiver release counters (acquired,cached_rx_rel, andrx_state), and a ticketedTailcursor (AtomicU64with aMutex<u64>fallback on targets without 64-bit atomics) so uncontendedsend,try_send,reserve,try_reserve,Permit::send,recv, andtry_recvexecute in two producer atomics without locking and copy payloads concurrently across slots.Unpinendpoint futures (SendValue,Reserve,Recv): Replace the outerasync fnandpoll_fnwrappers onBoundedSender::send,BoundedSender::reserve, andBoundedReceiver::recvwith explicitUnpinimpl Futuretypes staging unsent payloads inMaybeUninit<T>, so inline payloads move once from the caller frame into the ring slot instead of staging twice across generator frames.try_recvorPermit::drop, non-spinningRecv::pollsuspension and isolatedCondvarparking on claimed slots, linearizable close without spuriousFullerrors, poll-after-completion panics, ZSTusize::MAXaccounting and destructor counts, immediate ring deallocation on receiver drop,Send/Unpinauto-trait bounds, and two-phase publication documentation, and updateCHANGELOG.md.Closes #401.
Part of #396.
Design Notes
alloc::alloc_zeroedrequestingalign_of::<T>()withslot.align - align_of::<T>()slack so Miri's symbolic alignment check proves everyTaccess is aligned whilealign_of::<T>() <= MIN_ALIGNbuffers delegate directly to OS zero-pagecalloc. Each slot placesstate: AtomicU8(SLOT_EMPTY,SLOT_READY,SLOT_RX_WAITING) at byte offset0and payload storage atalign_of::<T>().max(16)with 128-byte slot stride alignment whensize_of::<T>() >= 64(128 Bstride for64..=112 Bvalues,1,152 Bfor[u8; 1024]).Tail::claimusesAcqRelordering so that even when an earlierPermitpauses before claiming a ticket while later permits cycle the ring bycapacity, the consumer'sSLOT_EMPTYrelease andrx_staterelease remain ordered before the reused slot's write. If asyncRecv::pollobserveshead < tailbefore the head producer finishes copying, it registers a ticket-scopedrecv_waker(SLOT_RX_WAITING) and returnsPoll::Pendingwithout spinning or blocking the executor thread; synchronoustry_recvand close draining wait on a privateMutex<bool>+Condvarwaker (SlotPark) without touching the caller thread's unpark token.reserve()+Permit::send(): producers first advance the 62-bit monotonicacquiredcounter whileacquired - cached_rx_rel < capacity(refreshingcached_rx_relfrom the receiver's monotonicrx_statecounter only when the cached window is exhausted) and then claim the next queue position viatail.RX_WAITERS_BITinrx_stateandACQ_WAITERS_BITinacquiredguardcompare_exchange_weakreleases inrelease_from_receiverandPermit::drop, making the check for no queued waiters and the publication of freed capacity one indivisible transition so concurrenttry_sendandtry_reservecallers cannot barge ahead of queued senders.not(target_has_atomic = "64")): On targets with 64-bit atomics,Atomic64wrapsAtomicU64; targets without 64-bit atomics retain the same protocol through aMutex<u64>wrapper without target restrictions.Shared::drop_receiversealsACQ_CLOSED_BITinacquiredandCLOSED_BITintailbefore storingrx_alive = falseso concurrent sends on a non-full channel never transiently observeFull, wakes queued senders outside the lock, drains buffered values via an unwind-safeDrainGuard(skipping per-slot iteration for!Droppayloads once all senders have disconnected), and immediately deallocates theSlotRingbuffer even if disconnectedBoundedSenderhandles remain alive.Unpinfutures:SendValue<'a, T>,Reserve<'a, T>, andRecv<'a, T>store waiter state as arena-indexedOption<WaiterId>values, stage pending values inMaybeUninit<T>, and encode completion in theirOptionendpoint reference niche, shrinkingBoundedSender<[u8; 1024]>::sendfrom2,072 Bto1,040 B(24 Bforusize),reservefrom32 Bto16 B, andrecvfrom16 Bto8 Bon 64-bit targets while remainingUnpin.Benchmarks
5-run medians (
cargo x bench --bench ecosystem -- mpsc/bounded --repeat 5andmpsc/reservation, lower is faster):async-channelflumempsc/bounded/tasks-4p1c-cap64-4w-inline1kmpsc/bounded/ready-roundtrip-inline1kmpsc/bounded/tasks-4p1c-cap64-4w-boxed1kmpsc/bounded/ready-roundtrip-boxed1kmpsc/bounded/try-roundtripmpsc/bounded/ready-roundtripmpsc/bounded/threads-4p1c-cap64mpsc/bounded/tasks-1p1c-cap64-4wmpsc/bounded/tasks-4p1c-cap64-4wmpsc/bounded/tasks-1p1c-cap1024-4wmpsc/bounded/tasks-4p1c-cap1024-4wmpsc/bounded/tasks-1p1c-cap64-currentmpsc/bounded/tasks-1p1c-cap1024-currentmpsc/bounded/tasks-4p1c-cap64-currentmpsc/bounded/tasks-4p1c-cap1-4wmpsc/bounded/external-receiver-1p1c-cap64-4wmpsc/reservation/reserve-publish-receivempsc/reservation/tasks-4p1c-cap1-4wReproduce with:
Validation
cargo +nightly fmt --all -- --checkcargo x lintcargo x checkcargo x testcargo +1.86.0 check -p asyncband --all-featuresMIRIFLAGS="-Zmiri-strict-provenance -Zmiri-symbolic-alignment-check -Zmiri-many-seeds=0..4" cargo +nightly miri test --package asyncband --lib --all-features mpscMIRIFLAGS="-Zmiri-strict-provenance -Zmiri-symbolic-alignment-check -Zmiri-many-seeds=0..4" cargo +nightly miri test --package tests-integration --test mpsc_test --test traits_test