Skip to content

fix(once): broadcast completion across Once and OnceCell and add OnceCell::wait - #446

Merged
tisonkun merged 4 commits into
mainfrom
fix/once-broadcast-completion
Nov 21, 2026
Merged

tisonkun merged 4 commits into
mainfrom
fix/once-broadcast-completion

Conversation

@tisonkun

Copy link
Copy Markdown
Member

Part of #445.

Problem

Once and OnceCell previously serialized concurrent initializers through fixed-permit Semaphore instances (Semaphore::new(1) alongside a CountdownState in Once, and Semaphore::new(3) with two permits per initializer in OnceCell):

  1. Paused-waiter head-of-line blocking: When an active initializer finished, releasing its permits could ready only the head queued caller. If that head caller had polled once and then paused polling without dropping (for example, while another branch of a select! or state machine remained active), trailing callers in Once, OnceCell, OnceMap, and singleflight::Group received no wakeup and remained Pending even though initialization was already complete.
  2. Serial wakeup chain and footprint: Concurrent followers woke one by one as each scheduled task polled completion and dropped its temporary permit. Once also carried two mutexes (144 B on 64-bit Apple targets) and took the semaphore's waiter lock on every uncontended completion because its single permit left available == 0.
  3. Missing observer wait on OnceCell: Unlike Once::wait, OnceCell had no observer-only entry point for callers that want to await publication without supplying an initializer.

Solution

  1. Introduce internal::once_state::OnceState: Separate exclusive initializer ownership from completion broadcast behind a compact atomic state (UNINIT, RUNNING, HAS_WAITERS, COMPLETE) and one waiter mutex:
    • Uncontended attempts transition UNINIT -> RUNNING -> COMPLETE (or RUNNING -> UNINIT on error/cancellation) via single atomic compare-exchanges without locking.
    • Single-waiter contention (either one candidate initializer or one observer) uses an inline slot without allocating an arena or overflow box.
    • Aborted, failed, or panicked attempts transfer leadership in strict FIFO order to at most one queued candidate without waking pure wait observers.
    • Successful completion detaches all queued candidates and observers at once, wakes them in parallel outside the lock, and releases any overflow waiter storage immediately.
  2. Migrate Once and OnceCell onto OnceState: Shrinks Once from 144 B to 56 B and OnceCell<u64> from 88 B to 72 B on 64-bit macOS while unblocking OnceMap and singleflight::Group followers simultaneously upon publication.
  3. Expose OnceCell::wait(&self) -> &T: Allows observers to await value publication without providing a closure; cancelling a pending wait unregisters only that observer.

Benchmarks

Apple M4 Max (macOS arm64), whole-batch medians across 7 runs (once, once_map) and 5 runs (singleflight), lower is faster:

Benchmark main (d436cd9) This PR Change
once::get_or_init::initialize_cell 78 ms 56 ms -28.2%
once::get_or_init::initialized_cell 105 ms 101 ms -3.8%
once::get_or_init::initialize_cell_waiter_batch/1 468 ms 365 ms -22.0%
once::get_or_init::initialize_cell_waiter_batch/4 264 ms 199 ms -24.6%
once::get_or_init::initialize_cell_waiter_batch/16 248 ms 154 ms -37.9%
once::wait::complete_waiter 269 ms 172 ms -36.1%
once::wait::complete_waiter_batch/1 576 ms 409 ms -29.0%
once::wait::complete_waiter_batch/4 232 ms 228 ms -1.7%
once::wait::complete_waiter_batch/16 175 ms 173 ms -1.1%
once::wait::cancel_pending_wait 314 ms 212 ms -32.5%
once_map::initialize::initialize_same_key/2 381 ms 276 ms -27.6%
once_map::initialize::initialize_same_key/4 298 ms 236 ms -20.8%
once_map::initialize::initialize_same_key/16 253 ms 174 ms -31.2%
singleflight::coalescing::complete_coalesced/2 246 ms 203 ms -17.5%
singleflight::coalescing::complete_coalesced/4 217 ms 189 ms -12.9%
singleflight::coalescing::complete_coalesced/16 230 ms 161 ms -30.0%
singleflight::coalescing::coalesced_retry_after_leader_error/16 223 ms 160 ms -28.3%
singleflight::leaders::leader_success 127 ms 116 ms -8.7%
singleflight::leaders::leader_error 119 ms 101 ms -15.1%

Validation

  • cargo x lint
  • cargo x check
  • cargo x test
  • Deterministic WakeCounter regressions for paused head followers, FIFO cancellation handoff, and observer-only waits across once_test, once_cell_test, singleflight_test, and Miri

…state

`Once` previously combined a `CountdownState` for observers with a one-permit `Semaphore` for `call_once` callers. That representation carried two mutexes (`144 B`), locked the semaphore queue on every uncontended completion because the single permit left `available == 0`, woke concurrent `call_once` followers one at a time as permits returned, and left trailing `call_once` callers blocked if the head follower stopped polling without dropping.

Introduce `internal::once_state::OnceState` to separate exclusive initializer selection from completion notification. Uncontended initialization transitions `UNINIT -> RUNNING -> COMPLETE` with atomic compare-exchanges and no mutex acquisitions, single-waiter contention uses an inline slot without allocating an arena, aborted attempts hand leadership to at most one queued candidate in FIFO order without waking pure `wait` observers, and successful completion broadcasts to every queued candidate and observer at once.
…hore state

`OnceCell` previously serialized `get_or_init` and `get_or_try_init` callers through a three-permit `Semaphore`, taking two permits per initializer. When the active initializer published a value and released its two permits, only the head waiting caller could become ready; each follower had to be scheduled and drop its temporary permit before the next follower was woken, and a head waiter that stopped polling without dropping kept trailing callers in `OnceCell`, `OnceMap`, and `singleflight::Group` blocked even after the value was published.

Switch `OnceCell` from `Semaphore` to `OnceState` so publication wakes every queued caller at once and releases overflow waiter storage immediately, while failed, panicked, or cancelled attempts still hand off to at most one queued candidate in FIFO order.
`Once` provides `Once::wait` for callers that need to observe completion without supplying an initializer, whereas `OnceCell` required every waiting caller to pass a dummy closure to `get_or_init`.

Expose `OnceCell::wait(&self) -> &T` backed by `OnceState::wait`. Pending observer waits stay asleep across failed or cancelled initialization attempts, wake in parallel when a value is published, and unregister cleanly on cancellation without affecting active initializers or other waiters.
…sets

Clearing `HAS_WAITERS` when the last waiter cancelled or claimed leadership previously left an empty `Box<OverflowWaiters>` in `Waiters::overflow`, allowing a subsequent lock-free `RUNNING -> COMPLETE` transition to retain burst waiter capacity until the primitive dropped. `OnceCell::get_mut_or_try_init` also called `complete_mut()` redundantly when a value was already stored.

Take and drop `Waiters::overflow` outside the waiter lock whenever the last waiter leaves so `HAS_WAITERS == 0` implies no retained overflow allocation, guard `complete_mut` and `reset_mut` on `HAS_WAITERS` before taking `Waiters`, and replace the `get_mut_or_try_init` hit-path `complete_mut()` call with a debug assertion.
@tisonkun
tisonkun merged commit c0ac0c1 into main Nov 21, 2026
9 checks passed
@tisonkun
tisonkun deleted the fix/once-broadcast-completion branch November 21, 2026 07:43
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.

1 participant