byteflow-actors 0.9.28

Embeddable flow runtime: M:N scheduler, Atomic Hop (Message+Cap), supervisor — use byteflow::
Documentation
//! Chase-Lev work-stealing deque (single owner, many stealers).
//!
//! The owner pushes and pops at the bottom. Stealers take from the top.
//! Those two ends meet only on the last task, so a busy worker does not
//! take a mutex to run its own queue. `unsafe` stays in this module;
//! the parent module exposes the safe wrapper.
//!
//! Buffer growth is intentionally absent: the ring has a fixed power-of-two
//! capacity. A full push returns the task so the caller can spill it onto
//! the global injector. That avoids retiring old buffers while a stealer
//! still holds the previous pointer.
//!
//! Algorithm: Chase and Lev, "Dynamic Circular Work-Stealing Deque" (SPAA
//! 2005), with the Lê et al. correction for weak memory (PPoPP 2013).
//!
//! # Why the slots are `AtomicPtr`
//!
//! A stealer reads its slot *before* the CAS on `top` decides whether it
//! owns the task. A stealer that stalls while the ring wraps can therefore
//! read a slot the owner is rewriting, or one whose task was already taken
//! and freed. With `UnsafeCell<MaybeUninit<T>>` slots that read is a data
//! race, and materialising the stale `T` (for example a dangling `Box`) is
//! undefined behaviour even when it is later `mem::forget`-ed. Miri reported
//! both. Storing the raw pointer of a `Box<T>` in an atomic makes the
//! speculative read a plain atomic load of an integer: a loser discards the
//! pointer without ever turning it back into a `Box`. Tasks are boxed flows
//! already, so this costs no extra allocation.
//!
//! # Verification
//!
//! The atomics come from [`sync`], which is `std` in normal builds and
//! [`loom`](https://docs.rs/loom) under `--cfg loom`. Loom explores every
//! interleaving the C11 model allows for the scenarios in `loom_tests`;
//! Miri runs the ordinary unit tests with its data-race and validity
//! checks. See `CONTRIBUTING.md` for the commands.

#![allow(unsafe_code)]

use std::marker::PhantomData;
use std::ptr;

use self::sync::{fence, AtomicI64, AtomicPtr, Ordering};
use super::Steal;

/// `std` atomics in normal builds.
#[cfg(not(loom))]
mod sync {
    pub(super) use std::sync::atomic::{fence, AtomicI64, AtomicPtr, Ordering};
}

/// Loom's model-checked atomics (`RUSTFLAGS="--cfg loom"`).
#[cfg(loom)]
mod sync {
    pub(super) use loom::sync::atomic::{fence, AtomicI64, AtomicPtr, Ordering};
}

/// Slots in one worker's local ring. Power of two so the index is a mask.
///
/// Loom runs with a tiny ring so wrap-around stays inside its search budget.
#[cfg(not(loom))]
pub(super) const LOCAL_CAP: usize = 256;
#[cfg(loom)]
pub(super) const LOCAL_CAP: usize = 4;

const _: () = assert!(LOCAL_CAP.is_power_of_two());

/// Owner-at-bottom, stealers-at-top ring of boxed tasks.
pub(super) struct LocalQueue<T> {
    top: AtomicI64,
    bottom: AtomicI64,
    /// `Box::into_raw` pointers. Null or stale outside `top..bottom`.
    slots: Box<[AtomicPtr<T>]>,
    /// The queue owns the boxes in `top..bottom`.
    _owns: PhantomData<Box<T>>,
}

// SAFETY: every live slot holds a `Box<T>` that exactly one thread turns
// back into a `Box`: the owner in `pop` or the stealer whose CAS on `top`
// succeeds. Moving a `Box<T>` to another thread needs only `T: Send`, and
// shared access never hands out `&T`, so `T: Sync` is not required. The
// fields are atomics, so concurrent access itself is race-free.
unsafe impl<T: Send> Send for LocalQueue<T> {}
// SAFETY: see above; `&LocalQueue` only lets a thread move a `Box<T>` out.
unsafe impl<T: Send> Sync for LocalQueue<T> {}

impl<T> LocalQueue<T> {
    pub(super) fn new() -> Self {
        let slots = (0..LOCAL_CAP)
            .map(|_| AtomicPtr::new(ptr::null_mut()))
            .collect::<Vec<_>>()
            .into_boxed_slice();
        Self {
            top: AtomicI64::new(0),
            bottom: AtomicI64::new(0),
            slots,
            _owns: PhantomData,
        }
    }

