#[test]
fn priority_follows_the_embedding_count() {
use std::time::{Duration, Instant};
let lines = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
let seen = std::sync::Arc::clone(&lines);
assert!(semlith::priority::manage(move |line| seen
.lock()
.unwrap()
.push(line.to_string())));
assert!(background(), "the daemon starts in background state");
below_normal_on_windows();
let lifted = Instant::now();
let guard = semlith::priority::embedding();
let took = lifted.elapsed();
assert!(took < Duration::from_millis(50), "the lift took {took:?}");
assert!(!background(), "an embed pass lifts the process at once");
below_normal_on_windows();
let inner = semlith::priority::embedding();
drop(inner);
assert!(!background(), "dropped while an outer pass was still going");
drop(guard);
assert!(!background(), "dropped inside the grace period");
let deadline = Instant::now() + Duration::from_secs(1);
while !background() {
assert!(
Instant::now() < deadline,
"still normal a second after the last embed ended"
);
std::thread::sleep(Duration::from_millis(20));
}
let log = lines.lock().unwrap().join("\n");
assert!(
log.contains("priority: background (idle at start)"),
"{log}"
);
assert!(log.contains("priority: normal (embedding)"), "{log}");
assert!(log.contains("priority: background (idle)"), "{log}");
let snapshot = semlith::priority::snapshot();
assert_eq!(snapshot["state"], "background");
assert_eq!(snapshot["switches"], 3);
index_threads_take_the_bulk_class();
}
#[cfg(target_os = "macos")]
fn background() -> bool {
let out = std::process::Command::new("ps")
.args(["-o", "pri=", "-p", &std::process::id().to_string()])
.output()
.expect("ps");
String::from_utf8_lossy(&out.stdout).trim() == "4"
}
#[cfg(not(target_os = "macos"))]
fn background() -> bool {
semlith::priority::snapshot()["state"] == "background"
}
#[cfg(windows)]
fn below_normal_on_windows() {
let out = std::process::Command::new("powershell")
.args([
"-NoProfile",
"-Command",
&format!("(Get-Process -Id {}).PriorityClass", std::process::id()),
])
.output()
.expect("powershell");
assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "BelowNormal");
}
#[cfg(not(windows))]
fn below_normal_on_windows() {}
#[cfg(target_os = "linux")]
fn index_threads_take_the_bulk_class() {
let policy = || unsafe { libc::sched_getscheduler(0) };
let before = policy();
let guard = semlith::priority::indexing_thread();
assert_eq!(policy(), libc::SCHED_BATCH);
assert_eq!(
semlith::priority::snapshot()["indexing_class"],
"SCHED_BATCH"
);
drop(guard);
assert_eq!(policy(), before);
}
#[cfg(not(target_os = "linux"))]
fn index_threads_take_the_bulk_class() {}