use std::sync::OnceLock;
use std::time::{Duration, Instant};
const MAX_SCALE: u32 = 4;
const MIN_SCALE: u32 = 2;
const BASE_CALIBRATION: u32 = 2;
fn load_average() -> Option<f64> {
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
let mut avg = [0f64; 1];
let n = unsafe { libc::getloadavg(avg.as_mut_ptr(), 1) };
return (n == 1).then_some(avg[0]);
}
#[allow(unreachable_code)]
None
}
pub fn load_scale() -> u32 {
static SCALE: OnceLock<u32> = OnceLock::new();
*SCALE.get_or_init(|| {
let cpus = std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(1) as f64;
let threads = configured_threads().unwrap_or(cpus);
let load = load_average().unwrap_or(0.0);
scale_from(threads, load, cpus)
})
}
fn configured_threads() -> Option<f64> {
threads_from_args(std::env::args()).or_else(|| {
std::env::var("RUST_TEST_THREADS")
.ok()
.and_then(|v| v.parse::<f64>().ok())
})
}
fn threads_from_args<I: IntoIterator<Item = String>>(args: I) -> Option<f64> {
let mut found = None;
let mut args = args.into_iter();
while let Some(a) = args.next() {
let value = if let Some(v) = a.strip_prefix("--test-threads=") {
Some(v.to_string())
} else if a == "--test-threads" {
args.next()
} else {
None
};
if let Some(n) = value.and_then(|v| v.parse::<f64>().ok()) {
found = Some(n);
}
}
found
}
fn scale_from(threads: f64, load: f64, cpus: f64) -> u32 {
if !(threads.is_finite() && load.is_finite() && cpus.is_finite()) || cpus < 1.0 {
return MIN_SCALE;
}
let raw = ((threads + load) / cpus).ceil();
if !raw.is_finite() {
return MIN_SCALE;
}
(raw as u32).clamp(MIN_SCALE, MAX_SCALE)
}
pub fn spawn_budget(base: Duration) -> Duration {
base * BASE_CALIBRATION * load_scale()
}
#[track_caller]
pub fn await_spawned(base: Duration, what: &str, mut ready: impl FnMut() -> bool) {
let scale = load_scale();
let budget = base * BASE_CALIBRATION * scale;
let started = Instant::now();
while started.elapsed() < budget {
if ready() {
return;
}
std::thread::sleep(Duration::from_millis(20));
}
panic!(
"timed out after {budget:?} ({base:?} x{BASE_CALIBRATION} calibration \
x{scale} for load) waiting for {what}; \
if this is a real failure it would also fail at 1x, so re-run the full suite \
on the unmodified merge base under the same load before suspecting your diff"
);
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
pub(crate) const RESTORED_SHELL_BASE: Duration = Duration::from_secs(2);
pub(crate) const TERMINAL_PROBE_BASE: Duration = Duration::from_millis(3750);
pub(crate) const SHELL_PAINT_BASE: Duration = Duration::from_secs(2);
pub(crate) const TASK_PANE_PROMPT_BASE: Duration = Duration::from_millis(1250);
pub(crate) const VIEW_ACCEPT_BASE: Duration = Duration::from_millis(1250);
pub(crate) const VIEW_SERVER_DEADLINE_BASE: Duration = Duration::from_millis(125);
pub(crate) const VIEW_DRAIN_BASE: Duration = Duration::from_millis(500);
pub(crate) const VIEW_FIFO_RECV_BASE: Duration = Duration::from_secs(5);
#[test]
fn the_scale_is_clamped_at_both_ends() {
assert_eq!(
scale_from(1.0, 0.0, 4.0),
MIN_SCALE,
"a quiet machine still gets the floor"
);
assert_eq!(
scale_from(64.0, 0.0, 4.0),
MAX_SCALE,
"far more threads than cores is capped"
);
assert_eq!(
scale_from(1.0, 999.0, 4.0),
MAX_SCALE,
"a crushed machine is capped too"
);
for (t, l, c) in [
(f64::NAN, f64::NAN, 4.0),
(4.0, f64::INFINITY, 4.0),
(4.0, 1.0, 0.0),
(4.0, 1.0, f64::NAN),
] {
assert_eq!(
scale_from(t, l, c),
MIN_SCALE,
"a nonsense reading falls back: {t} {l} {c}"
);
}
}
#[test]
fn a_big_quiet_machine_is_not_a_loaded_one() {
assert_eq!(
scale_from(64.0, 1.0, 64.0),
MIN_SCALE,
"64 threads on 64 cores with nothing else running is not \
contention: the old rule returned the CAP here"
);
assert_eq!(
scale_from(8.0, 0.5, 8.0),
MIN_SCALE,
"nor is a quiet developer machine at its default thread count"
);
assert!(
scale_from(4.0, 14.0, 4.0) > MIN_SCALE,
"while a 4-core box under a genuine 3.5x oversubscription is"
);
}
#[test]
fn both_signals_contribute_to_the_pressure() {
let quiet = scale_from(4.0, 0.0, 4.0);
assert!(
scale_from(12.0, 0.0, 4.0) > quiet,
"the suite's own parallelism counts"
);
assert!(
scale_from(4.0, 12.0, 4.0) > quiet,
"so does load from outside the suite"
);
assert!(
scale_from(6.0, 6.0, 4.0) > scale_from(6.0, 0.0, 4.0),
"together they are worse than either alone"
);
}
#[test]
fn the_worst_case_stretch_is_unchanged() {
assert_eq!(
BASE_CALIBRATION * MAX_SCALE,
8,
"a broken test on a 10s base still fails in 80s, not 160s"
);
assert_eq!(
BASE_CALIBRATION * MIN_SCALE,
4,
"and a quiet machine waits 4x, down from the old 8x"
);
let base = Duration::from_secs(1);
assert!(
spawn_budget(base) <= base * 8,
"no budget may exceed the 8x ceiling, however it is composed"
);
}
#[test]
fn a_converted_wait_keeps_the_budget_it_replaced() {
let floor = RESTORED_SHELL_BASE * BASE_CALIBRATION * MIN_SCALE;
assert!(
floor >= Duration::from_millis(8000),
"the restored-shell base must reproduce the 8000ms it replaced at \
the floor, got {floor:?}"
);
}
#[test]
fn the_probe_and_task_pane_bases_keep_their_old_budgets() {
let probe = TERMINAL_PROBE_BASE * BASE_CALIBRATION * MIN_SCALE;
assert!(
probe >= Duration::from_secs(15),
"the terminal probe base must reproduce the 15s it replaced at the \
floor, got {probe:?}"
);
let task = TASK_PANE_PROMPT_BASE * BASE_CALIBRATION * MIN_SCALE;
assert!(
task >= Duration::from_millis(5000),
"the task-pane prompt base must reproduce the 5000ms it replaced at \
the floor, got {task:?}"
);
let paint = SHELL_PAINT_BASE * BASE_CALIBRATION * MIN_SCALE;
assert!(
paint >= Duration::from_millis(8000),
"the shell-paint base must reproduce 8000ms at the floor, the \
constant its call sites replaced; the few that replaced 4000ms \
are deliberate raises, named in the doc above - got {paint:?}"
);
}
#[test]
fn the_view_socket_bases_reproduce_the_constants_they_replaced() {
let floor = |base: Duration| base * BASE_CALIBRATION * MIN_SCALE;
for (got, want, what) in [
(
floor(VIEW_ACCEPT_BASE),
Duration::from_secs(5),
"the accept wait",
),
(
floor(VIEW_SERVER_DEADLINE_BASE),
Duration::from_millis(500),
"the server deadline",
),
(
floor(VIEW_DRAIN_BASE),
Duration::from_millis(2000),
"the drain poll",
),
(
floor(VIEW_FIFO_RECV_BASE),
Duration::from_secs(20),
"the FIFO recv",
),
] {
assert_eq!(
got, want,
"{what} must give back exactly the budget it replaced at the \
floor: a quiet machine keeps what it had, and the worst case \
stays where this module bounds it"
);
}
}
#[test]
fn the_397_flake_still_gets_its_eight_seconds() {
let scale = scale_from(8.0, 6.0, 4.0);
assert_eq!(scale, 4, "runnable work per CPU: ceil((8 + 6) / 4)");
assert_eq!(
scale_from(6.0, 2.0, 4.0),
MIN_SCALE,
"away from the clamps, the rule is the sum over cpus"
);
let base = std::time::Duration::from_secs(1);
assert!(
base * BASE_CALIBRATION * scale >= std::time::Duration::from_secs(8),
"the 1s base a caller writes still clears the 8s that flake needed"
);
}
#[test]
fn both_spellings_of_the_thread_count_are_seen() {
let argv = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
assert_eq!(
threads_from_args(argv(&["croft", "--test-threads=8"])),
Some(8.0),
"the joined spelling"
);
assert_eq!(
threads_from_args(argv(&["croft", "--test-threads", "8"])),
Some(8.0),
"and the separated one"
);
assert_eq!(
threads_from_args(argv(&["croft", "--nocapture"])),
None,
"absent means absent, so the caller falls back to the CPU count"
);
assert_eq!(
threads_from_args(argv(&["croft", "--test-threads"])),
None,
"a flag with no value is not a thread count"
);
assert_eq!(
threads_from_args(argv(&["croft", "--test-threads=zero"])),
None,
"nor is one that does not parse"
);
assert_eq!(
threads_from_args(argv(&["croft", "--test-threads=zero", "--test-threads=8"])),
Some(8.0),
"a value that does not parse must not mask a real one later on"
);
}
#[test]
fn the_flag_outranks_the_environment_variable_as_libtest_does() {
fn resolve(flag: Option<f64>, env: Option<f64>) -> Option<f64> {
flag.or(env)
}
assert_eq!(
resolve(Some(8.0), Some(4.0)),
Some(8.0),
"the flag wins when both are given, as libtest resolves it"
);
assert_eq!(
resolve(None, Some(4.0)),
Some(4.0),
"the variable is the fallback, not the override"
);
assert_eq!(resolve(None, None), None, "neither means fall back to CPUs");
}
#[test]
fn a_budget_scales_by_exactly_the_scale() {
let base = Duration::from_millis(500);
assert_eq!(
spawn_budget(base),
base * BASE_CALIBRATION * load_scale(),
"the calibration factor rides with the scale (#422)"
);
}
#[test]
#[should_panic(expected = "waiting for a thing that never happens")]
fn a_condition_that_never_holds_still_fails() {
await_spawned(
Duration::from_millis(1),
"a thing that never happens",
|| false,
);
}
#[test]
fn a_condition_already_true_returns_at_once() {
let started = Instant::now();
await_spawned(Duration::from_secs(30), "an immediate condition", || true);
assert!(started.elapsed() < Duration::from_secs(1));
}
}