    /// Tasks the owner has published and nobody has taken yet.
    ///
    /// Racy by nature: a stealer may win the last task between the two
    /// loads. Callers use it as a hint (yield fairness), not as a bound.
    pub(super) fn has_tasks(&self) -> bool {
        let b = self.bottom.load(Ordering::Relaxed);
        let t = self.top.load(Ordering::Acquire);
        b.wrapping_sub(t) > 0
    }

    /// Owner only. `Err(task)` means the ring is full; the task was not stored.
    pub(super) fn push(&self, task: Box<T>) -> Result<(), Box<T>> {
        let b = self.bottom.load(Ordering::Relaxed);
        let t = self.top.load(Ordering::Acquire);
        if b.wrapping_sub(t) >= LOCAL_CAP as i64 {
            return Err(task);
        }
        // `b - t < CAP`, so slot `b` is outside the live range, and only the
        // owner writes `bottom`, so no other push targets it. The release
        // fence publishes the slot together with the new `bottom`.
        self.slot(b).store(Box::into_raw(task), Ordering::Relaxed);
        fence(Ordering::Release);
        self.bottom.store(b.wrapping_add(1), Ordering::Relaxed);
        Ok(())
    }

    /// Owner only. `None` if the ring is empty or a stealer took the last task.
    pub(super) fn pop(&self) -> Option<Box<T>> {
        let b = self.bottom.load(Ordering::Relaxed).wrapping_sub(1);
        self.bottom.store(b, Ordering::Relaxed);
        fence(Ordering::SeqCst);
        let t = self.top.load(Ordering::Relaxed);
        if b < t {
            self.bottom.store(t, Ordering::Relaxed);
            return None;
        }
        let raw = self.slot(b).load(Ordering::Relaxed);
        if b > t {
            // SAFETY: `t < b`: stealers only take index `top`, so slot `b`
            // still holds the box this owner pushed, and nobody else can
            // reach it now that `bottom` excludes it.
            return Some(unsafe { Box::from_raw(raw) });
        }
        // Last task: race the stealers for it on `top`.
        let won = self
            .top
            .compare_exchange(t, t.wrapping_add(1), Ordering::SeqCst, Ordering::Relaxed)
            .is_ok();
        self.bottom.store(t.wrapping_add(1), Ordering::Relaxed);
        if won {
            // SAFETY: the successful CAS made this thread the only owner of
            // the box in slot `t == b`.
            Some(unsafe { Box::from_raw(raw) })
        } else {
            None
        }
    }

    pub(super) fn steal(&self) -> Steal<Box<T>> {
        let t = self.top.load(Ordering::Acquire);
        fence(Ordering::SeqCst);
        let b = self.bottom.load(Ordering::Acquire);
        if t >= b {
            return Steal::Empty;
        }
        // May be stale if this thread stalled while the ring wrapped; then
        // the CAS below fails and the pointer is discarded unused.
        let raw = self.slot(t).load(Ordering::Relaxed);
        if self
            .top
            .compare_exchange(t, t.wrapping_add(1), Ordering::SeqCst, Ordering::Relaxed)
            .is_ok()
        {
            // SAFETY: the CAS moved `top` from `t`, so slot `t` was still live
            // (its box not yet taken) and this thread is its only owner. The
            // `Acquire` on `bottom` synchronised with the push that stored it.
            Steal::Success(unsafe { Box::from_raw(raw) })
        } else {
            Steal::Retry
        }
    }

    fn slot(&self, index: i64) -> &AtomicPtr<T> {
        debug_assert!(index >= 0);
        let i = (index as usize) & (LOCAL_CAP - 1);
        &self.slots[i]
    }
}

impl<T> Drop for LocalQueue<T> {
    fn drop(&mut self) {
        // Last `Arc` owner: stealers and the worker are gone, so relaxed
        // loads see the final indices (the `Arc` drop already synchronized).
        let t = self.top.load(Ordering::Relaxed);
        let b = self.bottom.load(Ordering::Relaxed);
        let mut i = t;
        while i < b {
            let raw = self.slot(i).load(Ordering::Relaxed);
            // SAFETY: `t <= i < b` is the live range; each slot in it holds a
            // box pushed and never taken, and `&mut self` excludes every
            // other thread.
            drop(unsafe { Box::from_raw(raw) });
            i = i.wrapping_add(1);
        }
    }
}

/// Model-checked scenarios. Run with:
///
/// ```text
/// RUSTFLAGS="--cfg loom" cargo test -p byteflow-actors --lib --release loom_
/// ```
#[cfg(all(test, loom))]
mod loom_tests {
    #![allow(clippy::unwrap_used, clippy::expect_used)]

    use loom::sync::atomic::{AtomicUsize, Ordering};
    use loom::sync::Arc;
    use loom::thread;

