Skip to main content

waratah/
affinity.rs

1//! Serve-process CPU affinity control (`WARATAH_SERVE_CORES`).
2//!
3//! ## Behavior
4//!
5//! - **Unset / `off` / `false`** (case-insensitive; `0` is core zero, not
6//!   an off token): no affinity syscall is ever made. This is the DEFAULT
7//!   for every subcommand, serving and batch alike — the process runs on
8//!   the stock scheduler and the storage worker pool runs unpinned at
9//!   `available_parallelism()` width. A serving subcommand (`start`,
10//!   `standalone`) announces the off state on stderr once; batch tools
11//!   stay silent.
12//! - **A core-list spec** (`6`, `4-7`, `2,3,6-8`): opt-in confinement for
13//!   any subcommand. (On Linux the `sched_setaffinity` calls are
14//!   best-effort: a set outside the process's cpuset degrades to
15//!   unpinned.)
16//!
17//! ## Why the default is off (the 0.4.0 disconfirmation)
18//!
19//! Pinning was originally default-on: an unset env auto-selected every
20//! physical core of one L3 domain (CPPC-ranked, deterministic) and pinned
21//! threads 1:1 onto it. The motivation was real — pre-0.4.0 small hot
22//! queries were bimodal (lubm-100 q13 hot passes ~1.4 ms for a few
23//! executions, then settling at ~0.65 ms; Oxigraph, same corpus, flat at
24//! ~0.5 ms), workers pinned onto distinct physical cores mitigated it,
25//! and SMT-sibling sets did not. But the fixed-resident storage worker
26//! pool (`waratah_storage/src/worker_pool.rs`) removed the per-call
27//! `spawn_blocking` thread churn that caused the original disease, and
28//! re-benchmarking 0.4.0 measured static pinning as strictly harmful on a
29//! quiet machine: q13 latencies gained a spike tail (30 spikes per 1,800
30//! iterations vs 2 unpinned; p99 0.90 vs 0.51 ms) because 30+ runtime,
31//! storage-pool, and blocking threads queue on 8 pinned cores; q02 hot
32//! p50 382 ms pinned vs 284 ms unpinned; bulk load and concurrent-engine
33//! throughput worse; and a static 16-logical-CPU mask recreated the
34//! original bimodality verbatim by forcing SMT-sibling packing whenever
35//! more than 8 threads were runnable — the unpinned scheduler avoids
36//! sibling packing adaptively, a static mask cannot. The hardware
37//! mechanism behind the original bimodality (SMT sibling contention vs
38//! private-cache re-warm on migration vs CPPC boost effects) was never
39//! discriminated by an instrumented experiment; the shared-L3-re-warm
40//! explanation once written here is withdrawn (contradicted by
41//! full-machine-set mitigation and the unified L3). Auto-selection
42//! machinery was deleted with the flip; explicit core lists remain the
43//! opt-in.
44//! ## What a resolved set does in this process
45//!
46//! - the runtime is built with `worker_threads = <set size>`, and ONE
47//!   start hook pins every newly-spawned runtime thread. Tokio delivers
48//!   `on_thread_start` to the WORKER threads and to the BLOCKING-POOL
49//!   threads alike (the blocking pool clones the runtime's hook and runs
50//!   it at the top of every blocking thread — verified against tokio
51//!   1.53.x `blocking/pool.rs`; the blocking pool runs the synchronous
52//!   RocksDB scan closures). The policy is [`slot_pin_target`]: today
53//!   EVERY thread takes `cores[slot % len]` from a process-global spawn
54//!   counter, so workers (first `len` slots) land 1:1 on distinct set
55//!   cores and blocking threads (later slots) wrap back onto worker
56//!   cores — a blocking scan thread is permanently paired with one
57//!   worker's core. Whether that pairing helps or hurts is part of the
58//!   open mechanism question above; the policy stays untouched until the
59//!   instrumented experiment reports.
60//! - Pinning is best-effort: a `sched_setaffinity` failure (e.g. a
61//!   container cpuset that excludes the requested cores) is logged and
62//!   the thread simply stays unpinned.
63//!
64//! `serve_pin` (a progressive self-pin called at the top of every scan
65//! closure) existed between the feature's landing and its first audit.
66//! It was designed under the assumption that tokio does not deliver the
67//! start hook to blocking threads — false, so its fast path hit on every
68//! invocation and it never pinned anything in any shipped build. Deleted
69//! rather than kept as a second pinner because its narrowing rule
70//! (freeze the thread onto the core it first ran on) is precisely the
71//! unvalidated behavior the mechanism experiment is meant to evaluate.
72//!
73//! In `start` mode the partition/registry children are confined by the
74//! LAUNCHER: [`confine_child`] attaches a pre-exec hook that narrows each
75//! child's initial thread to the same set before exec, so every thread the
76//! child creates afterwards (tonic workers, blocking pools, RocksDB
77//! background compaction) inherits the mask — without any cooperation from
78//! the child binary. The set is also written into the child's environment
79//! as an explicit spec so a future in-child runtime hook resolves to the
80//! same cores.
81
82use std::io;
83use std::sync::OnceLock;
84use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
85
86/// Resolved once per process by [`init_serve_cores`]; read everywhere else.
87static SERVE_CORES: OnceLock<Option<CoreSet>> = OnceLock::new();
88
89/// Core-set spec for the serve runtime, e.g. `WARATAH_SERVE_CORES=4-7`.
90pub const SERVE_CORES_ENV: &str = "WARATAH_SERVE_CORES";
91
92#[cfg(target_os = "linux")]
93const MAX_CORE_ID: usize = libc::CPU_SETSIZE as usize - 1;
94#[cfg(not(target_os = "linux"))]
95const MAX_CORE_ID: usize = 1023;
96
97/// A validated set of CPU ids the serve process may run on.
98#[derive(Debug, Clone, PartialEq, Eq)]
99pub struct CoreSet {
100    cores: Vec<usize>,
101}
102
103impl CoreSet {
104    /// Sorted distinct core ids, ascending.
105    pub fn cores(&self) -> &[usize] {
106        &self.cores
107    }
108
109    /// Number of cores in the set.
110    pub fn len(&self) -> usize {
111        self.cores.len()
112    }
113
114    /// True when the set is empty (never true for a parsed spec).
115    pub fn is_empty(&self) -> bool {
116        self.cores.is_empty()
117    }
118
119    /// Canonical spec string: comma-separated ascending ids (`0,1,4,5`).
120    pub fn to_spec(&self) -> String {
121        self.cores
122            .iter()
123            .map(|core| core.to_string())
124            .collect::<Vec<_>>()
125            .join(",")
126    }
127}
128
129/// Parse a core-set spec: single cores and inclusive ranges, comma
130/// separated (`6`, `4-7`, `2,3,6-8`), order-insensitive, duplicates
131/// collapsed and ranges merged. Rejects empty elements, non-numeric or
132/// reversed ranges, and core ids above the kernel's `cpu_set_t` width.
133pub fn parse_core_set(spec: &str) -> Result<CoreSet, String> {
134    let mut cores = std::collections::BTreeSet::new();
135    for part in spec.split(',') {
136        let part = part.trim();
137        if part.is_empty() {
138            return Err(format!("empty element in core set spec {spec:?}"));
139        }
140        let (first, last) = match part.split_once('-') {
141            None => {
142                let core = parse_core_id(part, spec)?;
143                (core, core)
144            }
145            Some((low, high)) => {
146                let low = parse_core_id(low, spec)?;
147                let high = parse_core_id(high, spec)?;
148                if low > high {
149                    return Err(format!("reversed range {part:?} in core set spec {spec:?}"));
150                }
151                (low, high)
152            }
153        };
154        cores.extend(first..=last);
155    }
156    if cores.last().is_some_and(|&highest| highest > MAX_CORE_ID) {
157        return Err(format!(
158            "core id above supported maximum {MAX_CORE_ID} in core set spec {spec:?}"
159        ));
160    }
161    Ok(CoreSet {
162        cores: cores.into_iter().collect(),
163    })
164}
165
166fn parse_core_id(text: &str, spec: &str) -> Result<usize, String> {
167    text.trim()
168        .parse::<usize>()
169        .map_err(|_| format!("bad core id {text:?} in core set spec {spec:?}"))
170}
171
172/// What the raw `WARATAH_SERVE_CORES` value asks for.
173#[derive(Debug, Clone, PartialEq, Eq)]
174enum EnvSpec {
175    /// Unset — off, the default for every subcommand (a serving process
176    /// announces the off state on stderr).
177    Unset,
178    /// An `off`/`false` token (case-insensitive) — explicitly disabled.
179    /// `0` is deliberately NOT here: it parses as core zero.
180    Off,
181    /// A valid core-set spec, any subcommand.
182    Set(CoreSet),
183    /// Anything else — warn once and treat as off.
184    Invalid(String),
185}
186
187fn parse_env_spec(raw: Option<String>) -> EnvSpec {
188    let Some(spec) = raw else {
189        return EnvSpec::Unset;
190    };
191    let trimmed = spec.trim();
192    if trimmed.eq_ignore_ascii_case("off") || trimmed.eq_ignore_ascii_case("false") {
193        return EnvSpec::Off;
194    }
195    match parse_core_set(trimmed) {
196        Ok(set) if !set.is_empty() => EnvSpec::Set(set),
197        _ => EnvSpec::Invalid(spec),
198    }
199}
200
201/// Resolve the serve core set for this process. Unset and `off`/`false`
202/// resolve to no set — the default for every subcommand; `serving=true`
203/// only makes the off state announce itself on stderr (batch tools stay
204/// silent). A valid core-list spec opts in; an invalid spec warns once
205/// and runs unpinned.
206fn resolve(serving: bool) -> Option<CoreSet> {
207    match parse_env_spec(std::env::var(SERVE_CORES_ENV).ok()) {
208        EnvSpec::Unset => {
209            if serving {
210                eprintln!(
211                    "waratah: serve cores: off (default; set {SERVE_CORES_ENV}=<e.g. 4-7> \
212                     to pin serving threads)"
213                );
214            }
215            None
216        }
217        EnvSpec::Off => None,
218        EnvSpec::Set(set) => Some(set),
219        EnvSpec::Invalid(raw) => {
220            eprintln!(
221                "waratah: ignoring invalid {SERVE_CORES_ENV}={raw:?}: use a core list \
222                 (e.g. 4-7) or off"
223            );
224            None
225        }
226    }
227}
228
229/// Resolve and cache the serve core set for this process. Call exactly
230/// once, before [`build_serve_runtime`]. Unset means off for every
231/// subcommand; `serving=true` (the serving subcommands `start` /
232/// `standalone`) only makes the off state announce itself on stderr —
233/// batch tools stay silent.
234pub fn init_serve_cores(serving: bool) {
235    let _ = SERVE_CORES.get_or_init(|| resolve(serving));
236}
237
238/// The resolved serve core set for this process: `None` when off (unset —
239/// the default — or an `off`/`false` token or an invalid spec), `Some`
240/// for an explicit core-list spec.
241pub fn serve_core_set() -> Option<CoreSet> {
242    SERVE_CORES.get_or_init(|| resolve(false)).clone()
243}
244
245/// What the start hook does to one newly-spawned runtime thread. The
246/// enum is the seam for the blocking-thread policy decision: adding a
247/// variant forces the hook's `match` (and the policy tests) to handle it.
248#[derive(Debug, Clone, Copy, PartialEq, Eq)]
249enum PinTarget {
250    /// `sched_setaffinity` the thread onto exactly this one core.
251    SingleCore(usize),
252}
253
254/// The pin policy for spawn slot `slot` of a resolved `set`. Current
255/// behavior, unchanged since the feature landed: EVERY runtime-spawned
256/// thread — worker or blocking-pool, both run the start hook — takes
257/// `cores[slot % len]` from a process-global spawn counter. Worker slots
258/// `0..len` land 1:1 on distinct cores; blocking threads take later
259/// slots, which wrap onto worker cores (permanent worker/scan-thread
260/// pairing — see the module docs for the open policy question).
261fn slot_pin_target(slot: usize, set: &CoreSet) -> PinTarget {
262    PinTarget::SingleCore(set.cores()[slot % set.len()])
263}
264
265/// The CLI's tokio runtime: the same multi-thread + io + time runtime
266/// `#[tokio::main]` builds, except when [`serve_core_set`] is `Some` — then
267/// the worker pool is sized to the core set and ONE start hook pins every
268/// newly-spawned runtime thread. Tokio delivers the hook to the worker
269/// threads AND to blocking-pool threads (the blocking pool clones the
270/// runtime's `after_start` callback — see the module docs), so both
271/// populations pin through [`slot_pin_target`].
272pub fn build_serve_runtime() -> tokio::runtime::Runtime {
273    let mut builder = tokio::runtime::Builder::new_multi_thread();
274    builder.enable_all();
275    if let Some(set) = serve_core_set() {
276        builder.worker_threads(set.len());
277        let next_slot = AtomicUsize::new(0);
278        builder.on_thread_start(move || {
279            let slot = next_slot.fetch_add(1, AtomicOrdering::Relaxed);
280            match slot_pin_target(slot, &set) {
281                PinTarget::SingleCore(core) => {
282                    if let Err(error) = pin_to_single_core(core) {
283                        eprintln!("waratah: could not pin runtime thread to core {core}: {error}");
284                    }
285                }
286            }
287        });
288    }
289    builder.build().expect("build serve tokio runtime")
290}
291
292/// Confine a not-yet-spawned child to `set`, launcher-side: a pre-exec hook
293/// (Linux) narrows the child's initial thread to the set before exec, so
294/// every thread the child creates afterwards — runtime workers, blocking
295/// pools, RocksDB background compaction — inherits the mask, without any
296/// cooperation from the child binary. The set is also written into the
297/// child's environment as an explicit spec so the child agrees with the
298/// launcher. The hook is best-effort: a `sched_setaffinity` failure
299/// (spec outside the child's cpuset) is swallowed and the child keeps its
300/// inherited mask rather than failing the spawn.
301pub fn confine_child(command: &mut std::process::Command, set: &CoreSet) {
302    command.env(SERVE_CORES_ENV, set.to_spec());
303    #[cfg(target_os = "linux")]
304    {
305        use std::os::unix::process::CommandExt;
306        let set = set.clone();
307        // SAFETY: the closure runs in the freshly forked child before
308        // exec; pid 0 is that child alone, and nothing else has been set
309        // up in its address space yet.
310        unsafe {
311            command.pre_exec(move || {
312                let _ = set_affinity(set.cores());
313                Ok(())
314            });
315        }
316    }
317}
318
319#[cfg(target_os = "linux")]
320fn pin_to_single_core(core: usize) -> io::Result<()> {
321    set_affinity(&[core])
322}
323
324#[cfg(target_os = "linux")]
325fn set_affinity(cores: &[usize]) -> io::Result<()> {
326    let mut mask: libc::cpu_set_t = unsafe { std::mem::zeroed() };
327    unsafe {
328        libc::CPU_ZERO(&mut mask);
329        for &core in cores {
330            libc::CPU_SET(core, &mut mask);
331        }
332    }
333    let rc = unsafe { libc::sched_setaffinity(0, std::mem::size_of::<libc::cpu_set_t>(), &mask) };
334    if rc != 0 {
335        return Err(io::Error::last_os_error());
336    }
337    Ok(())
338}
339
340#[cfg(test)]
341mod tests {
342    use super::*;
343
344    #[test]
345    fn parses_single_core() {
346        let set = parse_core_set("6").expect("valid spec");
347        assert_eq!(set.cores(), &[6]);
348    }
349
350    #[test]
351    fn parses_range() {
352        let set = parse_core_set("4-7").expect("valid spec");
353        assert_eq!(set.cores(), &[4, 5, 6, 7]);
354    }
355
356    #[test]
357    fn parses_mixed_and_collapses_duplicates() {
358        let set = parse_core_set("7, 4-6,5").expect("valid spec");
359        assert_eq!(set.cores(), &[4, 5, 6, 7]);
360    }
361
362    #[test]
363    fn rejects_bad_specs() {
364        for spec in [
365            "",
366            "  ",
367            "abc",
368            "9-x",
369            "9-8",
370            "4,",
371            "-3",
372            "4096",
373            "4,4095-4097",
374        ] {
375            assert!(
376                parse_core_set(spec).is_err(),
377                "spec {spec:?} must be rejected"
378            );
379        }
380    }
381
382    #[test]
383    fn spec_string_round_trips() {
384        let set = parse_core_set("7,4-6,5").expect("valid spec");
385        assert_eq!(set.to_spec(), "4,5,6,7");
386    }
387
388    #[test]
389    fn off_tokens_disable_case_insensitively() {
390        for raw in ["off", "OFF", "Off", "false", "FALSE", "False", " false "] {
391            assert!(
392                matches!(parse_env_spec(Some(raw.to_owned())), EnvSpec::Off),
393                "token {raw:?} must disable"
394            );
395        }
396        assert_eq!(parse_env_spec(None), EnvSpec::Unset);
397        assert!(matches!(
398            parse_env_spec(Some("4-7".to_owned())),
399            EnvSpec::Set(_)
400        ));
401        assert!(matches!(
402            parse_env_spec(Some("bogus".to_owned())),
403            EnvSpec::Invalid(_)
404        ));
405        // `0` is core zero, not an off token:
406        assert!(matches!(
407            parse_env_spec(Some("0".to_owned())),
408            EnvSpec::Set(_)
409        ));
410    }
411
412    #[test]
413    fn pin_policy_wraps_slots_round_robin() {
414        // Slots 0..len map 1:1 onto distinct cores (workers); later slots
415        // (blocking-pool threads) wrap onto worker cores — the current
416        // pairing behavior, under the open mechanism question.
417        let set = parse_core_set("4-6").expect("valid spec");
418        assert_eq!(slot_pin_target(0, &set), PinTarget::SingleCore(4));
419        assert_eq!(slot_pin_target(1, &set), PinTarget::SingleCore(5));
420        assert_eq!(slot_pin_target(2, &set), PinTarget::SingleCore(6));
421        assert_eq!(slot_pin_target(3, &set), PinTarget::SingleCore(4));
422        assert_eq!(slot_pin_target(10, &set), PinTarget::SingleCore(5));
423    }
424}