Skip to main content

yscv_threadpool/
lib.rs

1//! Custom work-stealing thread pool with priority-aware cold-idle spin.
2//!
3//! Designed to replace `rayon::ThreadPool` in yscv inference hot paths.
4//! On sub-4ms inferences, rayon's park-on-idle policy dominates MT overhead —
5//! the park/unpark round-trip between back-to-back submissions costs hundreds
6//! of nanoseconds per subtask. ORT's Eigen ThreadPool sidesteps this by
7//! holding workers in a cold-idle spin (~300µs) before parking.
8//!
9//! This crate lands the replacement in phases:
10//!   A.1 — skeleton pool with shared `Mutex<VecDeque<Task>>`, `install` API.
11//!   A.2 — per-worker Chase-Lev deques (via `crossbeam-deque`) with
12//!     random-victim work-stealing, still parks on empty.
13//!   **A.3 (current)** — cold-idle spin before park. Workers spin for
14//!     `YSCV_POOL_SPIN_US` microseconds (default 300) watching for new
15//!     work before blocking on the condvar. Back-to-back inferences
16//!     arriving within the spin window skip the park/unpark round-trip.
17//!   A.4 — priority-aware scheduling + big/physical-core affinity.
18//!   A.5 — `ParallelScope` trait + drop-in into `OnnxRunner`.
19//!   A.6 — empirical tuning and default switch decision.
20//!
21//! ## API
22//!
23//! ```no_run
24//! use yscv_threadpool::YscvPool;
25//! let pool = YscvPool::new(6).expect("build pool");
26//! let result = pool.install(|| {
27//!     // Runs on one of the pool's worker threads.
28//!     42
29//! });
30//! assert_eq!(result, 42);
31//! ```
32//!
33//! ## Unsafe policy
34//!
35//! This crate opts **into** `unsafe` (overriding the workspace-wide
36//! `unsafe_code = deny` lint) for the narrow case of extending closure
37//! lifetimes in `install`, matching `rayon::ThreadPool::install`'s
38//! design. Every `unsafe` block carries a `SAFETY:` comment documenting
39//! the invariants that make it sound.
40
41use std::cell::Cell;
42use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering};
43use std::sync::{Arc, OnceLock};
44use std::thread;
45use std::time::{Duration, Instant};
46
47// Thread-local set on every pool worker at spawn; read by
48// `YscvPool::current_worker_index()`. None for non-pool threads (main,
49// tests, rayon workers). Used by yscv-kernels to detect re-entrant
50// dispatch and avoid nested parallelism that over-subscribes the pool.
51thread_local! {
52    static CURRENT_WORKER: Cell<Option<usize>> = const { Cell::new(None) };
53}
54
55// Step 3 Session C: per-worker dispatch context installed by
56// `worker_loop` before entering the steal/sleep cycle. Used by
57// `section::try_run_regular_task` when a section is active but
58// `current_loop` is empty — instead of spinning idle, the worker
59// attempts to pick up a regular task (e.g. a `join_dyn` submit from
60// tower-parallel) so tower-parallel graphs don't deadlock.
61//
62// The pointers are valid for the duration of `worker_loop` — cleared
63// before the function returns.
64thread_local! {
65    pub(crate) static WORKER_DISPATCH_CTX: Cell<Option<WorkerDispatchCtx>> =
66        const { Cell::new(None) };
67}
68
69#[derive(Clone, Copy)]
70pub(crate) struct WorkerDispatchCtx {
71    pub(crate) local: *const DequeWorker<Task>,
72    pub(crate) shared: *const Shared,
73    pub(crate) worker_id: usize,
74    pub(crate) nworkers: usize,
75}
76
77pub mod affinity;
78mod scope;
79mod section;
80pub use scope::ParallelScope;
81pub use section::{PersistentSection, SectionGuard, current_section};
82
83/// `YSCV_POOL_SPIN_US` — microseconds workers spin on empty before parking.
84/// Default 0 — **measured optimum for ONNX inference workloads** on
85/// tracker-style graphs (fine-grained, 100–200 dispatches/inf, 10–50µs
86/// apart). Spin burns CPU cycles that steal from the main thread's
87/// useful work; zero-spin + park defers to the OS scheduler which wakes
88/// fast enough via `thread::unpark` (futex). Raise via env for coarse
89/// install-per-task patterns where spin pays off.
90///
91/// Measured on Zen 4 Siamese tracker (2026-04-19): spin=0 gave 4.29ms/6T,
92/// spin=50 gave 6.0ms, spin=300 gave 9.3ms, spin=1000 gave 19ms.
93fn spin_us() -> u64 {
94    static CACHED: OnceLock<u64> = OnceLock::new();
95    *CACHED.get_or_init(|| {
96        std::env::var("YSCV_POOL_SPIN_US")
97            .ok()
98            .and_then(|s| s.parse::<u64>().ok())
99            .unwrap_or(0)
100    })
101}
102
103use crossbeam_deque::{Injector, Steal, Stealer, Worker as DequeWorker};
104
105mod job;
106pub(crate) use job::JobRef;
107
108/// Worker task transport. `JobRef` is a 16-byte Copy type: `(fn_ptr,
109/// data_ptr)`. The caller stores the closure/state on its own stack
110/// frame and blocks on a latch/channel until every worker finishes —
111/// zero heap alloc per task. Replaces the pre-A″.4 `Box<dyn FnOnce>`
112/// which cost ~1200 `Box::new` per 6T inference on the tracker.
113type Task = JobRef;
114
115/// Shared state: one global injector queue for incoming submissions, one
116/// stealer per worker so other workers can steal its leftovers, a
117/// shutdown flag, and the lock-free sleep-state machinery.
118///
119/// ## Sleep state machine (A″.2)
120///
121/// Workers transition through THREE states to avoid futex syscalls in the
122/// hot inference path (where dispatches are 10-50 µs apart):
123///
124/// - `Active` (0): running a task, actively stealing, or in the optional
125///   spin window. `submit` never needs to signal an Active worker.
126/// - `Sleepy` (1): "ready to park" — the worker has exhausted one steal
127///   loop and is yield-watching `jobs_event`. If the counter changes
128///   while we're Sleepy, we observe it on the next yield_now iteration
129///   and drop back to Active, fetching the new work. **Critical: no
130///   park/unpark syscall fires in this state.**
131/// - `Sleeping` (2): past the Sleepy watch window; blocked on
132///   `thread::park_timeout`. Only reached when the worker is truly idle
133///   (no new dispatches in ~32 yield iterations ≈ 100 µs+).
134///
135/// ## JobsEventCounter
136///
137/// Packed `AtomicU64` — the rayon-equivalent of their `JobsEventCounter`:
138/// - bits 0..32   — `counter`: incremented by `submit` when `num_sleepy
139///   > 0 && was_empty`. Sleepy workers captured the old value; counter
140///   > inequality tells them new work exists.
141/// - bits 32..48  — `num_sleepy`: count of workers currently in Sleepy.
142/// - bits 48..64  — `num_sleeping`: count of workers actually parked.
143///
144/// The three fields fit in one atomic word so `submit` reads all of them
145/// with a single `load(Acquire)`. Increments to any field use
146/// `fetch_add`/`fetch_sub` with the right stride (`1`, `1 << 32`,
147/// `1 << 48`). Overflow of `counter` is fine — workers compare equality,
148/// and wrap-around only misses a wake when `num_sleepy` workers captured
149/// the exact same pre-wrap value (vanishingly improbable across 2^32
150/// submits).
151const WORKER_ACTIVE: u8 = 0;
152const WORKER_SLEEPY: u8 = 1;
153const WORKER_SLEEPING: u8 = 2;
154
155/// Number of yield-watch iterations a Sleepy worker performs before
156/// transitioning to Sleeping. Chosen so that under tracker-style
157/// fine-grained dispatch (10-50 µs apart), sequential dispatches land
158/// inside the window and the worker never reaches Sleeping. Tunable via
159/// `YSCV_POOL_SLEEPY_ROUNDS` for coarse workloads.
160fn sleepy_rounds() -> u32 {
161    static CACHED: OnceLock<u32> = OnceLock::new();
162    *CACHED.get_or_init(|| {
163        std::env::var("YSCV_POOL_SLEEPY_ROUNDS")
164            .ok()
165            .and_then(|s| s.parse::<u32>().ok())
166            .unwrap_or(32)
167    })
168}
169
170const JOBS_EVENT_COUNTER_MASK: u64 = 0x0000_0000_FFFF_FFFF;
171const JOBS_EVENT_SLEEPY_SHIFT: u32 = 32;
172const JOBS_EVENT_SLEEPY_INC: u64 = 1u64 << JOBS_EVENT_SLEEPY_SHIFT;
173const JOBS_EVENT_SLEEPY_MASK: u64 = 0x0000_FFFF_0000_0000;
174const JOBS_EVENT_SLEEPING_SHIFT: u32 = 48;
175const JOBS_EVENT_SLEEPING_INC: u64 = 1u64 << JOBS_EVENT_SLEEPING_SHIFT;
176const JOBS_EVENT_SLEEPING_MASK: u64 = 0xFFFF_0000_0000_0000;
177
178#[inline]
179fn unpack_counter(event: u64) -> u32 {
180    (event & JOBS_EVENT_COUNTER_MASK) as u32
181}
182#[inline]
183fn unpack_sleepy(event: u64) -> u32 {
184    ((event & JOBS_EVENT_SLEEPY_MASK) >> JOBS_EVENT_SLEEPY_SHIFT) as u32
185}
186#[inline]
187fn unpack_sleeping(event: u64) -> u32 {
188    ((event & JOBS_EVENT_SLEEPING_MASK) >> JOBS_EVENT_SLEEPING_SHIFT) as u32
189}
190
191struct WorkerSleepState {
192    state: AtomicU8,
193    /// Counter value captured when the worker entered Sleepy. When
194    /// `jobs_event.counter != captured_counter`, new work has been posted
195    /// and the worker drops back to Active — no park needed.
196    captured_counter: AtomicU32,
197    /// Set once the worker thread starts; `submit()` uses this to
198    /// `unpark()` a sleeping worker without holding any lock.
199    thread: OnceLock<thread::Thread>,
200}
201
202impl WorkerSleepState {
203    fn new() -> Self {
204        Self {
205            state: AtomicU8::new(WORKER_ACTIVE),
206            captured_counter: AtomicU32::new(0),
207            thread: OnceLock::new(),
208        }
209    }
210}
211
212struct Shared {
213    injector: Injector<Task>,
214    stealers: Vec<Stealer<Task>>,
215    shutdown: AtomicBool,
216    /// One entry per worker. Lock-free three-state machine.
217    sleep_states: Vec<WorkerSleepState>,
218    /// Packed (counter, num_sleepy, num_sleeping). See module-level
219    /// comment for bit layout. Drives the epoch-based wake that keeps
220    /// fine-grained dispatches syscall-free.
221    jobs_event: AtomicU64,
222}
223
224impl std::fmt::Debug for Shared {
225    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
226        f.debug_struct("Shared")
227            .field("workers", &self.stealers.len())
228            .field("shutdown", &self.shutdown.load(Ordering::Relaxed))
229            .finish_non_exhaustive()
230    }
231}
232
233/// Thread pool with a fixed number of worker threads. Uses per-worker
234/// Chase-Lev deques (via `crossbeam-deque`) + random-victim work-stealing.
235/// Use [`YscvPool::new`] to construct, [`YscvPool::install`] to run work.
236#[derive(Debug)]
237pub struct YscvPool {
238    shared: Arc<Shared>,
239    workers: Vec<thread::JoinHandle<()>>,
240    nthreads: usize,
241}
242
243impl YscvPool {
244    /// Builds a pool with `nthreads` worker threads. Returns `Err` on
245    /// `nthreads == 0` (rayon also rejects that).
246    pub fn new(nthreads: usize) -> Result<Self, PoolError> {
247        if nthreads == 0 {
248            return Err(PoolError::ZeroThreads);
249        }
250
251        // Create one deque per worker; collect the stealer halves into
252        // `shared.stealers` so everyone can steal from everyone.
253        let mut worker_deques: Vec<DequeWorker<Task>> = Vec::with_capacity(nthreads);
254        let mut stealers: Vec<Stealer<Task>> = Vec::with_capacity(nthreads);
255        for _ in 0..nthreads {
256            let w = DequeWorker::new_fifo();
257            stealers.push(w.stealer());
258            worker_deques.push(w);
259        }
260
261        let sleep_states: Vec<WorkerSleepState> =
262            (0..nthreads).map(|_| WorkerSleepState::new()).collect();
263        let shared = Arc::new(Shared {
264            injector: Injector::new(),
265            stealers,
266            shutdown: AtomicBool::new(false),
267            sleep_states,
268            jobs_event: AtomicU64::new(0),
269        });
270
271        // Resolve CPU affinity once at pool construction. Policy from env,
272        // defaulting to `physical` (avoid SMT siblings on symmetric SMT).
273        let pinning = affinity::resolve_pinning(affinity::policy_from_env(), nthreads);
274
275        // Spawn workers. Each owns a `DequeWorker<Task>` (not Send on its
276        // own, but we move it into the spawned thread immediately).
277        let mut workers = Vec::with_capacity(nthreads);
278        for (worker_id, local) in worker_deques.into_iter().enumerate() {
279            let s = Arc::clone(&shared);
280            let cpu = pinning.get(worker_id).copied();
281            workers.push(thread::spawn(move || {
282                if let Some(cpu_id) = cpu {
283                    affinity::pin_current_thread(cpu_id);
284                }
285                // Publish our Thread handle so the waker path can
286                // `unpark()` us without holding any lock.
287                let _ = s.sleep_states[worker_id].thread.set(thread::current());
288                // Record our index in TLS so `current_worker_index()`
289                // can report it to nested-dispatch check sites.
290                CURRENT_WORKER.with(|c| c.set(Some(worker_id)));
291                worker_loop(worker_id, local, s)
292            }));
293        }
294
295        Ok(Self {
296            shared,
297            workers,
298            nthreads,
299        })
300    }
301
302    /// Number of worker threads in this pool.
303    pub fn num_threads(&self) -> usize {
304        self.nthreads
305    }
306
307    /// The caller's worker index within this pool (0..num_threads), or
308    /// `None` if called from a thread that isn't one of our workers
309    /// (e.g. the main thread before `install`, a test thread, a rayon
310    /// worker). Mirrors `rayon::current_thread_index()`.
311    ///
312    /// Note: TLS is process-global, so this returns `Some(i)` on a
313    /// yscv-pool worker even when the function is invoked via a
314    /// different `YscvPool` instance — acceptable because kernels use
315    /// this purely to avoid re-entrant dispatch, and any yscv worker
316    /// is by definition busy.
317    pub fn current_worker_index(&self) -> Option<usize> {
318        CURRENT_WORKER.with(|c| c.get())
319    }
320
321    /// Runs `f` on one of the pool's worker threads and blocks the caller
322    /// until it returns. Matches `rayon::ThreadPool::install` semantics —
323    /// the closure may borrow from the caller's stack.
324    ///
325    /// # Safety
326    ///
327    /// The call blocks until the task completes, so any references captured
328    /// in `f` remain valid for the full task lifetime. To fit the closure
329    /// in the shared `Task` queue (`FnOnce + 'static`), we widen its
330    /// lifetime via `transmute`. Same pattern as `rayon::ThreadPool::install`.
331    pub fn install<F, R>(&self, f: F) -> R
332    where
333        F: FnOnce() -> R + Send,
334        R: Send,
335    {
336        // A″.4: zero heap alloc path. The closure + result channel live
337        // on this stack frame via `InstallCell`; we submit a `JobRef`
338        // pointing at it. Caller blocks on `rx.recv()` until the worker
339        // signals, keeping the stack frame alive for the worker's
340        // dereference.
341        let (tx, rx) = std::sync::mpsc::sync_channel::<R>(1);
342        // Put the closure + sender together so the trampoline can
343        // reconstitute them. Wrapped in `ManuallyDrop` because the
344        // trampoline consumes them via `ptr::read` (matches FnOnce
345        // semantics — the closure is moved out before execution).
346        use std::mem::ManuallyDrop;
347        struct InstallCell<F, R: Send>
348        where
349            F: FnOnce() -> R,
350        {
351            f: ManuallyDrop<F>,
352            tx: ManuallyDrop<std::sync::mpsc::SyncSender<R>>,
353        }
354        #[allow(unsafe_code)]
355        unsafe fn install_trampoline<F, R>(data: *const ())
356        where
357            F: FnOnce() -> R + Send,
358            R: Send,
359        {
360            // SAFETY: `data` was `&cell as *const InstallCell<F, R> as
361            // *const ()`. The caller (`install`) is blocked on `rx`
362            // until we finish, so `cell` is alive. We `ptr::read` F
363            // and the sender — one-shot consume, matching FnOnce.
364            #[allow(unsafe_code)]
365            let cell = unsafe { &*(data as *const InstallCell<F, R>) };
366            #[allow(unsafe_code)]
367            let f = unsafe { std::ptr::read(&*cell.f) };
368            #[allow(unsafe_code)]
369            let tx = unsafe { std::ptr::read(&*cell.tx) };
370            let value = f();
371            let _ = tx.send(value);
372        }
373        let cell = InstallCell {
374            f: ManuallyDrop::new(f),
375            tx: ManuallyDrop::new(tx),
376        };
377        // SAFETY: `install_trampoline::<F, R>` is a `fn` item, `'static`
378        // by definition. `&cell` outlives the blocking `rx.recv()` below,
379        // so the worker's dereference is valid. Same lifetime invariant
380        // as the previous Box-based path.
381        #[allow(unsafe_code)]
382        let job = unsafe {
383            JobRef::new(
384                &cell as *const InstallCell<F, R> as *const (),
385                install_trampoline::<F, R>,
386            )
387        };
388        self.submit(job);
389        rx.recv().expect("worker dropped the result channel")
390    }
391
392    /// Internal: push a task onto the global injector and wake workers.
393    ///
394    /// Three-path fast route:
395    /// 1. Load packed `jobs_event` once. If both `num_sleepy == 0` and
396    ///    `num_sleeping == 0` → push and return (everyone is Active,
397    ///    they'll find the task via steal/injector on their next loop).
398    /// 2. If `num_sleepy > 0` → bump the counter. Sleepy workers are
399    ///    yield-watching it and observe the change without any syscall.
400    /// 3. If `num_sleeping > 0` → scan `sleep_states` for a Sleeping
401    ///    worker, CAS it to Active, and `unpark()`.
402    fn submit(&self, task: Task) {
403        self.shared.injector.push(task);
404        self.notify_workers(1);
405    }
406
407    /// Batch notification path used by `par_for_each_index` after
408    /// pushing N helper tasks. A single `fetch_add(N)` on the counter +
409    /// optionally up to `n` unparks wakes at most `n` Sleeping workers
410    /// instead of doing one `submit` per helper with N cascaded atomic
411    /// RMWs. Measured to save ~50-100 µs per 6T inference on the
412    /// tracker (200 parallel regions × ~6 helpers each = 1200 fewer
413    /// atomic RMWs).
414    fn notify_workers(&self, job_count: usize) {
415        let event = self.shared.jobs_event.load(Ordering::Acquire);
416        let num_sleepy = unpack_sleepy(event);
417        let num_sleeping = unpack_sleeping(event);
418        if num_sleepy == 0 && num_sleeping == 0 {
419            return;
420        }
421        if num_sleepy > 0 {
422            // Single counter increment per notify — Sleepy workers compare
423            // equality, not delta, so one bump is sufficient even for
424            // multi-task batches. Release pairs with workers' Acquire.
425            self.shared.jobs_event.fetch_add(1, Ordering::Release);
426        }
427        if num_sleeping > 0 {
428            // Wake up to `job_count` Sleeping workers via unpark. Without
429            // this bound, a single submit would wake all sleepers when we
430            // only have one task for them. With it, each futex_wake
431            // corresponds to exactly one available task.
432            let wakes_wanted = job_count.min(num_sleeping as usize);
433            let mut woken = 0usize;
434            for st in &self.shared.sleep_states {
435                if woken >= wakes_wanted {
436                    break;
437                }
438                if st.state.load(Ordering::Relaxed) != WORKER_SLEEPING {
439                    continue;
440                }
441                if st
442                    .state
443                    .compare_exchange(
444                        WORKER_SLEEPING,
445                        WORKER_ACTIVE,
446                        Ordering::AcqRel,
447                        Ordering::Relaxed,
448                    )
449                    .is_ok()
450                {
451                    self.shared
452                        .jobs_event
453                        .fetch_sub(JOBS_EVENT_SLEEPING_INC, Ordering::Release);
454                    if let Some(t) = st.thread.get() {
455                        t.unpark();
456                    }
457                    woken += 1;
458                }
459            }
460        }
461    }
462
463    /// Push a batch of tasks onto the injector atomically from the
464    /// caller's perspective (still one-by-one into the lock-free queue,
465    /// but we defer notify to a single atomic update + bounded wake).
466    /// Used by `par_for_each_index` where all helpers share the same
467    /// closure and can be enqueued in one burst.
468    fn submit_batch<I: IntoIterator<Item = Task>>(&self, tasks: I) {
469        let mut count = 0usize;
470        for t in tasks {
471            self.shared.injector.push(t);
472            count += 1;
473        }
474        if count > 0 {
475            self.notify_workers(count);
476        }
477    }
478
479    /// Parallel for-each over `0..count`. Runs `f(index)` on pool workers
480    /// in parallel; blocks until all iterations complete. Equivalent to
481    /// rayon's `(0..count).into_par_iter().for_each(f)`.
482    ///
483    /// Dispatch strategy: **zero `Arc`, no mutex, no condvar**. All shared
484    /// state (the next-index counter and the completion latch) lives on
485    /// this function's stack frame. Helpers receive raw pointers into that
486    /// frame; the function blocks on the latch with a spin→yield loop
487    /// until every helper has finished, guaranteeing the frame outlives
488    /// all accesses. The closure is passed via a `&dyn Fn` trait-object
489    /// pointer — no allocation, no `Arc<ClosureHolder>` layer.
490    ///
491    /// This is the hot path of the pool on inference workloads (100-200
492    /// fine-grained parallel regions per inference). The previous design
493    /// allocated 3 `Arc`s + 1 `Arc<ClosureHolder>` + 4 `Arc::clone`s per
494    /// helper + waited on a `Condvar`. Each of those disappears here; the
495    /// only remaining heap alloc per call is `helpers` `Box`es (required
496    /// by the `Injector<Box<dyn FnOnce>>` task type — addressing that
497    /// would need a custom lock-free queue).
498    ///
499    /// # Safety
500    ///
501    /// This function contains `unsafe` blocks — see the `SAFETY:` comments
502    /// at each site for the invariants. In summary: the function blocks
503    /// on `latch` until every helper decrements it, guaranteeing that
504    /// `next`, `latch`, and the closure `f` all outlive any helper
505    /// access through the raw pointers we hand them.
506    pub fn par_for_each_index<F>(&self, count: usize, f: F)
507    where
508        F: Fn(usize) + Send + Sync,
509    {
510        if count == 0 {
511            return;
512        }
513
514        use std::sync::atomic::AtomicUsize;
515
516        // Stack-allocated shared state. Lives for the duration of this
517        // function's frame. Helpers access via raw pointers.
518        let next = AtomicUsize::new(0);
519
520        // Caller participates — it counts as one puller. Cap helpers at
521        // `count - 1` so we don't oversubscribe workers on tiny counts.
522        let helpers = self.nthreads.min(count.saturating_sub(1));
523
524        // `latch` counts down as each helper exits its loop. Caller waits
525        // until it hits 0. When `helpers == 0` we never touch it.
526        let latch = AtomicUsize::new(helpers);
527
528        // Monomorphized trampoline: `fn(*const (), usize)` — a thin fn
529        // pointer, Send/Sync by value and free of lifetime gymnastics.
530        // The context pointer is `&f as *const F as *const ()`. Each
531        // helper calls `(trampoline)(ctx, idx)` which casts back to
532        // `&F` and invokes. This avoids the `&dyn Fn + '_` fat pointer
533        // and its `F: 'static` bound noise.
534        fn trampoline<F: Fn(usize) + Send + Sync>(ctx: *const (), idx: usize) {
535            // SAFETY: `ctx` was constructed as `&f as *const F as *const ()`
536            // in the parent frame. That frame outlives every call via
537            // the latch/spin invariant documented on the outer function.
538            #[allow(unsafe_code)]
539            let f = unsafe { &*(ctx as *const F) };
540            f(idx);
541        }
542        let f_ctx: *const () = (&f as *const F) as *const ();
543        let f_trampoline: fn(*const (), usize) = trampoline::<F>;
544
545        // All helpers need to see: &AtomicUsize next, &AtomicUsize latch,
546        // and the closure fat pointer. We bundle them in a `Copy`
547        // struct that we mark `Send + Sync` manually — the individual
548        // raw pointers are Send/Sync-safe because of the function-scope
549        // lifetime invariant documented above.
550        #[derive(Clone, Copy)]
551        struct Ptrs {
552            next: *const AtomicUsize,
553            latch: *const AtomicUsize,
554            f_ctx: *const (),
555            f_trampoline: fn(*const (), usize),
556            /// Total index count — embedded here rather than captured by
557            /// the helper trampoline, because trampolines are `fn` items
558            /// (no closure environment).
559            count: usize,
560        }
561        // SAFETY: The pointer fields target data that outlives every
562        // helper task — `next`, `latch`, and the closure `f` all live on
563        // this function's stack frame, which we refuse to exit until
564        // every helper has bumped `latch` down to 0 at the spin-wait
565        // loop at the end of this function. The `AtomicUsize` targets
566        // are race-safe; the closure is `Fn + Sync` so concurrent
567        // invocation is sound. `f_trampoline` is a `fn` item, already
568        // Send+Sync.
569        #[allow(unsafe_code)]
570        unsafe impl Send for Ptrs {}
571        #[allow(unsafe_code)]
572        unsafe impl Sync for Ptrs {}
573
574        // Accessor methods so the spawned closure captures `Ptrs` as a
575        // whole (getting the `unsafe impl Send for Ptrs` stamp) rather
576        // than letting Rust-2021 disjoint field capture strip to the
577        // bare raw pointers, which would fail Send.
578        impl Ptrs {
579            #[inline]
580            fn next(&self) -> *const AtomicUsize {
581                self.next
582            }
583            #[inline]
584            fn latch(&self) -> *const AtomicUsize {
585                self.latch
586            }
587            #[inline]
588            fn call(&self, idx: usize) {
589                (self.f_trampoline)(self.f_ctx, idx);
590            }
591        }
592
593        let ptrs = Ptrs {
594            next: &next as *const AtomicUsize,
595            latch: &latch as *const AtomicUsize,
596            f_ctx,
597            f_trampoline,
598            count,
599        };
600
601        // A″.4: all helpers share the same `Ptrs` on the caller's stack
602        // frame; each worker's `JobRef` is just a pair of pointers
603        // (trampoline fn + &ptrs). Zero heap allocations per helper vs
604        // the prior `Box<dyn FnOnce>` path which cost one `Box::new`
605        // each. The trampoline runs the pull-from-counter / call / latch
606        // dec loop inline.
607        #[allow(unsafe_code)]
608        unsafe fn helper_trampoline(data: *const ()) {
609            // SAFETY: `data` was `&ptrs as *const Ptrs as *const ()`.
610            // The caller (`par_for_each_index`) blocks on `latch` until
611            // every helper decrements it, so `ptrs` and everything it
612            // points to remain valid.
613            #[allow(unsafe_code)]
614            let p = unsafe { *(data as *const Ptrs) };
615            // count is encoded in the caller's stack frame via the
616            // trampoline's closure? — no, trampolines can't capture.
617            // We read count via Ptrs (need to add it).
618            loop {
619                // SAFETY: p.next outlives helper via blocking latch.
620                #[allow(unsafe_code)]
621                let idx = unsafe { (*p.next()).fetch_add(1, Ordering::Relaxed) };
622                if idx >= p.count {
623                    break;
624                }
625                p.call(idx);
626            }
627            // SAFETY: p.latch outlives helper via blocking latch.
628            #[allow(unsafe_code)]
629            unsafe {
630                (*p.latch()).fetch_sub(1, Ordering::Release);
631            }
632        }
633
634        // Build `helpers` copies of the same `JobRef` pointing to the
635        // shared `ptrs` cell. Using a Vec<Task> (= Vec<JobRef>, 16 B
636        // each) here — allocation is once per call, amortized across
637        // all helpers; far cheaper than N Box<dyn FnOnce>.
638        // SAFETY: `helper_trampoline` is a `fn` item (`'static`), and
639        // `&ptrs` outlives the blocking spin-wait below. Same invariant
640        // as the previous Box-based path.
641        #[allow(unsafe_code)]
642        let job = unsafe { JobRef::new(&ptrs as *const Ptrs as *const (), helper_trampoline) };
643        let tasks: Vec<Task> = (0..helpers).map(|_| job).collect();
644        self.submit_batch(tasks);
645
646        // Caller participates — drains indices inline until the counter
647        // is exhausted. Handles `helpers == 0` (count == 1) entirely
648        // here: no helpers were spawned, the caller is the only puller.
649        loop {
650            let idx = next.fetch_add(1, Ordering::Relaxed);
651            if idx >= count {
652                break;
653            }
654            f(idx);
655        }
656
657        if helpers == 0 {
658            return;
659        }
660
661        // Spin-yield wait for all helpers to exit their loops. They'll
662        // hit the drained counter almost immediately since the caller
663        // also pulled — this is pure join overhead. No condvar: the
664        // window here is microseconds, parking on a cvar would cost
665        // more than it saves.
666        //
667        // Acquire: pair with the helpers' Release on `latch.fetch_sub`
668        // so we observe their memory writes before returning.
669        let mut spin = 0u32;
670        while latch.load(Ordering::Acquire) != 0 {
671            if spin < 64 {
672                std::hint::spin_loop();
673                spin += 1;
674            } else {
675                std::thread::yield_now();
676            }
677        }
678    }
679
680    /// Fork-join: run `a` and `b` in parallel, return both results.
681    /// Equivalent to `rayon::join(a, b)`. Implemented by submitting `a`
682    /// to the pool and running `b` inline on the caller's thread.
683    ///
684    /// # Safety
685    ///
686    /// Same lifetime-extension rule as `install` — we block on the result
687    /// channel for `a`, and `b` runs synchronously, so both closures'
688    /// captures remain live.
689    pub fn join<A, B, RA, RB>(&self, a: A, b: B) -> (RA, RB)
690    where
691        A: FnOnce() -> RA + Send,
692        B: FnOnce() -> RB + Send,
693        RA: Send,
694        RB: Send,
695    {
696        // A″.4: stack-allocate the `a` closure + its result sender into
697        // a `JoinCell` and submit a zero-alloc `JobRef`.
698        let (tx_a, rx_a) = std::sync::mpsc::sync_channel::<RA>(1);
699        use std::mem::ManuallyDrop;
700        struct JoinCell<A, RA: Send>
701        where
702            A: FnOnce() -> RA,
703        {
704            a: ManuallyDrop<A>,
705            tx: ManuallyDrop<std::sync::mpsc::SyncSender<RA>>,
706        }
707        #[allow(unsafe_code)]
708        unsafe fn join_trampoline<A, RA>(data: *const ())
709        where
710            A: FnOnce() -> RA + Send,
711            RA: Send,
712        {
713            // SAFETY: `data` points to a stack-allocated `JoinCell<A, RA>`
714            // held alive by the caller blocking on `rx_a.recv()` below.
715            #[allow(unsafe_code)]
716            let cell = unsafe { &*(data as *const JoinCell<A, RA>) };
717            #[allow(unsafe_code)]
718            let a = unsafe { std::ptr::read(&*cell.a) };
719            #[allow(unsafe_code)]
720            let tx = unsafe { std::ptr::read(&*cell.tx) };
721            let _ = tx.send(a());
722        }
723        let cell = JoinCell {
724            a: ManuallyDrop::new(a),
725            tx: ManuallyDrop::new(tx_a),
726        };
727        // SAFETY: `join_trampoline::<A, RA>` is a `fn` item (`'static`).
728        // `&cell` outlives the `rx_a.recv()` below. See install for the
729        // same pattern.
730        #[allow(unsafe_code)]
731        let job = unsafe {
732            JobRef::new(
733                &cell as *const JoinCell<A, RA> as *const (),
734                join_trampoline::<A, RA>,
735            )
736        };
737        self.submit(job);
738        // Run b synchronously on this thread. Uses one less worker =
739        // better CPU utilization during small fork-join patterns.
740        let rb = b();
741        let ra = rx_a.recv().expect("worker dropped join channel");
742        (ra, rb)
743    }
744
745    /// Step 3: enter a session-scoped [`PersistentSection`]. All pool
746    /// workers are held in [`section_worker_loop`] for the duration of
747    /// `f`; regular `submit` / `install` paths are effectively blocked
748    /// during the section (all workers busy). Each
749    /// [`PersistentSection::parallel_for`] call inside the closure
750    /// dispatches work via a single atomic pointer store + chunk-counter
751    /// CAS — no rayon scope creation, no `Box` alloc, no condvar/futex.
752    ///
753    /// Target: the tracker's ~1.6 ms MT-overhead budget. See
754    /// `reflective-fluttering-backus.md` Step 3 for projection.
755    ///
756    /// # Safety
757    ///
758    /// Section and trampoline context are stack-allocated on this
759    /// function's frame. Main thread spins on `workers_remaining` before
760    /// returning, guaranteeing every worker's `section_worker_loop` has
761    /// exited and released the pointer before the stack frame is freed.
762    pub fn enter_section<R, F>(&self, f: F) -> R
763    where
764        F: FnOnce(&PersistentSection) -> R,
765    {
766        let section = PersistentSection::new();
767
768        // Stack-allocated trampoline context — just the section pointer.
769        // Workers read `section_ptr`, cast back to `&PersistentSection`,
770        // run [`section_worker_loop`].
771        #[repr(C)]
772        struct SectionCtx {
773            section_ptr: *const PersistentSection,
774        }
775        // SAFETY: `SectionCtx` holds a pointer to a stack-rooted
776        // `PersistentSection` which outlives every worker dereference
777        // (main thread blocks on `workers_remaining == 0` before
778        // returning). No shared mutable state beyond the section's own
779        // atomics, which are Send/Sync by construction.
780        #[allow(unsafe_code)]
781        unsafe impl Send for SectionCtx {}
782        #[allow(unsafe_code)]
783        unsafe impl Sync for SectionCtx {}
784
785        #[allow(unsafe_code)]
786        unsafe fn section_worker_trampoline(data: *const ()) {
787            // SAFETY: `data` was constructed as `&ctx as *const _` in
788            // `enter_section`. `ctx` lives on the `enter_section` stack
789            // frame, kept alive by the `workers_remaining` spin barrier.
790            #[allow(unsafe_code)]
791            let ctx = unsafe { &*(data as *const SectionCtx) };
792            #[allow(unsafe_code)]
793            let section = unsafe { &*ctx.section_ptr };
794            // SAFETY: see `section` reference above.
795            #[allow(unsafe_code)]
796            unsafe {
797                section::section_worker_loop(section);
798            }
799        }
800
801        let ctx = SectionCtx {
802            section_ptr: &section as *const PersistentSection,
803        };
804
805        // SAFETY: `section_worker_trampoline` is a `fn` item (`'static`).
806        // `&ctx` outlives every worker dereference by the barrier below.
807        #[allow(unsafe_code)]
808        let job = unsafe {
809            JobRef::new(
810                &ctx as *const SectionCtx as *const (),
811                section_worker_trampoline,
812            )
813        };
814
815        // Submit one copy per worker. JobRef is Copy (16 B), so the
816        // Vec is a cheap dense buffer of identical handles.
817        let tasks: Vec<Task> = (0..self.nthreads).map(|_| job).collect();
818        self.submit_batch(tasks);
819
820        // Entry barrier: wait for every worker to pick up its job and
821        // increment `workers_remaining`. Typical time: <10 µs on Zen 4
822        // (workers already Active or in Sleepy). If any worker is
823        // Sleeping, submit_batch's bounded unpark already kicked it.
824        let expected = self.nthreads;
825        let mut spin = 0u32;
826        while section.workers_remaining_count() < expected {
827            if spin < 256 {
828                std::hint::spin_loop();
829                spin = spin.saturating_add(1);
830            } else {
831                std::thread::yield_now();
832            }
833        }
834
835        let result = f(&section);
836
837        // Signal exit. Workers observe `active == false` on their next
838        // loop iteration and `fetch_sub` workers_remaining.
839        section.mark_inactive();
840
841        // Exit barrier: wait for every worker to exit the section
842        // loop. Workers currently in their back-off yield may take a
843        // few µs to observe the flag.
844        let mut spin = 0u32;
845        while section.workers_remaining_count() > 0 {
846            if spin < 256 {
847                std::hint::spin_loop();
848                spin = spin.saturating_add(1);
849            } else {
850                std::thread::yield_now();
851            }
852        }
853
854        result
855    }
856}
857
858impl Drop for YscvPool {
859    fn drop(&mut self) {
860        // Signal shutdown and wake every worker so they exit cleanly.
861        // Each worker has its own Thread handle; unpark them all to
862        // kick any Sleeping ones out of their futex wait.
863        self.shared.shutdown.store(true, Ordering::Release);
864        for st in &self.shared.sleep_states {
865            if let Some(t) = st.thread.get() {
866                t.unpark();
867            }
868        }
869        for handle in self.workers.drain(..) {
870            let _ = handle.join();
871        }
872    }
873}
874
875/// Worker main loop: run own deque tasks first (LIFO for good cache
876/// locality), fall back to injector global queue, then random-victim
877/// steal. Cold-idle spin on empty for `YSCV_POOL_SPIN_US` µs before
878/// falling through to a condvar park.
879fn worker_loop(worker_id: usize, local: DequeWorker<Task>, shared: Arc<Shared>) {
880    let mut steal_rng_state: u32 = 0x9e37_79b1u32.wrapping_mul(worker_id as u32 + 1);
881    let nworkers = shared.stealers.len();
882    let spin_duration = Duration::from_micros(spin_us());
883    let spin_enabled = spin_duration > Duration::ZERO;
884
885    // Step 3 Session C: stash dispatch context in TLS so
886    // `section::section_worker_loop` can call `find_task` to pick up
887    // regular tasks (e.g. `join_dyn` submits from tower-parallel)
888    // while the worker is ALSO processing section chunks. Without this,
889    // tower-parallel graphs deadlock when all workers are spinning on
890    // `section.current_loop` and `join_dyn` submits a task to the
891    // injector with no available worker to pick it up.
892    WORKER_DISPATCH_CTX.with(|cell| {
893        cell.set(Some(WorkerDispatchCtx {
894            local: &local as *const _,
895            shared: Arc::as_ptr(&shared),
896            worker_id,
897            nworkers,
898        }));
899    });
900    // Guard that clears the TLS on worker exit — RAII so it fires on
901    // both normal return and unwinding paths (worker panic would leave
902    // a dangling pointer otherwise).
903    struct ClearDispatchCtxGuard;
904    impl Drop for ClearDispatchCtxGuard {
905        fn drop(&mut self) {
906            WORKER_DISPATCH_CTX.with(|cell| cell.set(None));
907        }
908    }
909    let _dispatch_ctx_guard = ClearDispatchCtxGuard;
910
911    'outer: loop {
912        // Drain local deque first.
913        while let Some(task) = local.pop() {
914            #[allow(unsafe_code)]
915            unsafe {
916                task.execute();
917            }
918        }
919
920        // Try injector + work-stealing.
921        if let Some(task) = find_task(&local, &shared, &mut steal_rng_state, worker_id, nworkers) {
922            #[allow(unsafe_code)]
923            unsafe {
924                task.execute();
925            }
926            continue;
927        }
928
929        if shared.shutdown.load(Ordering::Acquire) {
930            return;
931        }
932
933        // Cold-idle spin (deprecated default: spin_us=0). Still honoured
934        // via env override for callers that want busy-spin instead of
935        // the Sleepy yield-watch below.
936        if spin_enabled {
937            let deadline = Instant::now() + spin_duration;
938            while Instant::now() < deadline {
939                if shared.shutdown.load(Ordering::Acquire) {
940                    return;
941                }
942                if let Some(task) =
943                    find_task(&local, &shared, &mut steal_rng_state, worker_id, nworkers)
944                {
945                    #[allow(unsafe_code)]
946                    unsafe {
947                        task.execute();
948                    }
949                    break;
950                }
951                std::hint::spin_loop();
952            }
953            if let Some(task) =
954                find_task(&local, &shared, &mut steal_rng_state, worker_id, nworkers)
955            {
956                #[allow(unsafe_code)]
957                unsafe {
958                    task.execute();
959                }
960                continue;
961            }
962        }
963
964        // ── Sleepy state (A″.2) ──────────────────────────────────
965        //
966        // Instead of jumping straight to `park`, we enter Sleepy: capture
967        // the current `jobs_event` counter, announce ourselves via the
968        // packed `num_sleepy` field, and yield-watch the counter for
969        // `sleepy_rounds()` iterations. On each iteration we also retry
970        // `find_task` — a submit pushed the job before its counter bump
971        // may be visible already.
972        //
973        // Submit's fast path increments the counter ONLY IF `num_sleepy >
974        // 0`, so our Sleepy announcement is load-bearing: it tells submit
975        // "I'm watching, no syscall needed, just bump the counter". The
976        // counter change propagates via cache coherence in ~50-100 ns —
977        // far cheaper than park/unpark (~1 µs each).
978        let st = &shared.sleep_states[worker_id];
979        let initial_event = shared.jobs_event.load(Ordering::Acquire);
980        let captured = unpack_counter(initial_event);
981        st.captured_counter.store(captured, Ordering::Release);
982        st.state.store(WORKER_SLEEPY, Ordering::Release);
983        shared
984            .jobs_event
985            .fetch_add(JOBS_EVENT_SLEEPY_INC, Ordering::Release);
986
987        let rounds = sleepy_rounds();
988        let mut woken_by_counter = false;
989        // `yield_now` (sched_yield on Linux, ~300 ns) spreads the load
990        // across other runnable threads and — measured — outperforms
991        // tight `spin_loop` here. The bottleneck on tracker workloads
992        // isn't the yield cost, it's the cache-coherence ping-pong on
993        // `jobs_event` if 6 workers hammer the atomic in a tight loop.
994        // yield_now gives the cache line a chance to quiesce between
995        // reads.
996        for _ in 0..rounds {
997            thread::yield_now();
998
999            let cur = unpack_counter(shared.jobs_event.load(Ordering::Acquire));
1000            if cur != captured {
1001                woken_by_counter = true;
1002                break;
1003            }
1004            if shared.shutdown.load(Ordering::Acquire) {
1005                shared
1006                    .jobs_event
1007                    .fetch_sub(JOBS_EVENT_SLEEPY_INC, Ordering::Release);
1008                st.state.store(WORKER_ACTIVE, Ordering::Release);
1009                return;
1010            }
1011            // Opportunistic find_task — some submits may race the
1012            // counter bump (pushed but counter not yet incremented).
1013            if let Some(task) =
1014                find_task(&local, &shared, &mut steal_rng_state, worker_id, nworkers)
1015            {
1016                shared
1017                    .jobs_event
1018                    .fetch_sub(JOBS_EVENT_SLEEPY_INC, Ordering::Release);
1019                st.state.store(WORKER_ACTIVE, Ordering::Release);
1020                #[allow(unsafe_code)]
1021                unsafe {
1022                    task.execute();
1023                }
1024                continue 'outer;
1025            }
1026        }
1027
1028        // Leave Sleepy. Either the counter moved (woken_by_counter) or we
1029        // exhausted the window (truly idle → go Sleeping).
1030        shared
1031            .jobs_event
1032            .fetch_sub(JOBS_EVENT_SLEEPY_INC, Ordering::Release);
1033        if woken_by_counter {
1034            st.state.store(WORKER_ACTIVE, Ordering::Release);
1035            continue;
1036        }
1037
1038        // ── Sleeping state ───────────────────────────────────────
1039        //
1040        // Truly idle past the Sleepy window. CAS Sleepy → Sleeping; if
1041        // submit raced in and already flipped us to Active, skip the park.
1042        if st
1043            .state
1044            .compare_exchange(
1045                WORKER_SLEEPY,
1046                WORKER_SLEEPING,
1047                Ordering::AcqRel,
1048                Ordering::Acquire,
1049            )
1050            .is_err()
1051        {
1052            // submit flipped us to Active — re-loop.
1053            continue;
1054        }
1055        shared
1056            .jobs_event
1057            .fetch_add(JOBS_EVENT_SLEEPING_INC, Ordering::Release);
1058
1059        // Recheck for work + shutdown before parking (closes the race
1060        // where submit pushed work between our Sleepy exit and Sleeping
1061        // entry).
1062        let quick_work = find_task(&local, &shared, &mut steal_rng_state, worker_id, nworkers);
1063        if quick_work.is_some() || shared.shutdown.load(Ordering::Acquire) {
1064            if st
1065                .state
1066                .compare_exchange(
1067                    WORKER_SLEEPING,
1068                    WORKER_ACTIVE,
1069                    Ordering::AcqRel,
1070                    Ordering::Relaxed,
1071                )
1072                .is_ok()
1073            {
1074                shared
1075                    .jobs_event
1076                    .fetch_sub(JOBS_EVENT_SLEEPING_INC, Ordering::Release);
1077            }
1078            if let Some(task) = quick_work {
1079                #[allow(unsafe_code)]
1080                unsafe {
1081                    task.execute();
1082                }
1083            }
1084            if shared.shutdown.load(Ordering::Acquire) {
1085                return;
1086            }
1087            continue;
1088        }
1089
1090        // Blocking park. submit wakes via unpark; 1 ms timeout is a
1091        // safety net (rarely fires in practice once Sleepy catches the
1092        // fast path).
1093        thread::park_timeout(Duration::from_millis(1));
1094        if st
1095            .state
1096            .compare_exchange(
1097                WORKER_SLEEPING,
1098                WORKER_ACTIVE,
1099                Ordering::AcqRel,
1100                Ordering::Relaxed,
1101            )
1102            .is_ok()
1103        {
1104            shared
1105                .jobs_event
1106                .fetch_sub(JOBS_EVENT_SLEEPING_INC, Ordering::Release);
1107        }
1108        if shared.shutdown.load(Ordering::Acquire) {
1109            return;
1110        }
1111    }
1112}
1113
1114/// Find a task to run: injector first, then steal from a random peer.
1115/// Xorshift32 RNG for the victim pick — avoids a hot shared counter
1116/// while still giving reasonable spread.
1117pub(crate) fn find_task(
1118    local: &DequeWorker<Task>,
1119    shared: &Shared,
1120    rng: &mut u32,
1121    worker_id: usize,
1122    nworkers: usize,
1123) -> Option<Task> {
1124    // Try the injector — pumps a batch into our local deque if full.
1125    loop {
1126        match shared.injector.steal_batch_and_pop(local) {
1127            Steal::Success(t) => return Some(t),
1128            Steal::Empty => break,
1129            Steal::Retry => continue,
1130        }
1131    }
1132
1133    // Random-victim steal.
1134    for _ in 0..(nworkers * 2) {
1135        // xorshift32.
1136        *rng ^= *rng << 13;
1137        *rng ^= *rng >> 17;
1138        *rng ^= *rng << 5;
1139        let victim = (*rng as usize) % nworkers;
1140        if victim == worker_id {
1141            continue;
1142        }
1143        match shared.stealers[victim].steal_batch_and_pop(local) {
1144            Steal::Success(t) => return Some(t),
1145            Steal::Empty => {}
1146            Steal::Retry => {}
1147        }
1148    }
1149    None
1150}
1151
1152/// Errors returned by [`YscvPool::new`].
1153#[derive(Debug, Clone, PartialEq, Eq)]
1154pub enum PoolError {
1155    /// `nthreads == 0`.
1156    ZeroThreads,
1157}
1158
1159impl std::fmt::Display for PoolError {
1160    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1161        match self {
1162            PoolError::ZeroThreads => write!(f, "thread count must be > 0"),
1163        }
1164    }
1165}
1166
1167impl std::error::Error for PoolError {}
1168
1169#[cfg(test)]
1170mod tests;