Skip to content

refactor(mpsc): replace mutex-backed bounded queue with preallocated slot ring - #465

Merged
tisonkun merged 7 commits into
apache:mainfrom
biaoma-ty:perf/mpsc-bounded-slot-ring
Nov 24, 2026
Merged

tisonkun merged 7 commits into
apache:mainfrom
biaoma-ty:perf/mpsc-bounded-slot-ring

Conversation

@biaoma-ty

@biaoma-ty biaoma-ty commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Improve mpsc::bounded inline-message throughput and shrink endpoint futures:

  1. Preallocated slot ring and monotonic capacity accounting (mpsc::bounded::queue): Replace the mutex-guarded VecDeque<T> with a preallocated raw slot ring, 62-bit monotonic producer acquisition and receiver release counters (acquired, cached_rx_rel, and rx_state), and a ticketed Tail cursor (AtomicU64 with a Mutex<u64> fallback on targets without 64-bit atomics) so uncontended send, try_send, reserve, try_reserve, Permit::send, recv, and try_recv execute in two producer atomics without locking and copy payloads concurrently across slots.
  2. Compact Unpin endpoint futures (SendValue, Reserve, Recv): Replace the outer async fn and poll_fn wrappers on BoundedSender::send, BoundedSender::reserve, and BoundedReceiver::recv with explicit Unpin impl Future types staging unsent payloads in MaybeUninit<T>, so inline payloads move once from the caller frame into the ring slot instead of staging twice across generator frames.
  3. Unit, integration, trait, and changelog coverage: Cover non-power-of-two capacities, FIFO backpressure across many queued waiters, non-barging handoff when waiters enqueue concurrently with try_recv or Permit::drop, non-spinning Recv::poll suspension and isolated Condvar parking on claimed slots, linearizable close without spurious Full errors, poll-after-completion panics, ZST usize::MAX accounting and destructor counts, immediate ring deallocation on receiver drop, Send / Unpin auto-trait bounds, and two-phase publication documentation, and update CHANGELOG.md.

Closes #401.
Part of #396.

