waratah_compute/core_width.rs
1//! Process-wide core width for executor parallelism decisions.
2//!
3//! Sizing parallel executor work from `std::thread::available_parallelism()`
4//! at the call site is wrong on a pinned thread: it reads the CALLING
5//! thread's affinity mask, so a runtime worker pinned to a single core
6//! under serve-core confinement reports `1` and every parallel decision
7//! collapses to serial. That is how serving-mode Grace joins ran serially
8//! long after the parallel path existed. The width here has no such
9//! failure: the launcher resolves it once at startup from an unpinned
10//! context and publishes it.
11
12use std::sync::OnceLock;
13
14static CORE_WIDTH: OnceLock<usize> = OnceLock::new();
15
16/// Publish the process's core budget. Called once at startup by the
17/// launcher (`waratah_bin`) after serve-core resolution: the serve core
18/// set size when the process is confined, the machine width otherwise
19/// (read from the unpinned main thread). Idempotent: the first call wins.
20pub fn set_process_core_width(width: usize) {
21 let _ = CORE_WIDTH.set(width.max(1));
22}
23
24/// The process's core budget for executor parallelism.
25///
26/// Returns the published width when the launcher set one; otherwise
27/// (unit tests, batch tools, library embeddings — contexts whose threads
28/// are not pinned) falls back to `available_parallelism()`, which is
29/// correct for them.
30pub fn process_core_width() -> usize {
31 CORE_WIDTH.get().copied().unwrap_or_else(|| {
32 std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get)
33 })
34}
35
36#[cfg(test)]
37mod tests {
38 use super::*;
39
40 #[test]
41 fn unpublished_falls_back_to_available_parallelism() {
42 // Tests never publish, so the fallback must be live and sane.
43 assert!(process_core_width() >= 1);
44 }
45}