Repository navigation
perf(broadcast): replace mutex-backed unbounded backlog with segment buffers - #469
Merged
tisonkun merged 6 commits intoNov 24, 2026
Merged
Conversation
…buffers Replace the single-mutex VecDeque backlog and Arena cursor table in broadcast::mpmc::unbounded with reference-counted segment buffers (an 8-slot inline segment plus pooled 256-slot heap segments), atomic per-slot receiver counts, and explicit 16-byte Unpin RecvShared and RecvCloned futures: - Let steady-state send, try_recv, try_recv_cloned, ready recv / recv_cloned polls, empty probes, and zero-receiver discards execute without acquiring a channel mutex, while keeping a Mutex<u64> fallback on targets without 64-bit atomics. - Coordinate subscription changes through four cache-line-separated publisher epoch shards, recycle retired heap segments across three epochs with burst hysteresis, and immediately release heap segments when either endpoint side closes and finishes draining. - Suspend poll_recv without spinning when a claimed slot write is still in flight, and park synchronous try_recv and drop_receiver in-flight waits on a private Mutex + Condvar waker.
…overage
Expand integration, auto-trait, and changelog coverage for unbounded broadcast segment buffers and explicit receive futures:
- Cover poll-after-completion panics, overflow waiter slot reuse and waker replacement, completed future moves after payload drop, multi-segment concurrent subscribe/resubscribe/drop churn, close vs. try_recv linearizability, and concurrent last-receiver drop with resubscription in broadcast_test.
- Assert Unpin on UnboundedReceiver::{recv, recv_cloned} futures over !Unpin payloads in traits_test.
- Record the broadcast::mpmc::unbounded improvements and tradeoffs in CHANGELOG.md.
biaoma-ty
force-pushed
the
perf/broadcast-unbounded-segments
branch
from
November 24, 2026 14:23
5f094a0 to
83310f3
Compare
…ordering races Fix concurrency, layout, and counter-bound defects in `broadcast::mpmc::unbounded`: - Distinguish retired segments from segments without an allocated successor by storing a dedicated `unlinked_next` sentinel on `release_seg_ref` and reloading `tail_seg` when a preempted publisher encounters an unlinked predecessor, while guarding `advance_or_get_next_for_pub` against resurrecting a retired segment's zero reference count. - Compute `Segment::slot_ptr_at` via `mem::offset_of!(InlineSegment<T>, slots)` backed by a compile-time layout equality check with `HeapSegment<T>` instead of a zero-length `[MsgSlot<T>; 0]` tail array, fixing a 4-byte slot misalignment into uninitialized padding on 32-bit targets. - Use `Ordering::SeqCst` across publisher `tail_seg` loads, `extra_shards` pause barriers, and 3-epoch `Shard::is_epoch_idle` checks so weak-memory Store-Buffering reorderings cannot bypass subscription pauses or segment quiescence, and unify `Shard` to `[AtomicUsize; EPOCHS]` to eliminate the 16-bit per-epoch publisher cap. - Guard `CounterU64::claim_next` and `advance_or_abort` below `u64::MAX` so concurrent overflow checks saturate cleanly without wrapping `tail` to zero, and replace mutual recursion between `send` and `send_cold` with `try_discard_cold`. Signed-off-by: tison <[email protected]>
… races Eliminate the segment-pool hysteresis glue in `broadcast::mpmc::unbounded` while closing half-closed inline-segment reset races and adding a lock-free final-receiver teardown path: - Replace `SegmentPool`'s multi-segment `free_list`, cycle peak tracking, and `maybe_shrink_pool` hysteresis with a single `spare` heap segment (`HEAP_CAP = 252`, fitting a 4 KiB page on 64-bit targets) so excess retired segments deallocate immediately upon 3-epoch quiescence during streaming and partial drains without per-message cold-path probes. - Track active segment readers (`seg_readers`) across `drop_receiver`'s unlocked backlog drain so `reclaim_all_heap_when_no_receivers`, `reclaim_when_drained_and_disconnected`, and zero-receiver `subscribe` only reset `inline_seg0` once every live and draining subscription has released its segment reference, unlink any speculative successor attached to `inline_seg0` at the `INLINE_CAP` boundary, and keep publishers paused until pool cleanup completes. - Release any cached spare segment when the final sender disconnects on an already-drained channel, and bypass locks and atomic RMWs when dropping the sole remaining `seg_readers == 1` receiver on a disconnected channel. Signed-off-by: tison <[email protected]>
…ontracts Replace custom overflow waiter arena bookkeeping with `internal::wakerset::WakerSet`, shrink receive futures to one pointer, and tighten observable contract documentation: - Keep the uncontended inline `slot0` waker in `Waiters` while delegating multi-waiter overflow slots to `WakerSet` and storing registration state on `Subscription<T>`, shrinking `RecvShared` and `RecvCloned` to `size_of::<usize>()` (`8 B` on 64-bit and `4 B` on 32-bit targets). - Saturate `retained_message_count` and `unread_from` to `usize::MAX` instead of panicking on 32-bit concurrent skew, and document in-flight publication and approximate reclamation observations on `retained_message_count` and `unread_message_count`. - Update `CHANGELOG.md` with measured cross-platform allocation sizes and final observable contracts. Signed-off-by: tison <[email protected]>
Run `ptr::drop_in_place` on `HeapSegment<T>` before `alloc::dealloc` so targets without 64-bit atomics drop the `Mutex<u64>` fallback in `Segment::base` instead of leaking any lazily boxed OS mutex state, while compiling to a no-op on 64-bit-atomic targets, and tighten the `reclaim_when_drained_and_disconnected` doc comment to match its sole-reader scope. Signed-off-by: tison <[email protected]>
tisonkun
enabled auto-merge (squash)
November 24, 2026 23:20
tisonkun
approved these changes
Nov 24, 2026
tisonkun
left a comment
Member
There was a problem hiding this comment.
Thanks!
I'm afraid that all this code changes increase the cognitive overload, so maybe later we will give an overall code review for all the channels.
This was referenced Nov 25, 2026
Contributor
Author
Roger that. |
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
broadcast::mpmc::unboundedpreviously put itsVecDeque<Slot<T>>backlog,Arena<u64>subscriber cursors, and parked receiver wakers behind one channelMutex, so every publish, receive, empty probe, subscription change, and cancellation serialized on the same lock.broadcast::mpmc::unbounded::{queue, segment}): Replace the mutex-guardedVecDequeand cursor arena with an 8-slot inline segment inShared<T>plus252-slot (4,080 B, single 4 KiB page) heap segments, monotonictailandreclaimedu64counters (AtomicU64with aMutex<u64>fallback on targets without 64-bit atomics), and per-slot receiver counts so steady-statesend,try_recv,try_recv_cloned, readyrecv/recv_clonedpolls, empty probes, and zero-receiver discards proceed without acquiring a channel mutex.Unpinreceive futures andWakerSet-backed waiters (mod,waiters): Replace the outerasync fnreceive wrappers with1 * usize(8 Bon 64-bit,4 Bon 32-bit)UnpinRecvSharedandRecvClonedfutures backed by an inline single-waiter slot andinternal::wakerset::WakerSetoverflow storage, keeping uncontended single-receiver waits allocation-free and detaching woken registrations without relocking on drop.Unpintrait, and multi-seed Miri coverage for segment boundaries, retired-predecessor unlinking, half-closed segment reclamation across unwinds and lagging drops, in-flight slot suspension and parking, and concurrent subscription churn, and updateCHANGELOG.md.Closes #402.
Part of #396.
Design Notes
kreceivers are subscribed,sendclaims the nextu64version, writesArc<T>into the segment slot, and storesslot.state = k. Each receiver advances its own(cursor, seg, slot_ptr, rem_in_seg)cursor: whenslot.state == 1, the final eligible reader moves theArc<T>out directly without an atomic decrement (sotry_recv_clonedandrecv_clonedstill unwrapTwithout cloning on sole ownership) and incrementsreclaimed; whenslot.state >= 2, readers clone theArc<T>beforefetch_sub(1, AcqRel). When no receivers exist,senddiscards the value without entering the backlog while advancing bothtailandreclaimed.send(shard0inline plus three lazily allocated shards once cloned).subscribeanddrop_receiverpause new publishers undercontrolonly while snapshottingtailand updatinglive_receivers, whileseg_readerstracks subscriptions through unlocked backlog drains soinline_seg0is only reset once every live and draining reader has released its segment reference. Retired heap segments recycle across 3 publisher epochs, retaining at most one4,080 Bspare segment during active streaming and deallocating excess segments immediately (including during partial drains and upon endpoint closure).tailadvances right beforesendfinishes writingslot.msgandslot.state, a receiver can briefly observetail > cursorwhileslot.state == 0. Asyncpoll_recvregisters its taskWakerand returnsPoll::Pendingrather than spinning on the executor thread, while synchronoustry_recvanddrop_receiverpark on a privateMutex<bool>+Condvarwaker so any callerThread::unparktoken stays intact.16 BUnboundedSenderplus a lazy shard allocation once cloned, and56 BUnboundedReceiveron 64-bit targets), each channel uses a larger cache-line-isolated sharedArcallocation (936 Bonaarch64-apple-darwinand912 Bonx86_64-unknown-linux-gnu, including 8 inline16 Bmessage slots) plus4,080 B252-slot heap segments (alloc_zeroed) when retained backlog exceeds 8 messages, and dropping a lagging receiver while other subscriptions remain active scans and decrements its unread slots.Benchmarks
Measured back-to-back on Apple Silicon (
aarch64-apple-darwin, optimized Cargobenchprofile, median of 5 runs) comparingorigin/main(1c5584d) againstHEAD(b090ff8):main(1c5584d)b090ff8)ecosystembroadcast/no-backpressure/try-roundtripecosystembroadcast/no-backpressure/ready-roundtripecosystembroadcast/no-backpressure/publish-4p-drain-1recosystembroadcast/no-backpressure/drain-4rprimitivessend_and_try_recv_sharedprimitivessend_and_try_recv_string_sharedprimitivessend_and_try_recv_string_cloned_soleprimitivessend_and_try_recv_string_cloned_fanoutprimitivesdeliver_to_waiting_receiverprimitivesregister_and_deliver_fanout/1primitivesregister_and_deliver_fanout/4primitivesregister_and_deliver_fanout/16primitivessend_without_receiversprimitivestry_recv_emptyprimitivesdrain_with_receivers/peak 1 live 1primitivesdrain_with_receivers/peak 8 live 8primitivesdrain_with_receivers/peak 8 live 1primitivesdrain_with_receivers/peak 32 live 32primitivesdrain_with_receivers/peak 32 live 4primitivesdrain_with_receivers/peak 32 live 1primitivesdrain_with_receivers/peak 256 live 32primitivesdrain_with_receivers/peak 256 live 1primitivescancel_pendingValidation
cargo x lintcargo x checkcargo +1.86.0 check --workspace --all-targets --all-featurescargo x testcargo +stable semver-checks --baseline-rev origin/main -p asyncband --all-features(196/196 passed)MIRIFLAGS="-Zmiri-strict-provenance -Zmiri-symbolic-alignment-check -Zmiri-many-seeds=0..4" cargo +nightly miri test --package asyncband --lib --features broadcast -- broadcast::mpmcMIRIFLAGS="-Zmiri-strict-provenance -Zmiri-symbolic-alignment-check -Zmiri-many-seeds=0..4" cargo +nightly miri test --package tests-integration --test broadcast_test --test traits_testcargo x bench -- --test