//! Moved out of the parent module by STRA-338: impl Impl, impl Proc, fn procs_for, fn cell_env, fn scrubbed_command, fn run_cell .... #[allow(unused_imports)] use super::*; impl Impl { pub(super) fn name(self) -> &'static str { match self { Impl::Cpp => "cpp", Impl::Rust => "rust", } } } impl Proc { pub(super) fn name(&self) -> String { format!("{}-{}-{}", self.imp.name(), self.tree, self.rep) } pub(super) fn parse(s: &str) -> Option { let mut p = s.split('-'); let imp = match p.next()? { "cpp" => Impl::Cpp, "rust" => Impl::Rust, _ => return None, }; let wanted = p.next()?; let tree = *TREES.iter().find(|t| **t == wanted)?; let rep = match p.next()? { "a" => 'a', "b" => 'b', _ => return None, }; p.next().is_none().then_some(Proc { imp, tree, rep }) } } /// Every process of a round for the given trees, in canonical order. pub(super) fn procs_for(trees: &[&'static str]) -> Vec { let mut v = Vec::new(); for imp in [Impl::Cpp, Impl::Rust] { for tree in trees { for rep in ['a', 'b'] { v.push(Proc { imp, tree, rep }); } } } v } /// The environment a cell needs and nothing else. The avx2 trees set `STRATA_FORCE_AVX2=1`, which both implementations honour. The /// Rust cells run `DirectCpuPool::new(1)`, a worker thread plus the draining caller, both confined to the one pinned CPU: the pool must /// not re-pin its caller (`LELEKA_CPU_POOL_PIN_HOST=off`, so the pin is the requested one) and its worker must not spin after a batch /// (`STRATA_POOL_SPIN_US=0`; with the 20 ms default the worker spins on the caller's only CPU and costs it half its time). pub(super) fn cell_env(p: &Proc) -> Vec<(String, String)> { let mut v = Vec::new(); if p.tree == "avx2" { v.push(("STRATA_FORCE_AVX2".to_owned(), "1".to_owned())); } if p.imp == Impl::Rust { v.push(("LELEKA_CPU_POOL_PIN_HOST".to_owned(), "off".to_owned())); v.push(("STRATA_POOL_SPIN_US".to_owned(), "0".to_owned())); } v.sort(); v } /// A command whose environment is exactly: the parent's variables minus every STRATA_* / LELEKA_* one, plus the cell's variables. pub(super) fn scrubbed_command( program: &Path, parent_env: &[(OsString, OsString)], cell: &[(String, String)], ) -> Command { let mut c = Command::new(program); c.env_clear(); for (k, v) in parent_env { if !is_managed_name(&k.to_string_lossy()) { c.env(k, v); } } for (k, v) in cell { c.env(k, v); } c } /// Runs a prepared cell command; a failure names the cell. pub(super) fn run_cell(cmd: &mut Command, cell: &str) -> Result { let out = cmd.output().map_err(|e| format!("cell {cell}: cannot start the process: {e}"))?; if out.status.success() { return Ok(out); } let tail = |b: &[u8]| { String::from_utf8_lossy(b) .lines() .rev() .take(3) .collect::>() .into_iter() .rev() .collect::>() .join(" | ") }; Err(format!( "cell {cell} failed ({}): stderr: {}; stdout: {}", out.status.code().map_or("killed by a signal".to_owned(), |c| format!("exit {c}")), tail(&out.stderr), tail(&out.stdout) )) } pub(super) fn splitmix(state: &mut u64) -> u64 { *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15); let mut z = *state; z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); z ^ (z >> 31) } /// The schedule of one batch: round `i` (0-based) rotates a seeded permutation by `i mod n`; every block of `n` rounds draws a fresh /// permutation, so each process takes each position equally often within a block. A pure function of (seed, batch, rounds, procs). pub(super) fn make_schedule(seed: u64, batch: u32, rounds: u32, procs: &[Proc]) -> Vec> { let n = procs.len(); let mut out = Vec::new(); let mut base: Vec = Vec::new(); for i in 0..rounds as usize { if i % n == 0 { let mut st = seed; for x in [u64::from(batch), (i / n) as u64] { st = st.wrapping_add(x.wrapping_mul(0x9E37_79B9_7F4A_7C15)); st = splitmix(&mut st); } base = procs.to_vec(); for j in (1..n).rev() { let k = (splitmix(&mut st) % (j as u64 + 1)) as usize; base.swap(j, k); } } let mut order = base.clone(); order.rotate_left(i % n); out.push(order); } out } pub(super) fn schedule_text( seed: u64, batch: u32, rounds: u32, case: &str, pin: usize, first_round: u32, order: &[Vec], ) -> String { let mut t = format!( "{SCHEDULE_MAGIC} (written before the first run; the runner reads this file back)\n# seed={seed} batch={batch} rounds={rounds} case={case} pin={pin}\n" ); for (i, o) in order.iter().enumerate() { t += &format!("{}\t{}\n", first_round + i as u32, o.iter().map(Proc::name).collect::>().join(",")); } t } /// Reads a schedule back: (round number, processes in order) per round. Every round must name each process of the first round once. pub(super) fn parse_schedule(text: &str) -> Result)>, String> { let mut lines = text.lines(); if !lines.next().is_some_and(|l| l.starts_with(SCHEDULE_MAGIC)) { return Err("not a KAB1-alt schedule".to_owned()); } let mut rounds: Vec<(u32, Vec)> = Vec::new(); for l in lines.filter(|l| !l.starts_with('#') && !l.is_empty()) { let (no, list) = l.split_once('\t').ok_or_else(|| format!("bad schedule line {l:?}"))?; let no = no.parse::().map_err(|_| format!("bad round number in {l:?}"))?; let order: Vec = list .split(',') .map(|n| Proc::parse(n).ok_or_else(|| format!("unknown process {n:?} in the schedule"))) .collect::>()?; if let Some(prev) = rounds.last() && (no != prev.0 + 1 || BTreeSet::from_iter(order.iter()) != BTreeSet::from_iter(prev.1.iter()) || order.len() != prev.1.len()) { return Err(format!("round {no} does not follow round {} with the same processes", prev.0)); } rounds.push((no, order)); } if rounds.is_empty() { return Err("the schedule has no round".to_owned()); } Ok(rounds) } /// Refuses a path that is, or lies inside, a Git checkout (generated artifacts stay out of Git). pub(super) fn inside_git_checkout(path: &Path) -> bool { let abs = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf()); abs.ancestors().any(|a| a.join(".git").exists()) } pub(super) fn parse_regime(r: &Json, imp: Impl) -> Result { let mut ns = Vec::new(); let mut cycles = Vec::new(); let mut max_drift = 0.0f64; for (key, keep) in [("slices", true), ("dropped", false)] { for s in r.array(key)? { let (g0, g1) = (s.float("ghz_before")?, s.float("ghz_after")?); if g0 > 0.0 { max_drift = max_drift.max(((g1 - g0).abs() / g0).min(1.0)); } if keep { ns.push(s.float("ns_per_call")?); cycles.push(s.float("cycles_per_call")?); } } } let selfcheck_key = if imp == Impl::Cpp { "selfcheck_bitwise_equal_compose_expert" } else { "selfcheck_bitwise_equal_first_call" }; let kept = r.uint("slices_kept")? as usize; if kept != ns.len() || kept == 0 { return Err(format!("slices_kept {kept} disagrees with the {} kept slices (or none was kept)", ns.len())); } Ok(RegimeStat { copies_k: r.uint("copies_k")? as usize, expert_bytes: r.uint("expert_bytes")? as usize, llc_bytes: r.uint("llc_bytes")?, requested: r.uint("slices_requested")? as usize, dropped: r.uint("dropped_count")? as usize, median_ns: r.float("median_ns_per_call")?, median_cycles: r.float("median_cycles_per_call")?, ns, cycles, max_drift, selfcheck: r.flag(selfcheck_key)?, }) }