Skip to main content

relate_core/
load_pool.rs

1//! The shared lazy load worker pool and the per-open transient memory tracker.
2//!
3//! One process-wide pool of persistent worker slots serves every open's load
4//! phase. A load scope ([`with_load_scope`]) fixes how many slots (`k`) that
5//! open may use and which [`OpenTransientTracker`] its transient allocations
6//! are charged to; [`run_load_tasks`] then fans tasks out onto slots `0..k`
7//! only, so slots are spawned on demand and reused across opens. Opens that
8//! share a slot never share a tracker. On wasm32 there are no threads and
9//! [`run_load_tasks`] runs its tasks sequentially.
10
11use std::cell::RefCell;
12use std::ffi::OsStr;
13use std::num::NonZeroUsize;
14use std::sync::atomic::{AtomicU64, Ordering};
15use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
16
17use crate::{Error, Result};
18
19/// The environment variable that sets the load thread count when the
20/// `load_threads` option is absent.
21const LOAD_THREADS_ENV: &str = "RELATE_LOAD_THREADS";
22
23/// How many load worker slots one open may use (always at least one).
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub struct LoadThreads(NonZeroUsize);
26
27impl LoadThreads {
28    /// The thread count as a plain number (>= 1).
29    pub fn get(self) -> usize {
30        self.0.get()
31    }
32}
33
34/// Resolve the load thread count: an explicit `load_threads` wins, then
35/// `RELATE_LOAD_THREADS`, then the machine's available parallelism. Zero,
36/// negative, non-integer and non-UTF-8 values are rejected; an unset or
37/// blank environment variable counts as absent.
38pub fn resolve_load_threads(load_threads: Option<usize>) -> Result<LoadThreads> {
39    resolve(load_threads, std::env::var_os(LOAD_THREADS_ENV).as_deref())
40}
41
42fn resolve(load_threads: Option<usize>, env: Option<&OsStr>) -> Result<LoadThreads> {
43    let requested = match (load_threads, env) {
44        (Some(n), _) => NonZeroUsize::new(n)
45            .ok_or_else(|| Error::semantic("invalid load_threads: must be positive"))?,
46        (None, Some(raw)) => {
47            let text = raw.to_str().ok_or_else(|| {
48                Error::semantic(format!("invalid {LOAD_THREADS_ENV}: not valid UTF-8"))
49            })?;
50            match text.trim() {
51                "" => available(),
52                text => text.parse::<NonZeroUsize>().map_err(|_| {
53                    Error::semantic(format!(
54                        "invalid {LOAD_THREADS_ENV} '{text}': must be a positive integer"
55                    ))
56                })?,
57            }
58        }
59        (None, None) => available(),
60    };
61    Ok(LoadThreads(requested))
62}
63
64fn available() -> NonZeroUsize {
65    std::thread::available_parallelism().unwrap_or(NonZeroUsize::MIN)
66}
67
68/// Peak transient memory of one open: bytes currently leased and the
69/// high-water mark of that sum.
70#[derive(Debug, Default)]
71pub struct OpenTransientTracker {
72    current: AtomicU64,
73    peak: AtomicU64,
74}
75
76impl OpenTransientTracker {
77    /// A tracker with nothing leased.
78    pub fn new() -> Self {
79        Self::default()
80    }
81
82    /// The most bytes that were ever leased at once.
83    pub fn peak_bytes(&self) -> u64 {
84        self.peak.load(Ordering::Relaxed)
85    }
86
87    fn lease(self: &Arc<Self>, bytes: u64) -> TransientLease {
88        let now = self.current.fetch_add(bytes, Ordering::Relaxed) + bytes;
89        self.peak.fetch_max(now, Ordering::Relaxed);
90        TransientLease {
91            tracker: Some(Arc::clone(self)),
92            bytes,
93        }
94    }
95}
96
97/// Bytes charged to an open's tracker until this guard drops. Inert when
98/// taken outside a load scope.
99#[derive(Debug)]
100pub struct TransientLease {
101    tracker: Option<Arc<OpenTransientTracker>>,
102    bytes: u64,
103}
104
105impl Drop for TransientLease {
106    fn drop(&mut self) {
107        if let Some(tracker) = &self.tracker {
108            tracker.current.fetch_sub(self.bytes, Ordering::Relaxed);
109        }
110    }
111}
112
113/// Charge `bytes` of transient memory to the tracker of the load scope the
114/// calling thread is in (load workers inherit their caller's scope).
115pub fn record_transient_lease(bytes: u64) -> TransientLease {
116    match SCOPE.with(|scope| scope.borrow().as_ref().map(|s| Arc::clone(&s.tracker))) {
117        Some(tracker) => tracker.lease(bytes),
118        None => TransientLease {
119            tracker: None,
120            bytes,
121        },
122    }
123}
124
125#[derive(Clone)]
126struct Scope {
127    threads: LoadThreads,
128    tracker: Arc<OpenTransientTracker>,
129}
130
131thread_local! {
132    static SCOPE: RefCell<Option<Scope>> = const { RefCell::new(None) };
133}
134
135/// Restores the previous scope of the thread on drop.
136struct ScopeGuard(Option<Scope>);
137
138fn enter(scope: Scope) -> ScopeGuard {
139    ScopeGuard(SCOPE.with(|cell| cell.borrow_mut().replace(scope)))
140}
141
142impl Drop for ScopeGuard {
143    fn drop(&mut self) {
144        SCOPE.with(|cell| *cell.borrow_mut() = self.0.take());
145    }
146}
147
148/// Run `f` as one open's load phase: tasks it fans out through
149/// [`run_load_tasks`] use at most `threads` pool slots and charge their
150/// transient leases to `tracker`.
151pub fn with_load_scope<R>(
152    threads: LoadThreads,
153    tracker: Arc<OpenTransientTracker>,
154    f: impl FnOnce() -> R,
155) -> R {
156    let _scope = enter(Scope { threads, tracker });
157    f()
158}
159
160/// The load thread count of the scope the calling thread is in; one outside
161/// any scope.
162pub fn current_load_threads() -> LoadThreads {
163    SCOPE
164        .with(|scope| scope.borrow().as_ref().map(|s| s.threads))
165        .unwrap_or(LoadThreads(NonZeroUsize::MIN))
166}
167
168/// Run `tasks` and return their results in order. Inside a load scope with
169/// more than one thread the tasks run on the pool's slots (task `i` on slot
170/// `i % min(k, tasks)`); otherwise, and for calls made from a load worker,
171/// they run inline on the calling thread. The tasks may borrow from the
172/// caller's stack: this returns only once every task has finished. A task's
173/// panic is resumed on the caller after the rest have finished.
174pub fn run_load_tasks<T: Send, F: FnOnce() -> T + Send>(tasks: Vec<F>) -> Vec<T> {
175    #[cfg(not(target_arch = "wasm32"))]
176    {
177        let scope = SCOPE.with(|scope| scope.borrow().clone());
178        if let Some(scope) = scope.filter(|s| s.threads.get() > 1 && tasks.len() > 1) {
179            if !native::on_worker() {
180                return native::POOL.run(&scope, tasks);
181            }
182        }
183    }
184    tasks.into_iter().map(|task| task()).collect()
185}
186
187fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
188    mutex.lock().unwrap_or_else(PoisonError::into_inner)
189}
190
191#[cfg(not(target_arch = "wasm32"))]
192mod native {
193    use std::cell::Cell;
194    use std::panic::{catch_unwind, resume_unwind, AssertUnwindSafe};
195    use std::sync::{mpsc, Condvar};
196    use std::thread;
197
198    use super::*;
199
200    type Job = Box<dyn FnOnce() + Send + 'static>;
201
202    thread_local! {
203        static ON_WORKER: Cell<bool> = const { Cell::new(false) };
204    }
205
206    pub(super) static POOL: LoadPool = LoadPool {
207        slots: Mutex::new(Vec::new()),
208    };
209
210    pub(super) fn on_worker() -> bool {
211        ON_WORKER.get()
212    }
213
214    /// Persistent worker threads, one per slot, spawned on first use.
215    pub(super) struct LoadPool {
216        pub(super) slots: Mutex<Vec<mpsc::Sender<Job>>>,
217    }
218
219    /// The results of one `run`, and how many of its jobs are unfinished.
220    struct Batch<T> {
221        state: Mutex<BatchState<T>>,
222        done: Condvar,
223    }
224
225    struct BatchState<T> {
226        pending: usize,
227        results: Vec<Option<thread::Result<T>>>,
228    }
229
230    impl<T> Batch<T> {
231        fn finish(&self, index: usize, result: thread::Result<T>) {
232            let mut state = lock(&self.state);
233            state.results[index] = Some(result);
234            state.pending -= 1;
235            if state.pending == 0 {
236                self.done.notify_all();
237            }
238        }
239    }
240
241    /// Blocks on drop until the batch has no unfinished job, including while
242    /// `run` unwinds, so no job outlives the borrows its task captured.
243    struct WaitOnDrop<'a, T>(&'a Batch<T>);
244
245    impl<T> Drop for WaitOnDrop<'_, T> {
246        fn drop(&mut self) {
247            let mut state = lock(&self.0.state);
248            while state.pending > 0 {
249                state = self
250                    .0
251                    .done
252                    .wait(state)
253                    .unwrap_or_else(PoisonError::into_inner);
254            }
255        }
256    }
257
258    impl LoadPool {
259        fn sender(&self, slot: usize) -> mpsc::Sender<Job> {
260            let mut slots = lock(&self.slots);
261            while slots.len() <= slot {
262                let (tx, rx) = mpsc::channel::<Job>();
263                thread::Builder::new()
264                    .name(format!("relate-load-{}", slots.len()))
265                    .spawn(move || {
266                        ON_WORKER.set(true);
267                        rx.into_iter().for_each(|job| job());
268                    })
269                    .expect("spawn load worker");
270                slots.push(tx);
271            }
272            slots[slot].clone()
273        }
274
275        pub(super) fn run<'a, T: Send + 'a, F: FnOnce() -> T + Send + 'a>(
276            &self,
277            scope: &Scope,
278            tasks: Vec<F>,
279        ) -> Vec<T> {
280            let lanes = scope.threads.get().min(tasks.len());
281            let batch = Arc::new(Batch {
282                state: Mutex::new(BatchState {
283                    pending: 0,
284                    results: tasks.iter().map(|_| None).collect(),
285                }),
286                done: Condvar::new(),
287            });
288            let wait = WaitOnDrop(&batch);
289            for (index, task) in tasks.into_iter().enumerate() {
290                let sender = self.sender(index % lanes);
291                let (done, scope) = (Arc::clone(&batch), scope.clone());
292                let job: Box<dyn FnOnce() + Send + 'a> = Box::new(move || {
293                    let _scope = enter(scope);
294                    let result = catch_unwind(AssertUnwindSafe(task));
295                    done.finish(index, result);
296                });
297                // SAFETY: `wait` blocks until every sent job has called
298                // `finish`, which happens after the task (and everything it
299                // borrowed) is consumed, so no job outlives `'a`.
300                let job: Job = unsafe { std::mem::transmute(job) };
301                lock(&batch.state).pending += 1;
302                if sender.send(job).is_err() {
303                    lock(&batch.state).pending -= 1;
304                    panic!("load worker pool is unavailable");
305                }
306            }
307            drop(wait);
308            let results = std::mem::take(&mut lock(&batch.state).results);
309            results
310                .into_iter()
311                .map(|result| match result.expect("every load task finished") {
312                    Ok(value) => value,
313                    Err(panic) => resume_unwind(panic),
314                })
315                .collect()
316        }
317    }
318}
319
320#[cfg(test)]
321mod tests {
322    use std::collections::HashSet;
323    use std::ffi::OsString;
324    use std::sync::atomic::AtomicUsize;
325    use std::sync::Barrier;
326    use std::thread::{self, ThreadId};
327
328    use super::*;
329
330    fn threads(n: usize) -> LoadThreads {
331        resolve_load_threads(Some(n)).unwrap()
332    }
333
334    fn scope_with<R>(k: usize, tracker: &Arc<OpenTransientTracker>, f: impl FnOnce() -> R) -> R {
335        with_load_scope(threads(k), Arc::clone(tracker), f)
336    }
337
338    fn thread_ids(count: usize) -> Vec<(ThreadId, String)> {
339        run_load_tasks(
340            (0..count)
341                .map(|_| {
342                    || {
343                        (
344                            thread::current().id(),
345                            thread::current().name().unwrap().to_owned(),
346                        )
347                    }
348                })
349                .collect(),
350        )
351    }
352
353    #[test]
354    fn load_pool_resolve_rejects_bad_values() {
355        let semantic = |r: Result<LoadThreads>| match r.unwrap_err() {
356            Error::Semantic(msg) => msg,
357            other => panic!("not semantic: {other:?}"),
358        };
359        assert!(semantic(resolve(Some(0), None)).contains("load_threads"));
360        let mut bad = vec![OsString::from("0"), "-1".into(), "two".into(), "1.5".into()];
361        #[cfg(unix)]
362        bad.push(std::os::unix::ffi::OsStringExt::from_vec(vec![0x66, 0xff]));
363        for raw in bad {
364            let msg = semantic(resolve(None, Some(&raw)));
365            assert!(msg.contains("RELATE_LOAD_THREADS"), "{raw:?}: {msg}");
366        }
367    }
368
369    #[test]
370    fn load_pool_resolve_accepts_values_and_defaults() {
371        let parallelism = std::thread::available_parallelism().unwrap().get();
372        assert_eq!(resolve(Some(3), None).unwrap().get(), 3);
373        assert_eq!(resolve(Some(3), Some(OsStr::new("9"))).unwrap().get(), 3);
374        assert_eq!(resolve(None, Some(OsStr::new(" 4 "))).unwrap().get(), 4);
375        assert_eq!(resolve(None, None).unwrap().get(), parallelism);
376        assert_eq!(
377            resolve(None, Some(OsStr::new("  "))).unwrap().get(),
378            parallelism
379        );
380    }
381
382    #[test]
383    fn load_pool_slots_are_reused_and_capped_by_scope() {
384        let seen: Mutex<HashSet<(ThreadId, String)>> = Mutex::default();
385        thread::scope(|s| {
386            for _ in 0..4 {
387                s.spawn(|| {
388                    let tracker = Arc::default();
389                    for _ in 0..5 {
390                        let ids = scope_with(2, &tracker, || thread_ids(6));
391                        lock(&seen).extend(ids);
392                    }
393                });
394            }
395        });
396        let seen = lock(&seen);
397        assert!(seen.len() <= 2, "{seen:?}");
398        assert!(seen
399            .iter()
400            .all(|(_, name)| name == "relate-load-0" || name == "relate-load-1"));
401        assert!(lock(&native::POOL.slots).len() <= 2);
402    }
403
404    #[test]
405    fn load_pool_borrows_stack_and_resumes_panics_after_all_finish() {
406        let finished = AtomicUsize::new(0);
407        let data = [1_u64, 2, 3, 4];
408        let tracker = Arc::default();
409        let sums = scope_with(2, &tracker, || {
410            run_load_tasks(data.iter().map(|n| || *n * 10).collect())
411        });
412        assert_eq!(sums, [10, 20, 30, 40]);
413
414        let outcome = std::panic::catch_unwind(|| {
415            scope_with(2, &tracker, || {
416                run_load_tasks(
417                    (0..4)
418                        .map(|i| {
419                            let finished = &finished;
420                            move || {
421                                if i == 0 {
422                                    panic!("boom");
423                                }
424                                thread::sleep(std::time::Duration::from_millis(30));
425                                finished.fetch_add(1, Ordering::SeqCst);
426                            }
427                        })
428                        .collect(),
429                )
430            })
431        });
432        assert_eq!(*outcome.unwrap_err().downcast::<&str>().unwrap(), "boom");
433        assert_eq!(finished.load(Ordering::SeqCst), 3);
434        // The pool survives a panicking task.
435        assert_eq!(scope_with(2, &tracker, || thread_ids(2)).len(), 2);
436    }
437
438    #[test]
439    fn load_pool_nested_calls_run_inline_on_the_worker() {
440        let tracker = Arc::default();
441        let nested = scope_with(2, &tracker, || {
442            run_load_tasks(
443                (0..2)
444                    .map(|_| {
445                        || {
446                            let outer = thread::current().id();
447                            let inner = run_load_tasks(vec![|| thread::current().id(); 3]);
448                            (outer, inner, current_load_threads().get())
449                        }
450                    })
451                    .collect(),
452            )
453        });
454        for (outer, inner, k) in nested {
455            assert_eq!(inner, [outer; 3]);
456            assert_eq!(k, 2);
457        }
458        assert_eq!(current_load_threads().get(), 1);
459    }
460
461    #[test]
462    fn load_pool_tracker_peaks_are_isolated_per_scope() {
463        let trackers: Vec<Arc<OpenTransientTracker>> = (0..2).map(|_| Arc::default()).collect();
464        thread::scope(|s| {
465            for (tracker, bytes) in trackers.iter().zip([100_u64, 7]) {
466                s.spawn(move || {
467                    let barrier = Barrier::new(2);
468                    scope_with(2, tracker, || {
469                        run_load_tasks(
470                            (0..2)
471                                .map(|_| {
472                                    let barrier = &barrier;
473                                    move || {
474                                        let _lease = record_transient_lease(bytes);
475                                        barrier.wait();
476                                    }
477                                })
478                                .collect(),
479                        )
480                    });
481                });
482            }
483        });
484        assert_eq!(trackers[0].peak_bytes(), 200);
485        assert_eq!(trackers[1].peak_bytes(), 14);
486        assert_eq!(trackers[0].current.load(Ordering::Relaxed), 0);
487        drop(record_transient_lease(5)); // outside a scope: inert
488    }
489}