Design Notes

  • Slot layout, lazy zero-paged initialization, and readiness handoff: Slots are allocated once via alloc::alloc_zeroed requesting align_of::<T>() with slot.align - align_of::<T>() slack so Miri's symbolic alignment check proves every T access is aligned while align_of::<T>() <= MIN_ALIGN buffers delegate directly to OS zero-page calloc. Each slot places state: AtomicU8 (SLOT_EMPTY, SLOT_READY, SLOT_RX_WAITING) at byte offset 0 and payload storage at align_of::<T>().max(16) with 128-byte slot stride alignment when size_of::<T>() >= 64 (128 B stride for 64..=112 B values, 1,152 B for [u8; 1024]). Tail::claim uses AcqRel ordering so that even when an earlier Permit pauses before claiming a ticket while later permits cycle the ring by capacity, the consumer's SLOT_EMPTY release and rx_state release remain ordered before the reused slot's write. If async Recv::poll observes head < tail before the head producer finishes copying, it registers a ticket-scoped recv_waker (SLOT_RX_WAITING) and returns Poll::Pending without spinning or blocking the executor thread; synchronous try_recv and close draining wait on a private Mutex<bool> + Condvar waker (SlotPark) without touching the caller thread's unpark token.
  • Two-step publication, linearizable monotonic capacity accounting, and indivisible FIFO handoff: Sending follows the same two-step structure as reserve() + Permit::send(): producers first advance the 62-bit monotonic acquired counter while acquired - cached_rx_rel < capacity (refreshing cached_rx_rel from the receiver's monotonic rx_state counter only when the cached window is exhausted) and then claim the next queue position via tail. RX_WAITERS_BIT in rx_state and ACQ_WAITERS_BIT in acquired guard compare_exchange_weak releases in release_from_receiver and Permit::drop, making the check for no queued waiters and the publication of freed capacity one indivisible transition so concurrent try_send and try_reserve callers cannot barge ahead of queued senders.
  • Target portability (not(target_has_atomic = "64")): On targets with 64-bit atomics, Atomic64 wraps AtomicU64; targets without 64-bit atomics retain the same protocol through a Mutex<u64> wrapper without target restrictions.
  • Linearizable disconnection and immediate ring reclamation: Shared::drop_receiver seals ACQ_CLOSED_BIT in acquired and CLOSED_BIT in tail before storing rx_alive = false so concurrent sends on a non-full channel never transiently observe Full, wakes queued senders outside the lock, drains buffered values via an unwind-safe DrainGuard (skipping per-slot iteration for !Drop payloads once all senders have disconnected), and immediately deallocates the SlotRing buffer even if disconnected BoundedSender handles remain alive.
  • Compact Unpin futures: SendValue<'a, T>, Reserve<'a, T>, and Recv<'a, T> store waiter state as arena-indexed Option<WaiterId> values, stage pending values in MaybeUninit<T>, and encode completion in their Option endpoint reference niche, shrinking BoundedSender<[u8; 1024]>::send from 2,072 B to 1,040 B (24 B for usize), reserve from 32 B to 16 B, and recv from 16 B to 8 B on 64-bit targets while remaining Unpin.

Benchmarks

5-run medians (cargo x bench --bench ecosystem -- mpsc/bounded --repeat 5 and mpsc/reservation, lower is faster):

Scenario Fixed rounds Asyncband (this PR) Tokio async-channel flume
mpsc/bounded/tasks-4p1c-cap64-4w-inline1k 26 83 ms 96 ms 120 ms 271 ms
mpsc/bounded/ready-roundtrip-inline1k 1,000,000 107 ms 155 ms 140 ms 128 ms
mpsc/bounded/tasks-4p1c-cap64-4w-boxed1k 26 59 ms 112 ms 115 ms 135 ms
mpsc/bounded/ready-roundtrip-boxed1k 1,000,000 49 ms 67 ms 75 ms 61 ms
mpsc/bounded/try-roundtrip 30,000,000 139 ms 348 ms 796 ms 344 ms
mpsc/bounded/ready-roundtrip 24,000,000 123 ms 508 ms 733 ms 357 ms
mpsc/bounded/threads-4p1c-cap64 89 158 ms 201 ms 302 ms 325 ms
mpsc/bounded/tasks-1p1c-cap64-4w 896 225 ms 518 ms 778 ms 381 ms
mpsc/bounded/tasks-4p1c-cap64-4w 320 256 ms 547 ms 578 ms 431 ms
mpsc/bounded/tasks-1p1c-cap1024-4w 430 75 ms 350 ms 380 ms 215 ms
mpsc/bounded/tasks-4p1c-cap1024-4w 320 255 ms 552 ms 383 ms 382 ms
mpsc/bounded/tasks-1p1c-cap64-current 1,200 180 ms 496 ms 665 ms 372 ms
mpsc/bounded/tasks-1p1c-cap1024-current 1,200 161 ms 510 ms 642 ms 337 ms
mpsc/bounded/tasks-4p1c-cap64-current 1,100 188 ms 487 ms 666 ms 381 ms
mpsc/bounded/tasks-4p1c-cap1-4w 160 337 ms 364 ms 1,453 ms 1,058 ms
mpsc/bounded/external-receiver-1p1c-cap64-4w 128 271 ms 279 ms 259 ms 260 ms
mpsc/reservation/reserve-publish-receive 18,000,000 87 ms 326 ms - -
mpsc/reservation/tasks-4p1c-cap1-4w 170 331 ms 369 ms - -

Reproduce with:

cargo x bench --bench ecosystem -- mpsc/bounded --repeat 5
cargo x bench --bench ecosystem -- mpsc/reservation --repeat 5
cargo x bench --bench primitives -- mpsc::bounded --repeat 5

Validation

  • cargo +nightly fmt --all -- --check
  • cargo x lint
  • cargo x check
  • cargo x test
  • cargo +1.86.0 check -p asyncband --all-features
  • MIRIFLAGS="-Zmiri-strict-provenance -Zmiri-symbolic-alignment-check -Zmiri-many-seeds=0..4" cargo +nightly miri test --package asyncband --lib --all-features mpsc
  • MIRIFLAGS="-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

@biaoma-ty
biaoma-ty force-pushed the perf/mpsc-bounded-slot-ring branch from d4d7f56 to f55f7db Compare November 24, 2026 03:50
… 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
biaoma-ty force-pushed the perf/mpsc-bounded-slot-ring branch from f55f7db to ccd1b65 Compare November 24, 2026 04:36
@biaoma-ty

biaoma-ty commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

time to run /learn for me

…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
tisonkun force-pushed the perf/mpsc-bounded-slot-ring branch from 7c97197 to a985e90 Compare November 24, 2026 12:55
@tisonkun

Copy link
Copy Markdown
Member

Bounded mpsc Benchmark Report (main vs This PR vs Best Ecosystem Peer)

Measured back-to-back on aarch64-apple-darwin (rustc 1.101.0-nightly (8006091eb 2026-10-17), --repeat 5, median elapsed ms, lower is faster) comparing main (1cadff0), this PR (a985e90), and the fastest external implementation per scenario among tokio, flume, and async-channel.

1. Ecosystem Scenarios (mpsc/bounded/* and mpsc/reservation/*)

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 bounded mpsc benchmarks improve (1.02x to 3.69x faster), 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 (tokio on contended inline/boxed/OS-thread/cap-1 workloads, flume on scalar task and roundtrip workloads) in 17 of 18 ecosystem scenarios (1.08x to 3.75x faster), and sits within 4% (271 ms vs async-channel 259 ms) on external-receiver-1p1c-cap64-4w, which is dominated by cross-thread parker wakeups outside the runtime.

@tisonkun tisonkun changed the title perf(mpsc): replace mutex-backed bounded queue with preallocated slot ring refactor(mpsc): replace mutex-backed bounded queue with preallocated slot ring Nov 24, 2026
@tisonkun
tisonkun merged commit 1c5584d into apache:main Nov 24, 2026
9 checks passed
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.

Improve bounded MPSC throughput for inline 1 KiB messages

2 participants