    use super::{LocalQueue, Steal, LOCAL_CAP};

    /// Counts drops so a double drop or a leak fails the model.
    struct Task {
        id: usize,
        drops: Arc<AtomicUsize>,
    }

    impl Drop for Task {
        fn drop(&mut self) {
            self.drops.fetch_add(1, Ordering::Relaxed);
        }
    }

    fn task(id: usize, drops: &Arc<AtomicUsize>) -> Box<Task> {
        Box::new(Task {
            id,
            drops: Arc::clone(drops),
        })
    }

    fn steal_until_settled(q: &LocalQueue<Task>) -> Option<usize> {
        loop {
            match q.steal() {
                Steal::Success(t) => return Some(t.id),
                Steal::Empty => return None,
                Steal::Retry => thread::yield_now(),
            }
        }
    }

    fn model(f: impl Fn() + Sync + Send + 'static) {
        let mut builder = loom::model::Builder::new();
        builder.preemption_bound = Some(3);
        builder.check(f);
    }

    /// The last-task race: owner pop vs one stealer. Exactly one wins.
    #[test]
    fn loom_last_task_goes_to_exactly_one() {
        model(|| {
            let drops = Arc::new(AtomicUsize::new(0));
            let q = Arc::new(LocalQueue::new());
            assert!(q.push(task(1, &drops)).is_ok());

            let thief = {
                let q = Arc::clone(&q);
                thread::spawn(move || steal_until_settled(&q))
            };
            let mine = q.pop().map(|t| t.id);
            let stolen = thief.join().unwrap();

            assert_eq!(mine.is_some() as u8 + stolen.is_some() as u8, 1);
            drop(q);
            assert_eq!(drops.load(Ordering::Relaxed), 1);
        });
    }

    /// Two stealers and the owner share two tasks; every task is taken once.
    #[test]
    fn loom_two_thieves_conserve_tasks() {
        model(|| {
            let drops = Arc::new(AtomicUsize::new(0));
            let q = Arc::new(LocalQueue::new());
            assert!(q.push(task(1, &drops)).is_ok());
            assert!(q.push(task(2, &drops)).is_ok());

            let thieves: Vec<_> = (0..2)
                .map(|_| {
                    let q = Arc::clone(&q);
                    thread::spawn(move || steal_until_settled(&q))
                })
                .collect();
            let mut seen: Vec<usize> = q.pop().map(|t| t.id).into_iter().collect();
            for thief in thieves {
                seen.extend(thief.join().unwrap());
            }
            while let Some(t) = q.pop() {
                seen.push(t.id);
            }
            seen.sort_unstable();
            assert_eq!(seen, vec![1, 2]);
            drop(q);
            assert_eq!(drops.load(Ordering::Relaxed), 2);
        });
    }

    /// Owner keeps pushing while a thief steals, so slots are reused after
    /// the ring wraps. Nothing is lost, duplicated or dropped twice.
    #[test]
    fn loom_push_during_steal_with_wraparound() {
        model(|| {
            let drops = Arc::new(AtomicUsize::new(0));
            let q = Arc::new(LocalQueue::new());
            for id in 0..LOCAL_CAP {
                assert!(q.push(task(id, &drops)).is_ok());
            }

            let thief = {
                let q = Arc::clone(&q);
                thread::spawn(move || steal_until_settled(&q))
            };
            let mut seen = Vec::new();
            // Free one slot, then reuse it: the new task lands on a slot
            // index a slow thief might still be looking at.
            seen.extend(q.pop().map(|t| t.id));
            if let Err(t) = q.push(task(LOCAL_CAP, &drops)) {
                seen.push(t.id);
            }
            seen.extend(thief.join().unwrap());
            while let Some(t) = q.pop() {
                seen.push(t.id);
            }
            seen.sort_unstable();
            assert_eq!(seen, (0..=LOCAL_CAP).collect::<Vec<_>>());
            drop(q);
            assert_eq!(drops.load(Ordering::Relaxed), LOCAL_CAP + 1);
        });
    }

    /// Tasks still queued when the last handle goes away are dropped once.
    #[test]
    fn loom_drop_releases_queued_tasks() {
        model(|| {
            let drops = Arc::new(AtomicUsize::new(0));
            let q = Arc::new(LocalQueue::new());
            for id in 0..3 {
                assert!(q.push(task(id, &drops)).is_ok());
            }
            let thief = {
                let q = Arc::clone(&q);
                thread::spawn(move || steal_until_settled(&q))
            };
            let stolen = thief.join().unwrap();
            assert!(stolen.is_some());
            drop(q);
            assert_eq!(drops.load(Ordering::Relaxed), 3);
        });
    }
}