Skip to main content

waratah_storage/
worker_pool.rs

1//! Fixed-resident worker pool for the storage layer's parallel walks.
2//!
3//! Storage parallel-walk mechanisms (the registry seek walk, the domain-scan
4//! parallel walks, and any later sibling) need worker threads for the
5//! duration of one call. Spawning them on demand with `std::thread::scope`
6//! looks free, but scoped children **inherit the creating thread's CPU
7//! affinity mask**. Under the serve-core affinity setup
8//! (`WARATAH_SERVE_CORES`, `waratah_bin/src/affinity.rs`) the calling
9//! thread is a tokio runtime worker pinned to one core, so every scoped
10//! walker lands on that same core and time-slices it — measured on a real
11//! standalone server: a registry resolve stage of 189.5 ms with K=1 and
12//! 190.0 ms with K=4 pinned, versus 189.0 → 75.5 ms (2.5×) with the serve
13//! core set off.
14//!
15//! This pool fixes that by creating its threads **once per process** and
16//! giving each a core placement that never changes:
17//!
18//! - each pool thread is assigned a serving core round-robin
19//!   (`worker slot i → cores[i % cores.len()]`) at pool creation and
20//!   self-pins as its first statement (`sched_setaffinity` on its own
21//!   thread id), then never migrates. A worker that panics is retired and
22//!   replaced with a fresh thread on the same core;
23//! - concurrency is bounded by the pool width (the queue is the
24//!   backpressure), so callers do not need a separate permit mechanism;
25//! - work units own their inputs and return owned outputs. The pool
26//!   outlives individual calls, so units may not borrow caller state; this
27//!   is sound by construction and the per-unit data copy is small against
28//!   the I/O each unit performs;
29//! - every worker queue is FIFO with no priority lanes. Units are bounded
30//!   at construction (the registry walk's 16-group `MIN` rule, the domain
31//!   walks' per-constraint slices), which bounds the time a small unit
32//!   waits behind a big one.
33//!
34//! Dispatch assigns unit `j` of one call to slot
35//! `(counter.fetch_add(units) + j) % width`, so concurrent bursts
36//! interleave their round-robin windows across the pool instead of stacking
37//! on the same workers. A unit that panics is caught per unit, reported as
38//! [`UnitOutcome::Panicked`], and that one worker is replaced; every other
39//! unit and thread is unaffected.
40//!
41//! ## Initialization and the scoped fallback
42//!
43//! The pool is installed once per process with [`init_worker_pool`] (explicit
44//! core placement, used by `waratah_bin`) or [`init_worker_pool_from_env`]
45//! (parses `WARATAH_SERVE_CORES`; used by the `waratah-partition` and
46//! `waratah-registry` child processes). Both calls are idempotent.
47//! `WARATAH_STORAGE_POOL_THREADS` overrides the width over either default.
48//!
49//! A process that never initializes the pool — unit tests, batch tools
50//! such as `waratah import --offline`, any unforeseen embedding — falls back
51//! to the previous `std::thread::scope` spawn in [`run_units`]. The fallback
52//! keeps those callers working without setup; it does not get the affinity
53//! fix, and [`effective_width`] reports no width limit for it.
54//!
55//! ## Topology drift
56//!
57//! Placement is derived from the startup topology and never re-derived.
58//! Revisit this (add a TTL, re-derive the serve set, or re-pin dynamically)
59//! if Waratah ever runs under containerized dynamic cpusets or CPU hotplug:
60//! a worker stranded on a core the kernel no longer schedules would silently
61//! serialize every parallel walk, exactly the failure the serve-core
62//! affinity produced for scoped walkers.
63//!
64//! ## Panic policy
65//!
66//! Each unit runs under `catch_unwind` inside its worker. A panic does not
67//! unwind into the caller (the old `thread::scope` behavior) and does not
68//! poison the pool: the outcome carries the payload text, and the worker is
69//! retired and replaced because a panicked thread's state is unknown. A
70//! later dispatch runs normally. `dispatch` also guarantees one outcome per
71//! unit even if the report glue around the unit unwinds — the job body
72//! catches that too and delivers a synthetic `Panicked` outcome, because a
73//! missing report would block the dispatcher on its receive forever.
74
75use std::any::Any;
76use std::cell::Cell;
77use std::collections::VecDeque;
78use std::panic::{AssertUnwindSafe, catch_unwind};
79use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
80use std::sync::{Arc, Condvar, Mutex, OnceLock};
81use std::thread;
82
83/// Serve-core environment variable (`WARATAH_SERVE_CORES`), shared by the
84/// process launcher and the storage children.
85pub const SERVE_CORES_ENV: &str = "WARATAH_SERVE_CORES";
86
87/// Pool-width override (`WARATAH_STORAGE_POOL_THREADS`); unset / invalid
88/// keeps the caller's default.
89pub const POOL_THREADS_ENV: &str = "WARATAH_STORAGE_POOL_THREADS";
90
91/// Thread-name prefix; worker slot `i` is `waratah-pool-i`. Stable thread
92/// ids and names make traces and profiles readable (the old scope-spawn
93/// code churned a fresh set of thread ids per parallel resolve).
94const POOL_THREAD_NAME_PREFIX: &str = "waratah-pool";
95
96/// Upper bound on a parsed core id: the kernel's `cpu_set_t` width on
97/// Linux, a conservative fixed bound elsewhere.
98#[cfg(target_os = "linux")]
99const MAX_POOL_CORE_ID: usize = libc::CPU_SETSIZE as usize - 1;
100#[cfg(not(target_os = "linux"))]
101const MAX_POOL_CORE_ID: usize = 1023;
102
103/// One unit of work executed by the storage worker pool.
104///
105/// Units own everything they touch: the pool outlives any single call, so a
106/// unit cannot borrow caller state. Return values are handed back to the
107/// dispatcher in unit order.
108pub trait PoolUnit: Send + 'static {
109    /// The unit's result, returned positionally by [`run_units`].
110    type Output: Send + 'static;
111
112    /// Run the unit to completion on a pool worker thread.
113    fn execute(self) -> Self::Output;
114}
115
116/// What became of one dispatched unit.
117pub enum UnitOutcome<P> {
118    /// The unit ran and returned its output.
119    Ok(P),
120    /// The unit panicked. The string is the panic payload for diagnostics;
121    /// the pool recycled the worker that ran it.
122    Panicked(String),
123}
124
125/// One type-erased job: returns `true` when the unit it ran panicked, so
126/// the worker knows to recycle itself.
127type Job = Box<dyn FnOnce() -> bool + Send + 'static>;
128
129/// The process-wide pool, installed once by [`init_worker_pool`] or
130/// [`init_worker_pool_from_env`].
131static POOL: OnceLock<WorkerPool> = OnceLock::new();
132
133// Marks a thread that is itself a pool worker. A nested `run_units` from
134// a worker runs its units inline instead of queueing them behind the
135// caller's own blocked join (which could stall the whole pool).
136thread_local! {
137    static IN_POOL_WORKER: Cell<bool> = const { Cell::new(false) };
138}
139
140/// Round-robin assignment cursor shared by every dispatch in the process.
141/// Concurrent bursts advance it by their unit count, so successive calls
142/// start at different workers instead of all stacking on slot zero.
143static ASSIGNMENT: AtomicUsize = AtomicUsize::new(0);
144
145/// One worker's FIFO queue. The queue outlives its worker: on panic the
146/// worker replaces itself with a fresh thread that drains the same queue, so
147/// jobs already queued are never lost.
148struct WorkQueue {
149    jobs: Mutex<VecDeque<Job>>,
150    ready: Condvar,
151}
152
153impl WorkQueue {
154    fn push(&self, job: Job) {
155        let mut jobs = self
156            .jobs
157            .lock()
158            .unwrap_or_else(|poisoned| poisoned.into_inner());
159        jobs.push_back(job);
160        drop(jobs);
161        self.ready.notify_one();
162    }
163
164    /// Block for the next job. Returns `None` once the pool is shutting down
165    /// and the queue is drained.
166    fn next(&self, shutdown: &AtomicBool) -> Option<Job> {
167        let mut jobs = self
168            .jobs
169            .lock()
170            .unwrap_or_else(|poisoned| poisoned.into_inner());
171        loop {
172            if let Some(job) = jobs.pop_front() {
173                return Some(job);
174            }
175            if shutdown.load(Ordering::Acquire) {
176                return None;
177            }
178            jobs = self
179                .ready
180                .wait(jobs)
181                .unwrap_or_else(|poisoned| poisoned.into_inner());
182        }
183    }
184}
185
186/// State shared by every worker of one pool: shutdown flag and the panic
187/// counter kept for diagnostics.
188struct PoolShared {
189    shutdown: AtomicBool,
190    panics: AtomicUsize,
191}
192
193impl PoolShared {
194    fn note_panic(&self) {
195        let count = self.panics.fetch_add(1, Ordering::Relaxed) + 1;
196        // One warning per process: a repeated panic storm is already
197        // reflected in the counter, and one line is enough to point at it.
198        static WARNED: OnceLock<()> = OnceLock::new();
199        if WARNED.set(()).is_ok() {
200            eprintln!(
201                "waratah-storage: a worker pool unit panicked (panic #{count}); \
202                 the panicked worker thread is being replaced"
203            );
204        }
205    }
206}
207
208/// A fixed-resident pool of worker threads, each with a stable core
209/// placement (or none, when created unpinned).
210struct WorkerPool {
211    queues: Vec<Arc<WorkQueue>>,
212    shared: Arc<PoolShared>,
213}
214
215impl WorkerPool {
216    /// Create the pool and start every worker. `width` is floored at one;
217    /// `cores` empty or `None` leaves workers on the inherited mask.
218    fn new(cores: Option<Vec<usize>>, width: usize) -> Self {
219        let width = width.max(1);
220        let cores = cores.filter(|list| !list.is_empty());
221        let shared = Arc::new(PoolShared {
222            shutdown: AtomicBool::new(false),
223            panics: AtomicUsize::new(0),
224        });
225        let mut queues = Vec::with_capacity(width);
226        for slot in 0..width {
227            let queue = Arc::new(WorkQueue {
228                jobs: Mutex::new(VecDeque::new()),
229                ready: Condvar::new(),
230            });
231            let core = cores.as_ref().map(|list| list[slot % list.len()]);
232            let worker_queue = Arc::clone(&queue);
233            let worker_shared = Arc::clone(&shared);
234            thread::Builder::new()
235                .name(format!("{POOL_THREAD_NAME_PREFIX}-{slot}"))
236                .spawn(move || worker_loop(worker_queue, core, worker_shared, slot))
237                .expect("spawn storage worker pool thread");
238            queues.push(queue);
239        }
240        Self { queues, shared }
241    }
242
243    /// Run every unit on the pool and return one outcome per unit, in unit
244    /// order.
245    ///
246    /// The one-outcome-per-unit guarantee holds even against a panic in the
247    /// report glue itself: the job body catches its own unwind and delivers
248    /// a synthetic `Panicked` outcome, so a dispatcher can never block on a
249    /// missing report (see the panic policy in the module docs).
250    fn dispatch<U: PoolUnit>(&self, units: Vec<U>) -> Vec<UnitOutcome<U::Output>> {
251        let count = units.len();
252        let (tx, rx) = std::sync::mpsc::channel::<(usize, UnitOutcome<U::Output>)>();
253        let start = ASSIGNMENT.fetch_add(count, Ordering::Relaxed);
254        for (index, unit) in units.into_iter().enumerate() {
255            let queue = Arc::clone(&self.queues[(start + index) % self.queues.len()]);
256            let reply = tx.clone();
257            // Separate handle for the recovery arm below: the primary
258            // `reply` is moved into the job body, so the unwind path needs
259            // its own sender to deliver the synthetic outcome.
260            let recovery_reply = reply.clone();
261            queue.push(Box::new(move || {
262                // The dispatcher blocks on `recv` once per unit, so the job
263                // must deliver exactly one outcome even if the report path
264                // itself unwinds — that is this inner catch. A panic in
265                // `run_unit`'s glue (not the unit, which `run_unit` already
266                // caught) reaches this recovery arm, which sends a
267                // synthetic `Panicked` so the dispatcher unblocks and
268                // flags the worker as poisoned via the `true` return.
269                match catch_unwind(AssertUnwindSafe(|| {
270                    let outcome = run_unit(unit);
271                    let panicked = matches!(outcome, UnitOutcome::Panicked(_));
272                    // The receiver drops the message only if the dispatcher
273                    // is gone, which cannot happen while it waits below.
274                    let _ = reply.send((index, outcome));
275                    panicked
276                })) {
277                    Ok(panicked) => panicked,
278                    Err(_) => {
279                        let _ = recovery_reply.send((
280                            index,
281                            UnitOutcome::Panicked(String::from(
282                                "worker pool: the unit report path itself panicked",
283                            )),
284                        ));
285                        true
286                    }
287                }
288            }));
289        }
290        drop(tx);
291        let mut slots: Vec<Option<UnitOutcome<U::Output>>> = (0..count).map(|_| None).collect();
292        for _ in 0..count {
293            let (index, outcome) = rx
294                .recv()
295                .expect("worker pool dispatch channel closed before every unit reported");
296            slots[index] = Some(outcome);
297        }
298        slots
299            .into_iter()
300            .map(|slot| slot.expect("worker pool unit reported exactly once"))
301            .collect()
302    }
303}
304
305impl Drop for WorkerPool {
306    fn drop(&mut self) {
307        // Workers are detached; setting the flag and waking them lets each
308        // drain its queue and exit. The process-lifetime pool never drops;
309        // this is for tests and for a construction that lost the install race.
310        self.shared.shutdown.store(true, Ordering::Release);
311        for queue in &self.queues {
312            // Notify while holding the queue mutex: `next` checks the flag
313            // and enters `wait` inside that same mutex, so a worker sitting
314            // between its flag check and `wait` entry is serialized behind
315            // this lock — after it acquires the mutex it re-checks the flag,
316            // sees shutdown, and exits instead of missing the wake and
317            // sleeping until process exit.
318            let _jobs = queue
319                .jobs
320                .lock()
321                .unwrap_or_else(|poisoned| poisoned.into_inner());
322            queue.ready.notify_all();
323        }
324    }
325}
326
327/// One worker thread's whole life: pin, then drain this slot's queue until
328/// shutdown. A panicked unit retires this thread and starts a replacement
329/// on the same queue and core, so queued work is never stranded.
330fn worker_loop(queue: Arc<WorkQueue>, core: Option<usize>, shared: Arc<PoolShared>, slot: usize) {
331    IN_POOL_WORKER.with(|in_pool| in_pool.set(true));
332    if let Some(core) = core {
333        pin_current_thread(core, slot);
334    }
335    while let Some(job) = queue.next(&shared.shutdown) {
336        let panicked = match catch_unwind(AssertUnwindSafe(job)) {
337            Ok(panicked) => panicked,
338            Err(payload) => {
339                // Unreachable while the job body's own catch holds — it
340                // delivers every unit's outcome and returns instead of
341                // re-raising. Kept as the last line of defense: a future
342                // edit that let a job unwind would otherwise strand a
343                // dispatcher on `recv` forever. Treat the worker as
344                // poisoned so the thread state is not trusted further.
345                let _ = payload;
346                true
347            }
348        };
349        if panicked {
350            shared.note_panic();
351            let replacement_queue = Arc::clone(&queue);
352            let replacement_shared = Arc::clone(&shared);
353            let spawned = thread::Builder::new()
354                .name(format!("{POOL_THREAD_NAME_PREFIX}-{slot}"))
355                .spawn(move || worker_loop(replacement_queue, core, replacement_shared, slot));
356            match spawned {
357                Ok(_) => return,
358                Err(error) => {
359                    // No replacement thread: keep draining this queue on the
360                    // current thread rather than stranding already-queued
361                    // jobs (a dispatcher would wait for them forever).
362                    eprintln!(
363                        "waratah-storage: worker pool could not replace panicked worker \
364                         {slot} ({error}); it keeps serving its queue"
365                    );
366                }
367            }
368        }
369    }
370}
371
372/// Run one unit with its panic caught. This is the only place a unit's
373/// panic is turned into data; both dispatch paths use it.
374fn run_unit<U: PoolUnit>(unit: U) -> UnitOutcome<U::Output> {
375    match catch_unwind(AssertUnwindSafe(|| unit.execute())) {
376        Ok(output) => UnitOutcome::Ok(output),
377        Err(payload) => UnitOutcome::Panicked(panic_message(payload.as_ref())),
378    }
379}
380
381/// Best-effort text for a panic payload (`panic!("…")`, `assert!`, …).
382fn panic_message(payload: &(dyn Any + Send)) -> String {
383    if let Some(text) = payload.downcast_ref::<&str>() {
384        (*text).to_owned()
385    } else if let Some(text) = payload.downcast_ref::<String>() {
386        text.clone()
387    } else {
388        "panic payload is not a string".to_owned()
389    }
390}
391
392/// Run every unit to completion, returning one outcome per unit in unit
393/// order.
394///
395/// With an installed pool, units run on its fixed workers (distinct workers
396/// for a burst up to the pool width). Without one, a `std::thread::scope`
397/// spawn preserves the historical behavior for tests and batch tools. A
398/// nested call from a pool worker runs inline to avoid queueing work behind
399/// its own blocked join.
400pub fn run_units<U: PoolUnit>(units: Vec<U>) -> Vec<UnitOutcome<U::Output>> {
401    if units.is_empty() {
402        return Vec::new();
403    }
404    if IN_POOL_WORKER.with(Cell::get) {
405        return units.into_iter().map(run_unit).collect();
406    }
407    match POOL.get() {
408        Some(pool) => pool.dispatch(units),
409        None => scope_fallback(units),
410    }
411}
412
413/// The pre-pool behavior: one scoped thread per unit. Used only until a
414/// process installs its pool.
415fn scope_fallback<U: PoolUnit>(units: Vec<U>) -> Vec<UnitOutcome<U::Output>> {
416    thread::scope(|scope| {
417        let handles: Vec<_> = units
418            .into_iter()
419            .map(|unit| scope.spawn(move || run_unit(unit)))
420            .collect();
421        handles
422            .into_iter()
423            .map(|handle| {
424                handle.join().unwrap_or_else(|payload| {
425                    UnitOutcome::Panicked(panic_message(payload.as_ref()))
426                })
427            })
428            .collect()
429    })
430}
431
432/// Width a parallel walk may use: the installed pool's width, or
433/// `usize::MAX` when no pool exists (the scoped fallback spawns one thread
434/// per unit, as before).
435pub fn effective_width() -> usize {
436    POOL.get().map_or(usize::MAX, |pool| pool.queues.len())
437}
438
439/// Slice count for a parallel walk whose caller did not request an explicit
440/// worker count: the installed pool's width, or `available_parallelism()`
441/// when no pool exists. Serving processes install their pool at startup —
442/// before any walk can resolve its execution mode — so the value is always
443/// the installed width there (including a [`POOL_THREADS_ENV`] override).
444/// The no-pool branch covers unit tests, batch tools such as
445/// `waratah import --offline`, and embeddings: their [`run_units`] fallback
446/// spawns one scoped thread per slice, so the machine's parallelism is the
447/// natural width. [`effective_width`] cannot be used for this: its no-pool
448/// `usize::MAX` is a "no width limit" report, not a slice count.
449pub fn default_walk_width() -> usize {
450    match POOL.get() {
451        Some(pool) => pool.queues.len(),
452        None => default_unpinned_width(),
453    }
454}
455
456/// Install the process-wide pool with explicit core placement.
457///
458/// `cores` is the resolved serve core set (`None` for unpinned: workers
459/// inherit the process mask); `width` is the default thread count before
460/// [`POOL_THREADS_ENV`] overrides it. Idempotent: a repeated call keeps the
461/// first pool.
462pub fn init_worker_pool(cores: Option<&[usize]>, width: usize) {
463    let width = pool_threads_override().unwrap_or(width.max(1));
464    install(cores.map(<[usize]>::to_vec), width);
465}
466
467/// Install the process-wide pool from `WARATAH_SERVE_CORES` (the value the
468/// launcher writes into each storage child's environment).
469///
470/// Unset, `off`, `false`, and any invalid spec (including `auto`) run
471/// unpinned; a core-list spec (`6`, `4-7`, `2,3,6-8`) pins workers
472/// round-robin over it. The width defaults to the core count when pinned
473/// and to `available_parallelism()` otherwise; [`POOL_THREADS_ENV`]
474/// overrides either. Idempotent.
475pub fn init_worker_pool_from_env() {
476    let (cores, default_width) = match parse_serve_cores(std::env::var(SERVE_CORES_ENV).ok()) {
477        ServeCoreSpec::Off => (None, default_unpinned_width()),
478        ServeCoreSpec::Set(cores) => {
479            let width = cores.len();
480            (Some(cores), width)
481        }
482        ServeCoreSpec::Invalid(raw) => {
483            eprintln!(
484                "waratah-storage: ignoring invalid {SERVE_CORES_ENV}={raw:?}: use a core \
485                 list (e.g. 4-7) or off; the worker pool runs unpinned"
486            );
487            (None, default_unpinned_width())
488        }
489    };
490    let width = pool_threads_override().unwrap_or(default_width.max(1));
491    install(cores, width);
492}
493
494/// Store `pool` as the process-wide pool; a later call is a no-op.
495fn install(cores: Option<Vec<usize>>, width: usize) {
496    if POOL.get().is_some() {
497        #[cfg(debug_assertions)]
498        eprintln!("waratah-storage: worker pool already initialized; ignoring the repeated call");
499        return;
500    }
501    if POOL.set(WorkerPool::new(cores, width)).is_err() {
502        // Another thread installed its pool first; that one is the process
503        // pool. The rejected pool's threads exit through its `Drop`.
504    }
505}
506
507/// Width default for an unpinned process.
508fn default_unpinned_width() -> usize {
509    thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get)
510}
511
512/// Parsed `WARATAH_SERVE_CORES` value.
513enum ServeCoreSpec {
514    /// Unset or an `off`/`false` token: no pinning.
515    Off,
516    /// A valid core list, sorted ascending and deduplicated.
517    Set(Vec<usize>),
518    /// Anything else (`auto` included), kept for the warning text.
519    Invalid(String),
520}
521
522fn parse_serve_cores(raw: Option<String>) -> ServeCoreSpec {
523    let Some(raw) = raw else {
524        return ServeCoreSpec::Off;
525    };
526    let trimmed = raw.trim();
527    if trimmed.eq_ignore_ascii_case("off") || trimmed.eq_ignore_ascii_case("false") {
528        return ServeCoreSpec::Off;
529    }
530    match parse_core_list(trimmed) {
531        Some(cores) => ServeCoreSpec::Set(cores),
532        None => ServeCoreSpec::Invalid(raw),
533    }
534}
535
536/// Parse a core-list spec: single cores and inclusive ranges, comma
537/// separated (`6`, `4-7`, `2,3,6-8`). Order-insensitive; duplicates
538/// collapse; ranges merge. `None` for empty elements, non-numeric or
539/// reversed ranges, and ids above the kernel's `cpu_set_t` width.
540///
541/// This mirrors the launcher's parser in `waratah_bin/src/affinity.rs`.
542/// Storage parses on its own because the child processes must understand
543/// the spec the launcher writes into their environment without depending on
544/// the launcher crate.
545fn parse_core_list(spec: &str) -> Option<Vec<usize>> {
546    let mut cores = std::collections::BTreeSet::new();
547    for part in spec.split(',') {
548        let part = part.trim();
549        if part.is_empty() {
550            return None;
551        }
552        match part.split_once('-') {
553            Some((low, high)) => {
554                let low: usize = low.trim().parse().ok()?;
555                let high: usize = high.trim().parse().ok()?;
556                if low > high || high > MAX_POOL_CORE_ID {
557                    return None;
558                }
559                cores.extend(low..=high);
560            }
561            None => {
562                let core: usize = part.parse().ok()?;
563                if core > MAX_POOL_CORE_ID {
564                    return None;
565                }
566                cores.insert(core);
567            }
568        }
569    }
570    if cores.is_empty() {
571        None
572    } else {
573        Some(cores.into_iter().collect())
574    }
575}
576
577/// `WARATAH_STORAGE_POOL_THREADS` override, if set to a valid count.
578fn pool_threads_override() -> Option<usize> {
579    pool_threads_from_env(std::env::var(POOL_THREADS_ENV).ok().as_deref())
580}
581
582/// Parse one [`POOL_THREADS_ENV`] value; `0` / junk warn and return `None`.
583fn pool_threads_from_env(raw: Option<&str>) -> Option<usize> {
584    let raw = raw?;
585    match raw.trim().parse::<usize>() {
586        Ok(width) if width >= 1 => Some(width),
587        _ => {
588            eprintln!(
589                "waratah-storage: ignoring invalid {POOL_THREADS_ENV}={raw:?} (expected a \
590                 thread count >= 1); using the default width"
591            );
592            None
593        }
594    }
595}
596
597/// Pin the calling thread to `core` as its first action (best-effort). A
598/// refused request leaves the thread on its inherited mask; the pool keeps
599/// working, just without the placement guarantee.
600#[cfg(target_os = "linux")]
601fn pin_current_thread(core: usize, slot: usize) {
602    if core > MAX_POOL_CORE_ID {
603        eprintln!(
604            "waratah-storage: worker pool core {core} is outside the kernel CPU set; \
605             worker {slot} stays unpinned"
606        );
607        return;
608    }
609    let mut mask: libc::cpu_set_t = unsafe { std::mem::zeroed() };
610    unsafe {
611        libc::CPU_ZERO(&mut mask);
612        libc::CPU_SET(core, &mut mask);
613    }
614    let rc = unsafe { libc::sched_setaffinity(0, std::mem::size_of::<libc::cpu_set_t>(), &mask) };
615    if rc != 0 {
616        let error = std::io::Error::last_os_error();
617        eprintln!(
618            "waratah-storage: worker pool could not pin worker {slot} to core {core}: \
619             {error}; it keeps the inherited mask"
620        );
621    }
622}
623
624#[cfg(not(target_os = "linux"))]
625fn pin_current_thread(_core: usize, _slot: usize) {}
626
627#[cfg(test)]
628mod tests {
629    use std::sync::Mutex as StdMutex;
630
631    use super::*;
632
633    struct Echo(u32);
634
635    impl PoolUnit for Echo {
636        type Output = u32;
637
638        fn execute(self) -> u32 {
639            self.0
640        }
641    }
642
643    struct Named;
644
645    impl PoolUnit for Named {
646        type Output = String;
647
648        fn execute(self) -> String {
649            thread::current().name().unwrap_or_default().to_owned()
650        }
651    }
652
653    struct Record(u32, Arc<StdMutex<Vec<u32>>>);
654
655    impl PoolUnit for Record {
656        type Output = ();
657
658        fn execute(self) {
659            self.1.lock().unwrap().push(self.0);
660        }
661    }
662
663    struct MaybeBoom(u32, bool);
664
665    impl PoolUnit for MaybeBoom {
666        type Output = u32;
667
668        fn execute(self) -> u32 {
669            if self.1 {
670                panic!("boom marker");
671            }
672            self.0
673        }
674    }
675
676    struct Nested;
677
678    impl PoolUnit for Nested {
679        type Output = u32;
680
681        fn execute(self) -> u32 {
682            match run_units(vec![Echo(5)]).remove(0) {
683                UnitOutcome::Ok(value) => value,
684                UnitOutcome::Panicked(message) => panic!("nested unit panicked: {message}"),
685            }
686        }
687    }
688
689    fn outputs(outcomes: Vec<UnitOutcome<u32>>) -> Vec<u32> {
690        outcomes
691            .into_iter()
692            .map(|outcome| match outcome {
693                UnitOutcome::Ok(value) => value,
694                UnitOutcome::Panicked(message) => panic!("unit panicked: {message}"),
695            })
696            .collect()
697    }
698
699    #[test]
700    fn dispatch_returns_outputs_in_unit_order() {
701        let pool = WorkerPool::new(None, 3);
702        let units = (0..17).map(Echo).collect();
703        assert_eq!(outputs(pool.dispatch(units)), (0..17).collect::<Vec<_>>());
704    }
705
706    #[test]
707    fn a_burst_spreads_over_distinct_workers() {
708        let pool = WorkerPool::new(None, 4);
709        let outcomes = pool.dispatch(vec![Named, Named, Named, Named]);
710        let names: Vec<String> = outcomes
711            .into_iter()
712            .map(|outcome| match outcome {
713                UnitOutcome::Ok(name) => name,
714                UnitOutcome::Panicked(message) => panic!("unit panicked: {message}"),
715            })
716            .collect();
717        let unique: std::collections::BTreeSet<&String> = names.iter().collect();
718        assert_eq!(
719            unique.len(),
720            4,
721            "each unit must get its own worker: {names:?}"
722        );
723        assert!(
724            names
725                .iter()
726                .all(|name| name.starts_with(POOL_THREAD_NAME_PREFIX)),
727            "pool threads keep their names: {names:?}"
728        );
729    }
730
731    #[test]
732    fn one_queue_runs_units_fifo() {
733        let pool = WorkerPool::new(None, 1);
734        let seen = Arc::new(StdMutex::new(Vec::new()));
735        let units = (0..8u32)
736            .map(|value| Record(value, Arc::clone(&seen)))
737            .collect();
738        let outcomes = pool.dispatch(units);
739        assert!(
740            outcomes
741                .iter()
742                .all(|outcome| matches!(outcome, UnitOutcome::Ok(())))
743        );
744        assert_eq!(*seen.lock().unwrap(), (0..8u32).collect::<Vec<_>>());
745    }
746
747    #[test]
748    fn panicking_unit_is_reported_and_its_worker_is_replaced() {
749        let pool = WorkerPool::new(None, 1);
750        // Both units share the single queue: the second one is already
751        // queued when the first panics, so it proves the replacement drains
752        // the same queue.
753        let outcomes = pool.dispatch(vec![MaybeBoom(0, true), MaybeBoom(7, false)]);
754        assert!(
755            matches!(&outcomes[0], UnitOutcome::Panicked(message) if message.contains("boom marker")),
756            "the panic payload must reach the caller"
757        );
758        assert!(matches!(outcomes[1], UnitOutcome::Ok(7)));
759        // The replacement keeps serving later dispatches.
760        assert_eq!(outputs(pool.dispatch(vec![Echo(9)])), vec![9]);
761        assert_eq!(pool.shared.panics.load(Ordering::Relaxed), 1);
762    }
763
764    #[test]
765    fn nested_dispatch_from_a_worker_runs_inline() {
766        let pool = WorkerPool::new(None, 1);
767        assert_eq!(outputs(pool.dispatch(vec![Nested])), vec![5]);
768    }
769
770    #[test]
771    fn width_is_floored_at_one() {
772        let pool = WorkerPool::new(None, 0);
773        assert_eq!(pool.queues.len(), 1);
774        assert_eq!(outputs(pool.dispatch(vec![Echo(1)])), vec![1]);
775    }
776
777    #[test]
778    fn empty_dispatch_returns_no_outcomes() {
779        let pool = WorkerPool::new(None, 2);
780        assert!(pool.dispatch(Vec::<Echo>::new()).is_empty());
781        assert!(run_units(Vec::<Echo>::new()).is_empty());
782    }
783
784    #[test]
785    fn scoped_fallback_runs_units_in_order_without_a_pool() {
786        let outcomes = scope_fallback(vec![Echo(1), Echo(2), Echo(3)]);
787        assert_eq!(outputs(outcomes), vec![1, 2, 3]);
788    }
789
790    #[test]
791    fn pool_threads_parser_accepts_positive_counts_only() {
792        assert_eq!(pool_threads_from_env(None), None);
793        assert_eq!(pool_threads_from_env(Some("4")), Some(4));
794        assert_eq!(pool_threads_from_env(Some(" 7 ")), Some(7));
795        assert_eq!(pool_threads_from_env(Some("0")), None);
796        assert_eq!(pool_threads_from_env(Some("-1")), None);
797        assert_eq!(pool_threads_from_env(Some("junk")), None);
798        assert_eq!(pool_threads_from_env(Some("")), None);
799    }
800
801    #[test]
802    fn core_list_parser_matches_the_launcher_grammar() {
803        assert_eq!(parse_core_list("6"), Some(vec![6]));
804        assert_eq!(parse_core_list("4-7"), Some(vec![4, 5, 6, 7]));
805        assert_eq!(parse_core_list("7, 4-6,5"), Some(vec![4, 5, 6, 7]));
806        for bad in ["", "  ", "abc", "9-x", "9-8", "4,", "-3", "auto"] {
807            assert_eq!(parse_core_list(bad), None, "spec {bad:?} must be rejected");
808        }
809    }
810
811    #[test]
812    fn serve_core_env_distinguishes_off_set_and_invalid() {
813        assert!(matches!(parse_serve_cores(None), ServeCoreSpec::Off));
814        for raw in ["off", "OFF", "false", " False "] {
815            assert!(
816                matches!(parse_serve_cores(Some(raw.to_owned())), ServeCoreSpec::Off),
817                "token {raw:?} must disable pinning"
818            );
819        }
820        assert!(
821            matches!(parse_serve_cores(Some("2,3".to_owned())), ServeCoreSpec::Set(cores) if cores == vec![2, 3])
822        );
823        // `auto` is the launcher's internal choice, never a valid child spec.
824        assert!(matches!(
825            parse_serve_cores(Some("auto".to_owned())),
826            ServeCoreSpec::Invalid(_)
827        ));
828        assert!(matches!(
829            parse_serve_cores(Some("bogus".to_owned())),
830            ServeCoreSpec::Invalid(_)
831        ));
832        // `0` is core zero, not an off token.
833        assert!(
834            matches!(parse_serve_cores(Some("0".to_owned())), ServeCoreSpec::Set(cores) if cores == vec![0])
835        );
836    }
837}