From e80528ac7a5a00a15ca8bd2b42f72bfd337ce9b4 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 28 Oct 2026 21:09:10 +0100 Subject: [PATCH 1/2] kernel_ab: Rust time mode and the alternation runner (STRA-318) Adds the sub-commands 'time' (the Rust twin of 'kab time', same command line) and 'alternate' (fresh scrubbed pinned processes for the cells {cpp,rust} x {avx512,avx2}, a/b replicates for the A/A pairs, seeded schedule file written before the first run, per-round COMPONENT_KERNEL records, equality recorded per tree). No statistics. run-tree gains an optional --case. Co-Authored-By: Claude Sonnet 5.5 --- .../native-cpu-expert/examples/kernel_ab.rs | 1836 ++++++++++++++++- 1 file changed, 1812 insertions(+), 24 deletions(-) diff --git a/crates/native-cpu-expert/examples/kernel_ab.rs b/crates/native-cpu-expert/examples/kernel_ab.rs index f7216cbe..5e2689a4 100644 --- a/crates/native-cpu-expert/examples/kernel_ab.rs +++ b/crates/native-cpu-expert/examples/kernel_ab.rs @@ -12,11 +12,24 @@ //! `.out` files (bitwise on the f32 bit patterns, or the tolerance the manifest case //! declares with its basis), write `R/case-.rust-.out` and one //! COMPONENT_KERNEL record per case and tree to `R/records/` -//! kernel_ab run-tree D --tree T --out R [--pin CPU] -//! internal: one fresh process, one tree (T = avx512 | avx2) +//! kernel_ab run-tree D --tree T --out R [--pin CPU] [--case ID] +//! internal: one fresh process, one tree (T = avx512 | avx2), all cases or only ID //! -//! Timing is NOT here (alternation runner, regimes, clock calibration, A/A floor: STRA-318). The records written by this part carry -//! the fields the schema requires for them with the explicit NOT_MEASURED marker (see `NOT_MEASURED`), never a measurement. +//! Timing is not in `verify` / `compare`. The records written by `compare` carry the fields the schema requires for timing with the +//! explicit NOT_MEASURED marker (see `NOT_MEASURED`), never a measurement. Timing is the second half (STRA-318, S0.8b2): +//! +//! kernel_ab time --run-dir D --case ID --slices N --pin CPU --out F.json [--slice-ms 60] [--regime both|resident|streamed] +//! [--llc-bytes B] +//! the Rust twin of `kab time` (tools/kernel-ab, STRA-317): ONE fresh process times ONE +//! case in the resident and the streamed regime on the pinned CPU and writes the KAB1-time +//! JSON (writer "rust"); no statistics +//! kernel_ab alternate --run-dir D --case ID --rounds N --batch K --pin CPU --schedule FILE [--seed S] [--out R] [--slices N] +//! [--slice-ms MS] [--llc-bytes B] [--machine-role NAME] [--kab PATH] +//! the alternation runner (ARCHITECT 395f0394 sec 1.3): std::process::Command only. Per +//! round it starts FRESH processes for the cells {cpp, rust} x {avx512, avx2} (each twice, +//! a and b, for the A/A pairs) in the order of a seeded schedule file written before the +//! first run, and writes COMPONENT_KERNEL round records. It computes NO statistics: no +//! class, no interval, no A/A verdict (those are S0.10b, STRA-313). //! //! cargo run --release -p leleka-native-cpu-expert --example kernel_ab -- compare D //! cargo test -p leleka-native-cpu-expert --example kernel_ab @@ -24,12 +37,14 @@ use leleka_native_cpu_expert::{BorrowedExpert, BorrowedGroup, DirectCpuPool, DownFormat, GateUpFormat, PreparedJob, cpu_kernel_report, rust_topology}; use sha2::{Digest, Sha256}; use std::cell::Cell; -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet}; +use std::ffi::OsString; use std::fs::{self, File}; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; use std::process::{Command, ExitCode}; -use std::time::{SystemTime, UNIX_EPOCH}; +use std::sync::OnceLock; +use std::time::{Instant, SystemTime, UNIX_EPOCH}; const IN_MAGIC: u32 = 0x4942_414B; const OUT_MAGIC: u32 = 0x4F42_414B; @@ -365,6 +380,31 @@ impl Json { _ => Err(format!("key {key:?} is not a number")), } } + fn float(&self, key: &str) -> Result { + match self.req(key)? { + Json::Num(n) => n.parse::().ok().filter(|v| v.is_finite()).ok_or_else(|| format!("key {key:?} is not a finite number")), + _ => Err(format!("key {key:?} is not a number")), + } + } + /// A number, or None for a JSON null (the C++ writer prints null for a value it could not measure). + fn float_or_null(&self, key: &str) -> Result, String> { + match self.req(key)? { + Json::Null => Ok(None), + _ => self.float(key).map(Some), + } + } + fn flag(&self, key: &str) -> Result { + match self.req(key)? { + Json::Bool(b) => Ok(*b), + _ => Err(format!("key {key:?} is not a boolean")), + } + } + fn array(&self, key: &str) -> Result<&[Json], String> { + match self.req(key)? { + Json::Arr(a) => Ok(a), + _ => Err(format!("key {key:?} is not an array")), + } + } } // ------------------------------------------------------------------------------------------------ KAB1 headers @@ -698,8 +738,9 @@ fn read_out(path: &Path, name: &str, rows: usize, tree: &str, expect: Option<(&s Ok(bits) } -/// The reader rule. Everything in the directory is checked before anything is used; any problem refuses the whole directory. -fn verify_dir(dir: &Path) -> Result { +/// Reads and parses `manifest.json` (size cap first). Returns its bytes (the caller hashes them), the provenance, the cases and the flat +/// files table. A missing manifest is the `incomplete` refusal. +fn read_manifest(dir: &Path) -> Result<(Vec, Provenance, Vec, FileTable), Refusal> { let mpath = dir.join("manifest.json"); let mname = "manifest.json"; if !mpath.is_file() { @@ -717,6 +758,14 @@ fn verify_dir(dir: &Path) -> Result { f.read_exact(&mut mbytes).map_err(|e| r(format!("cannot read: {e}")))?; let manifest = parse_json(&mbytes).map_err(r)?; let (provenance, cases, files) = parse_manifest(&manifest).map_err(r)?; + Ok((mbytes, provenance, cases, files)) +} + +/// The reader rule. Everything in the directory is checked before anything is used; any problem refuses the whole directory. +fn verify_dir(dir: &Path) -> Result { + let mname = "manifest.json"; + let r = |reason: String| Refusal::new(mname, reason); + let (mbytes, provenance, cases, files) = read_manifest(dir)?; // the flat files table and the case entries must describe exactly the same files let mut expected: Vec<(&str, &str, u64)> = cases.iter().flat_map(case_files).collect(); expected.sort_unstable(); @@ -907,7 +956,7 @@ fn family_of(report: &[String]) -> Option<&'static str> { report.iter().find(|l| l.starts_with("cpu: process kernel family ")).map(|l| if l.starts_with("cpu: process kernel family AVX-512") { "avx512" } else { "avx2" }) } -fn cmd_run_tree(dir: &Path, tree: &str, out: &Path, pin: usize) -> Result { +fn cmd_run_tree(dir: &Path, tree: &str, out: &Path, pin: usize, only_case: Option<&str>) -> Result { let verified = verify_dir(dir).map_err(|e| e.to_string())?; let previous = rust_topology::pin_current_thread(pin as i32); if previous < 0 { @@ -924,12 +973,17 @@ fn cmd_run_tree(dir: &Path, tree: &str, out: &Path, pin: usize) -> Result, trees: Vec, tree: Option, + case: Option, } fn parse_options(args: &[String]) -> Result { - let mut o = Options { out: None, pin: 0, machine_role: None, trees: TREES.iter().map(|t| (*t).to_owned()).collect(), tree: None }; + let mut o = Options { out: None, pin: 0, machine_role: None, trees: TREES.iter().map(|t| (*t).to_owned()).collect(), tree: None, case: None }; let mut it = args.iter(); while let Some(a) = it.next() { let mut value = |what: &str| it.next().cloned().ok_or_else(|| format!("{what} needs a value")); @@ -1020,6 +1075,7 @@ fn parse_options(args: &[String]) -> Result { "--machine-role" => o.machine_role = Some(value("--machine-role")?), "--trees" => o.trees = value("--trees")?.split(',').map(str::to_owned).collect(), "--tree" => o.tree = Some(value("--tree")?), + "--case" => o.case = Some(value("--case")?), other => return Err(format!("unknown option {other}")), } } @@ -1052,6 +1108,7 @@ fn cmd_compare(dir: &Path, opts: &Options) -> Result { let records = out.join("records"); fs::create_dir_all(&records).map_err(|e| format!("{}: {e}", records.display()))?; let exe = std::env::current_exe().map_err(|e| format!("current_exe: {e}"))?; + let parent_env: Vec<(OsString, OsString)> = std::env::vars_os().collect(); let machine_role = opts.machine_role.clone().or_else(|| std::env::var("HOSTNAME").ok()).or_else(|| std::env::var("COMPUTERNAME").ok()).unwrap_or_else(|| "unknown".to_owned()); let (rustc_version, triple) = rustc_info(); let flags = format!("cargo profile {}; RUSTFLAGS={:?}; target-cpu default", if cfg!(debug_assertions) { "dev" } else { "release" }, std::env::var("RUSTFLAGS").unwrap_or_default()); @@ -1059,17 +1116,9 @@ fn cmd_compare(dir: &Path, opts: &Options) -> Result { let mut cells = 0usize; for tree in &opts.trees { let sibling = sibling_idle(opts.pin); - let mut cmd = Command::new(&exe); + let probe = Proc { imp: Impl::Rust, tree: TREES.iter().find(|t| **t == tree.as_str()).copied().unwrap_or("avx2"), rep: 'a' }; + let mut cmd = scrubbed_command(&exe, &parent_env, &cell_env(&probe)); cmd.arg("run-tree").arg(dir).args(["--tree", tree, "--out"]).arg(&out).args(["--pin", &opts.pin.to_string()]); - for (k, _) in std::env::vars() { - if k.starts_with("STRATA_") || k.starts_with("LELEKA_") { - cmd.env_remove(k); - } - } - cmd.env("LELEKA_CPU_POOL_PIN_HOST", "off"); - if tree == "avx2" { - cmd.env("STRATA_FORCE_AVX2", "1"); - } let res = cmd.output().map_err(|e| format!("cannot start the {tree} process: {e}"))?; let stdout = String::from_utf8_lossy(&res.stdout).into_owned(); let report: Vec = stdout.lines().filter_map(|l| l.strip_prefix("REPORT ")).map(str::to_owned).collect(); @@ -1131,15 +1180,1402 @@ fn cmd_compare(dir: &Path, opts: &Options) -> Result { Ok(if all_equal && cells > 0 { ExitCode::SUCCESS } else { ExitCode::from(1) }) } +// ------------------------------------------------------------------------------------------------ flags (time, alternate) + +struct Flags(Vec<(String, String)>); + +impl Flags { + fn parse(args: &[String], known: &[&str]) -> Result { + let mut items: Vec<(String, String)> = Vec::new(); + let mut it = args.iter(); + while let Some(a) = it.next() { + let name = a.strip_prefix("--").ok_or_else(|| format!("unexpected argument {a}"))?; + if !known.contains(&name) { + return Err(format!("unknown option {a}")); + } + if items.iter().any(|(k, _)| k == name) { + return Err(format!("option {a} given twice")); + } + let v = it.next().ok_or_else(|| format!("{a} needs a value"))?; + items.push((name.to_owned(), v.clone())); + } + Ok(Self(items)) + } + fn get(&self, k: &str) -> Option<&str> { + self.0.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str()) + } + fn req(&self, k: &str) -> Result<&str, String> { + self.get(k).ok_or_else(|| format!("--{k} is required")) + } + fn number(&self, k: &str) -> Result, String> { + self.get(k).map(|v| v.parse::().map_err(|_| format!("--{k} {v:?} is not a valid number"))).transpose() + } +} + +// ------------------------------------------------------------------------------------------------ clocks and host facts + +/// The 60 ms slice of `tq_cpu_parity.cpp:461` (`slice_ms = quick ? 40 : 60`), the same value `kab time` uses. +const DEFAULT_SLICE_MS: f64 = 60.0; +/// `tq_cpu_parity.cpp:303`: a slice whose calibrated clock moved by more than this fraction is dropped. Copied, not chosen here. +const CLOCK_MOVED_FRACTION: f64 = 0.05; +/// An SMT sibling busier than this fraction is not idle (the 5 percent rule of `sibling_idle`). +const SIBLING_BUSY_LIMIT: f64 = 0.05; +const ALIGN: usize = 4096; +/// Latency of a dependent 64-bit multiply in cycles on every core the A/B runs on (Intel Skylake to Golden Cove, AMD Zen 1 to 5). +const MUL_LATENCY_CYCLES: f64 = 3.0; +const CLOCK_METHOD: &str = "chain of dependent 64-bit multiplies (latency 3 cycles), 1000000 iterations of 4, ghz = 3 * 4e6 / (elapsed ns); before and after every slice"; + +fn mono_ns() -> u64 { + static ORIGIN: OnceLock = OnceLock::new(); + ORIGIN.get_or_init(Instant::now).elapsed().as_nanos() as u64 +} + +/// The core clock in GHz from a chain of dependent multiplies (safe code: the C++ chain of dependent adds needs inline assembly). The +/// constant is opaque to the optimiser, so the four multiplies per iteration stay four dependent instructions. +fn core_ghz() -> f64 { + let k = std::hint::black_box(0x9E37_79B9_7F4A_7C15u64 | 1); + let mut x = std::hint::black_box(1u64); + let n = 1_000_000u64; + let t0 = mono_ns(); + for _ in 0..n { + x = x.wrapping_mul(k); + x = x.wrapping_mul(k); + x = x.wrapping_mul(k); + x = x.wrapping_mul(k); + } + let dt = mono_ns().saturating_sub(t0).max(1); + std::hint::black_box(x); + MUL_LATENCY_CYCLES * 4.0 * n as f64 / dt as f64 +} + +fn median_of(v: &[f64]) -> f64 { + if v.is_empty() { + return 0.0; + } + let mut s = v.to_vec(); + s.sort_by(f64::total_cmp); + s[s.len() / 2] +} + +/// Nearest-rank percentile of raw slice values (a description of the slices, not an inference). +fn percentile_of(v: &[f64], p: f64) -> f64 { + if v.is_empty() { + return 0.0; + } + let mut s = v.to_vec(); + s.sort_by(f64::total_cmp); + s[((s.len() - 1) as f64 * p).round() as usize] +} + +fn jnum(v: f64, decimals: usize) -> String { + if v.is_finite() { format!("{v:.decimals$}") } else { "null".to_owned() } +} + +fn read_text(path: &str) -> String { + fs::read_to_string(path).map(|s| s.trim().to_owned()).unwrap_or_default() +} + +fn parse_cpu_list(s: &str) -> Vec { + let mut v = Vec::new(); + for part in s.trim().split(',').filter(|p| !p.is_empty()) { + let (a, b) = part.split_once('-').unwrap_or((part, part)); + if let (Ok(a), Ok(b)) = (a.trim().parse::(), b.trim().parse::()) { + v.extend(a..=b); + } + } + v +} + +fn parse_size(s: &str) -> u64 { + let digits: String = s.chars().take_while(char::is_ascii_digit).collect(); + let n = digits.parse::().unwrap_or(0); + match s[digits.len()..].chars().next() { + Some('K' | 'k') => n << 10, + Some('M' | 'm') => n << 20, + Some('G' | 'g') => n << 30, + _ => n, + } +} + +struct Llc { + level: u32, + bytes: u64, + source: String, +} + +/// Linux: the highest-level data or unified cache of `cpu` from sysfs. Elsewhere: None (the caller passes `--llc-bytes`). +fn llc_of_cpu(cpu: usize) -> Option { + let mut best: Option = None; + for i in 0..16 { + let d = format!("/sys/devices/system/cpu/cpu{cpu}/cache/index{i}"); + let (level, kind, size) = (read_text(&format!("{d}/level")), read_text(&format!("{d}/type")), read_text(&format!("{d}/size"))); + if level.is_empty() || size.is_empty() || kind == "Instruction" { + continue; + } + let level_n = level.parse::().unwrap_or(0); + if best.as_ref().is_none_or(|b| level_n >= b.level) { + best = Some(Llc { level: level_n, bytes: parse_size(&size), source: format!("{d}/size = {size}") }); + } + } + best.filter(|l| l.bytes > 0) +} + +/// (busy, total) jiffies of one logical CPU from /proc/stat (Linux). +fn proc_stat_cpu(cpu: usize) -> Option<(u64, u64)> { + let stat = fs::read_to_string("/proc/stat").ok()?; + let line = stat.lines().find(|l| l.starts_with(&format!("cpu{cpu} ")))?; + let f: Vec = line.split_whitespace().skip(1).filter_map(|x| x.parse().ok()).collect(); + let total: u64 = f.iter().take(8).sum(); + Some((total - f.get(3)? - f.get(4).copied().unwrap_or(0), total)) +} + +fn busy_fraction(before: Option<(u64, u64)>, after: Option<(u64, u64)>) -> Option { + let (b, a) = (before?, after?); + (a.1 > b.1).then(|| (a.0.saturating_sub(b.0)) as f64 / (a.1 - b.1) as f64) +} + +/// Linux: the logical CPU the calling thread last ran on (field 39 of /proc/thread-self/stat). Elsewhere: None. +fn current_cpu() -> Option { + if !cfg!(target_os = "linux") { + return None; + } + let s = fs::read_to_string("/proc/thread-self/stat").ok()?; + let rest = &s[s.rfind(')')? + 1..]; + rest.split_whitespace().nth(36)?.parse().ok() +} + +/// Linux: every thread of this process with the CPU it last ran on (the pool's worker is one of them). +fn observed_threads() -> Vec<(String, Option)> { + let mut v = Vec::new(); + if let Ok(dir) = fs::read_dir("/proc/self/task") { + for e in dir.flatten() { + let p = e.path(); + let name = read_text(&format!("{}/comm", p.display())); + let cpu = fs::read_to_string(p.join("stat")).ok().and_then(|s| s.get(s.rfind(')')? + 1..)?.split_whitespace().nth(36)?.parse().ok()); + v.push((name, cpu)); + } + } + v.sort(); + v +} + +fn is_managed_name(name: &str) -> bool { + let up = name.to_ascii_uppercase(); + up.starts_with("STRATA_") || up.starts_with("LELEKA_") +} + +/// Every STRATA_* / LELEKA_* variable the process sees. +fn managed_env_now() -> BTreeMap { + std::env::vars_os().filter_map(|(k, v)| Some((k.into_string().ok()?, v.into_string().ok()?))).filter(|(k, _)| is_managed_name(k)).collect() +} + +fn json_env(env: &BTreeMap) -> String { + format!("{{{}}}", env.iter().map(|(k, v)| format!("{}: {}", jstr(k), jstr(v))).collect::>().join(", ")) +} + +// ------------------------------------------------------------------------------------------------ time (one fresh process) + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum RegimeSel { + Both, + Resident, + Streamed, +} + +#[derive(Debug)] +struct TimeArgs { + dir: PathBuf, + case: String, + slices: usize, + pin: usize, + out: PathBuf, + slice_ms: f64, + regime: RegimeSel, + llc_bytes: Option, +} + +const TIME_FLAGS: [&str; 8] = ["run-dir", "case", "slices", "pin", "out", "slice-ms", "regime", "llc-bytes"]; + +/// The command line of `kab time` (STRA-317), checked the same way. +fn parse_time_args(args: &[String]) -> Result { + let f = Flags::parse(args, &TIME_FLAGS)?; + let slices = f.number::("slices")?.ok_or("--slices is required")?; + let pin = f.number::("pin")?.ok_or("--pin is required")?; + let slice_ms = f.number::("slice-ms")?.unwrap_or(DEFAULT_SLICE_MS); + if !(1..=100_000).contains(&slices) { + return Err("--slices must be 1..100000".to_owned()); + } + if !(1.0..=10_000.0).contains(&slice_ms) { + return Err("--slice-ms must be 1..10000".to_owned()); + } + let regime = match f.get("regime").unwrap_or("both") { + "both" => RegimeSel::Both, + "resident" => RegimeSel::Resident, + "streamed" => RegimeSel::Streamed, + _ => return Err("--regime must be both, resident or streamed".to_owned()), + }; + let case = f.req("case")?.to_owned(); + if !valid_id(&case) { + return Err(format!("--case {case:?} is not a plain identifier")); + } + Ok(TimeArgs { + dir: PathBuf::from(f.req("run-dir")?), + case, + slices, + pin, + out: PathBuf::from(f.req("out")?), + slice_ms, + regime, + llc_bytes: f.number::("llc-bytes")?, + }) +} + +/// A buffer whose usable part starts on a 4096-byte boundary. +struct Arena { + buf: Vec, + off: usize, +} +impl Arena { + fn new(len: usize) -> Self { + let size = std::mem::size_of::(); + let buf = vec![T::default(); len + ALIGN / size]; + let misalign = buf.as_ptr() as usize % ALIGN; + let off = if misalign == 0 { 0 } else { (ALIGN - misalign) / size }; + Self { buf, off } + } + fn slice(&self, len: usize) -> &[T] { + &self.buf[self.off..self.off + len] + } + fn slice_mut(&mut self, len: usize) -> &mut [T] { + &mut self.buf[self.off..self.off + len] + } +} + +/// The timed call: one group of one expert through the crate's public pool, exactly as `compute_case` does it. +struct Timed<'a> { + pool: DirectCpuPool, + gu: GateUpFormat, + down: DownFormat, + header: InHeader, + pairs: Vec<(usize, usize)>, + tokens: &'a [f32], + out: Vec, +} + +impl Timed<'_> { + fn call(&mut self, weights: &[u8]) -> Result<(), String> { + let (g, u) = (self.header.gate, self.header.up); + let expert = BorrowedExpert { gate: &weights[..g], up: &weights[g..g + u], down: &weights[g + u..g + u + self.header.down_bytes], pairs: &self.pairs }; + let experts = [expert]; + let group = BorrowedGroup { tokens: self.tokens, experts: &experts, stride: 1 }; + self.pool.compute_group(self.gu, self.down, &group, &mut self.out).map_err(|e| format!("compute_group failed: {e:?}")) + } +} + +struct Slice { + calls: u64, + wall_ns: u64, + ns_per_call: f64, + ghz_before: f64, + ghz_after: f64, + cycles_per_call: f64, + moved: bool, +} + +/// One slice of `ms` milliseconds cycling over the copies; the shape of `time_slice()` in tq_cpu_parity.cpp (lines 290-304). +fn time_slice(t: &mut Timed, copies: &[&[u8]], ms: f64, next: &mut usize) -> Result { + let ghz_before = core_ghz(); + let mut calls = 0u64; + let ns0 = mono_ns(); + let mut ns1; + loop { + t.call(copies[*next % copies.len()])?; + *next += 1; + calls += 1; + ns1 = mono_ns(); + if (ns1 - ns0) as f64 >= ms * 1e6 && calls >= 2 { + break; + } + } + let ghz_after = core_ghz(); + let wall = ns1 - ns0; + let ns_per_call = wall as f64 / calls as f64; + let ghz_mean = 0.5 * (ghz_before + ghz_after); + Ok(Slice { + calls, + wall_ns: wall, + ns_per_call, + ghz_before, + ghz_after, + cycles_per_call: ns_per_call * ghz_mean, + moved: ghz_mean > 0.0 && (ghz_after - ghz_before).abs() > CLOCK_MOVED_FRACTION * ghz_before, + }) +} + +fn slice_json(s: &Slice, idx: usize) -> String { + format!( + "{{\"i\": {idx}, \"calls\": {}, \"wall_ns\": {}, \"ns_per_call\": {}, \"ghz_before\": {}, \"ghz_after\": {}, \"cycles_per_call\": {}}}", + s.calls, + s.wall_ns, + jnum(s.ns_per_call, 3), + jnum(s.ghz_before, 6), + jnum(s.ghz_after, 6), + jnum(s.cycles_per_call, 1) + ) +} + +/// Slices with their index within the regime. +type Numbered = Vec<(usize, Slice)>; + +struct RegimeRun { + json: String, + kept: usize, + ok: bool, +} + +struct RegimeSpec<'a> { + label: &'a str, + copies: Vec<&'a [u8]>, + expert_bytes: usize, + stride: usize, + llc: &'a Llc, + slices: usize, + slice_ms: f64, + pin: usize, + selfcheck: bool, +} + +fn run_regime(t: &mut Timed, spec: &RegimeSpec) -> Result { + let mut next = 0usize; + // warm-up (not recorded): tables and buffers, and for STREAMED one full pass over the copies so every page is resident + for _ in 0..3 { + t.call(spec.copies[next % spec.copies.len()])?; + next += 1; + } + if spec.copies.len() > 1 { + for _ in 0..spec.copies.len() { + t.call(spec.copies[next % spec.copies.len()])?; + next += 1; + } + } + let (mut kept, mut dropped): (Numbered, Numbered) = (Vec::new(), Vec::new()); + let mut migrated: Option = cfg!(target_os = "linux").then_some(0); + for i in 0..spec.slices { + let before = current_cpu(); + let s = time_slice(t, &spec.copies, spec.slice_ms, &mut next)?; + if let Some(m) = migrated.as_mut() + && (before != Some(spec.pin) || current_cpu() != Some(spec.pin)) + { + *m += 1; + } + if s.moved { dropped.push((i, s)) } else { kept.push((i, s)) } + } + let ns: Vec = kept.iter().map(|k| k.1.ns_per_call).collect(); + let cyc: Vec = kept.iter().map(|k| k.1.cycles_per_call).collect(); + let med = |v: &[f64], d: usize| if v.is_empty() { "null".to_owned() } else { jnum(median_of(v), d) }; + let list = |v: &[(usize, Slice)]| v.iter().map(|(i, s)| slice_json(s, *i)).collect::>().join(",\n "); + let json = format!( + "{{\"regime\": {}, \"copies_k\": {}, \"expert_bytes\": {}, \"copy_stride_bytes\": {}, \"working_set_bytes\": {}, \"llc_level\": {}, \"llc_bytes\": {}, \"llc_source\": {}, \"working_set_over_llc\": {}, \"slice_ms\": {}, \"slices_requested\": {}, \"slices_kept\": {}, \"dropped_count\": {}, \"selfcheck_bitwise_equal_first_call\": {}, \"migrated_slices\": {}, \"median_ns_per_call\": {}, \"median_cycles_per_call\": {},\n \"slices\": [\n {}],\n \"dropped\": [\n {}]}}", + jstr(spec.label), + spec.copies.len(), + spec.expert_bytes, + spec.stride, + spec.expert_bytes * spec.copies.len(), + spec.llc.level, + spec.llc.bytes, + jstr(&spec.llc.source), + spec.copies.len() > 1, + jnum(spec.slice_ms, 1), + spec.slices, + kept.len(), + dropped.len(), + spec.selfcheck, + migrated.map_or("null".to_owned(), |m| m.to_string()), + med(&ns, 3), + med(&cyc, 1), + list(&kept), + list(&dropped) + ); + Ok(RegimeRun { json, kept: kept.len(), ok: !kept.is_empty() && migrated.is_none_or(|m| m == 0) }) +} + +fn f32_bits_sha(values: &[f32]) -> String { + let mut b = Vec::with_capacity(values.len() * 4); + for v in values { + b.extend_from_slice(&v.to_bits().to_le_bytes()); + } + sha_hex(&b) +} + +/// `kernel_ab time ...`: one fresh process, one case, the resident and the streamed regime, JSON written by tmp + rename. Exit codes as +/// `kab time`: 0 ok; 1 usage / refused input; 3 a regime kept no slice or a slice migrated off the pin; 4 the final output differs. +fn cmd_time(args: &[String]) -> Result { + let t = parse_time_args(args)?; + let wall0 = mono_ns(); + // pin first (before any buffer or pool exists, so the pool's threads inherit the mask), then the facts about the pin + if rust_topology::pin_current_thread(t.pin as i32) < 0 { + return Err(format!("the pin to CPU {} was refused", t.pin)); + } + if cfg!(target_os = "linux") && current_cpu() != Some(t.pin) { + return Err(format!("the process is not running on CPU {} after the pin", t.pin)); + } + let cpu_dir = format!("/sys/devices/system/cpu/cpu{}", t.pin); + let sib_text = read_text(&format!("{cpu_dir}/topology/thread_siblings_list")); + let sibling = parse_cpu_list(&sib_text).into_iter().rfind(|c| *c != t.pin); + let sib0 = sibling.and_then(proc_stat_cpu); + let pin0 = proc_stat_cpu(t.pin); + let load0 = read_text("/proc/loadavg"); + + // the case: the KAB1 reader rule (validate, then use) and the manifest and case input hashes + let (manifest_bytes, _provenance, cases, _files) = read_manifest(&t.dir).map_err(|e| e.to_string())?; + let manifest_sha = sha_hex(&manifest_bytes); + let entry = cases.iter().find(|c| c.id == t.case).ok_or_else(|| format!("case {} is not in the manifest", t.case))?; + let case = read_case_in(&t.dir, entry).map_err(|e| e.to_string())?; + let header = case.header; + let weights = &case.blob[IN_HEADER..header.input_at()]; + let expert_bytes = weights.len(); + + // environment and tree + let env = managed_env_now(); + let report = cpu_kernel_report(); + let tree = family_of(&report).ok_or("no process kernel family line in cpu_kernel_report")?; + + // the streamed set: K copies, K x stride at least 2 x the last-level cache of the pinned CPU (the design choice of kab_time.cpp) + let llc = match (t.llc_bytes, llc_of_cpu(t.pin)) { + (Some(bytes), found) => Llc { level: found.map_or(0, |l| l.level), bytes, source: "--llc-bytes (override)".to_owned() }, + (None, Some(l)) => l, + (None, None) => return Err(format!("cannot read the last-level cache size of CPU {} from sysfs; pass --llc-bytes", t.pin)), + }; + if llc.bytes == 0 { + return Err("--llc-bytes must be positive".to_owned()); + } + let stride = expert_bytes.div_ceil(ALIGN) * ALIGN; + let copies_k = ((2 * llc.bytes) / stride as u64) as usize + 1; + if copies_k * stride > (4usize << 30) { + return Err("the streamed working set would exceed 4 GiB; check --llc-bytes".to_owned()); + } + + // the pool is created AFTER the pin: its worker inherits the one-CPU mask (rust_platform::cores sees a one-CPU affinity) + let mut pool = DirectCpuPool::new(1).map_err(|e| format!("DirectCpuPool::new(1) failed: {e:?}"))?; + let want = compute_case(&mut pool, &case)?; + let want_bits: Vec = want.iter().map(|v| v.to_bits()).collect(); + let output_sha = f32_bits_sha(&want); + + let mut tokens = Arena::::new(header.rows * H); + tokens.slice_mut(header.rows * H).copy_from_slice(&case.input()); + let mut resident = Arena::::new(stride); + resident.slice_mut(expert_bytes).copy_from_slice(weights); + let mut streamed = Arena::::new(stride * copies_k); + for k in 0..copies_k { + streamed.slice_mut(stride * copies_k)[k * stride..k * stride + expert_bytes].copy_from_slice(weights); + } + let res_copies: Vec<&[u8]> = vec![resident.slice(expert_bytes)]; + let stm_all = streamed.slice(stride * copies_k); + let stm_copies: Vec<&[u8]> = (0..copies_k).map(|k| &stm_all[k * stride..k * stride + expert_bytes]).collect(); + + let mut timed = Timed { + pool, + gu: gate_up_row(header.gu).ok_or("gate/up type")?.1, + down: down_row(header.down).ok_or("down type")?.1, + header, + pairs: (0..header.rows).map(|r| (r, 0)).collect(), + tokens: tokens.slice(header.rows * H), + out: vec![0.0f32; header.rows * H], + }; + // selfcheck: the timed call's output on every aligned copy is bit-identical to the first (unaligned) call's + let mut selfcheck = true; + for w in [res_copies[0], stm_copies[0], stm_copies[copies_k - 1]] { + timed.call(w)?; + selfcheck &= timed.out.iter().map(|v| v.to_bits()).eq(want_bits.iter().copied()); + } + if !selfcheck { + return Err("selfcheck failed: the timed call differs from the first call".to_owned()); + } + + let ghz0 = core_ghz(); + let mut regimes = Vec::new(); + let mut all_ok = true; + let (mut kept_res, mut kept_stm) = (0, 0); + for (label, copies, sel) in [("RESIDENT", &res_copies, RegimeSel::Resident), ("STREAMED", &stm_copies, RegimeSel::Streamed)] { + if t.regime != RegimeSel::Both && t.regime != sel { + continue; + } + let spec = RegimeSpec { label, copies: copies.clone(), expert_bytes, stride, llc: &llc, slices: t.slices, slice_ms: t.slice_ms, pin: t.pin, selfcheck }; + let r = run_regime(&mut timed, &spec)?; + all_ok &= r.ok; + if sel == RegimeSel::Resident { kept_res = r.kept } else { kept_stm = r.kept } + regimes.push(r.json); + } + let ghz1 = core_ghz(); + timed.call(res_copies[0])?; + let final_same = timed.out.iter().map(|v| v.to_bits()).eq(want_bits.iter().copied()); + + let threads = observed_threads(); + let sib1 = sibling.and_then(proc_stat_cpu); + let pin1 = proc_stat_cpu(t.pin); + let frac = |f: Option| f.map_or("null".to_owned(), |v| jnum(v, 4)); + let rust_fmt = |l: &str| jstr(l); + let (gu_name, down_name) = (gate_up_row(header.gu).map_or("?", |x| x.4), down_row(header.down).map_or("?", |x| x.4)); + let in_name = format!("case-{}.in", t.case); + let command_line = format!( + "time --run-dir {} --case {} --slices {} --pin {} --out {}{}{}", + t.dir.display(), + t.case, + t.slices, + t.pin, + t.out.display(), + if args.iter().any(|a| a == "--slice-ms") { format!(" --slice-ms {}", t.slice_ms) } else { String::new() }, + match t.regime { + RegimeSel::Both => String::new(), + RegimeSel::Resident => " --regime resident".to_owned(), + RegimeSel::Streamed => " --regime streamed".to_owned(), + } + ); + let mut j = String::from("{\n \"format\": \"KAB1-time\",\n \"version\": 1,\n \"mode\": \"time\",\n \"writer\": \"rust\",\n"); + j += &format!(" \"command_line\": {},\n \"run_dir\": {},\n \"manifest_sha256\": {},\n", jstr(&command_line), jstr(&t.dir.display().to_string()), jstr(&manifest_sha)); + j += &format!( + " \"case\": {{\"id\": {}, \"gu_type\": {}, \"down_type\": {}, \"gu_name\": {}, \"down_name\": {}, \"rows\": {}, \"input_file\": {}, \"input_sha256\": {}, \"input_sha256_matches_manifest\": true, \"expert_bytes\": {}}},\n", + jstr(&t.case), + header.gu, + header.down, + jstr(gu_name), + jstr(down_name), + header.rows, + jstr(&in_name), + jstr(&entry.in_sha256), + expert_bytes + ); + j += &format!( + " \"tree\": {},\n \"tree_detail\": {{\"tree\": {}, \"cpu_report\": [{}], \"strata_env\": {}}},\n \"effective_env\": {},\n", + jstr(tree), + jstr(tree), + report.iter().map(|l| rust_fmt(l)).collect::>().join(", "), + json_env(&env), + json_env(&env) + ); + j += &format!( + " \"pool\": {{\"workers\": 1, \"host_drains\": true, \"threads_observed\": [{}], \"note\": \"DirectCpuPool::new(1): one worker thread plus the calling thread that drains beside it (pool.cpp host_works_); both inherit the one-CPU mask of the pin\"}},\n", + threads.iter().map(|(n, c)| format!("{{\"name\": {}, \"cpu\": {}}}", jstr(n), c.map_or("null".to_owned(), |c| c.to_string()))).collect::>().join(", ") + ); + j += &format!( + " \"pin\": {{\"cpu\": {}, \"thread_siblings_list\": {}, \"sibling_cpu\": {}, \"physical_core_id\": {}, \"pin_busy_fraction_during_run\": {}, \"sibling_busy_fraction_during_run\": {}, \"sibling_busy_note\": \"/proc/stat jiffies of the sibling logical CPU between the start and the end of this process; it is recorded, no threshold is applied here\", \"scaling_governor\": {}, \"cpufreq_boost\": {}, \"loadavg_start\": {}, \"loadavg_end\": {}, \"final_cpu\": {}}},\n", + t.pin, + jstr(&sib_text), + sibling.map_or("null".to_owned(), |s| s.to_string()), + jstr(&read_text(&format!("{cpu_dir}/topology/core_id"))), + frac(busy_fraction(pin0, pin1)), + if sibling.is_some() { frac(busy_fraction(sib0, sib1)) } else { "null".to_owned() }, + jstr(&read_text(&format!("{cpu_dir}/cpufreq/scaling_governor"))), + jstr(&read_text("/sys/devices/system/cpu/cpufreq/boost")), + jstr(&load0), + jstr(&read_text("/proc/loadavg")), + current_cpu().map_or("null".to_owned(), |c| c.to_string()) + ); + j += &format!(" \"buffers\": {{\"alignment_bytes\": {ALIGN}, \"expert_copy_stride_bytes\": {stride}, \"activations_aligned\": true, \"scratch_aligned\": false, \"scratch_note\": \"the pool's own scratch is allocated inside the crate\"}},\n"); + j += &format!( + " \"clock_calibration\": {{\"method\": {}, \"source\": \"engine/strata/src/kernels/cpu/tq_cpu_parity.cpp --bench: core_ghz() lines 273-284, time_slice() lines 290-304; the dependent-add chain needs inline assembly, so the safe Rust twin chains multiplies\", \"drop_rule\": {{\"source_file\": \"engine/strata/src/kernels/cpu/tq_cpu_parity.cpp\", \"source_line\": 303, \"source_text\": \"std::fabs(g1 - g0) > 0.05 * g0\", \"fraction\": {}, \"meaning\": \"a slice whose calibrated clock moved by more than 5 percent between its before and after calibration is dropped\"}}, \"slice_ms_source\": \"tq_cpu_parity.cpp:461 slice_ms = quick ? 40 : 60\", \"ghz_at_start\": {}, \"ghz_at_end\": {}, \"tsc_invariant\": null, \"clocks\": \"monotonic ns (std::time::Instant); no TSC read: rdtsc and lfence are unsafe intrinsics and the crate keeps unsafe_code = deny\"}},\n", + jstr(CLOCK_METHOD), + jnum(CLOCK_MOVED_FRACTION, 2), + jnum(ghz0, 6), + jnum(ghz1, 6) + ); + j += &format!( + " \"build\": {{\"profile\": {}, \"rustflags\": {}, \"example\": \"crates/native-cpu-expert/examples/kernel_ab.rs\"}},\n", + jstr(if cfg!(debug_assertions) { "dev" } else { "release" }), + jstr(&std::env::var("RUSTFLAGS").unwrap_or_default()) + ); + j += &format!( + " \"selfcheck_bitwise_equal_first_call\": {selfcheck},\n \"final_output_unchanged\": {final_same},\n \"output_sha256\": {},\n \"duration_ns\": {},\n \"timing_caveat\": \"numbers from a shared host are not evidence by themselves; loadavg and the sibling busy fraction are recorded above\",\n \"regimes\": [\n {}\n ]\n}}\n", + jstr(&output_sha), + mono_ns() - wall0, + regimes.join(",\n ") + ); + let tmp = PathBuf::from(format!("{}.tmp", t.out.display())); + fs::write(&tmp, j.as_bytes()).map_err(|e| format!("{}: {e}", tmp.display()))?; + fs::rename(&tmp, &t.out).map_err(|e| format!("rename to {}: {e}", t.out.display()))?; + println!("kernel_ab time: case={} tree={tree} pin={} slices={} resident_kept={kept_res} streamed_kept={kept_stm} K={copies_k} out={}", t.case, t.pin, t.slices, t.out.display()); + if !all_ok { + eprintln!("kernel_ab time: a regime has no kept slice or a slice migrated off CPU {}", t.pin); + return Ok(ExitCode::from(3)); + } + if !final_same { + eprintln!("kernel_ab time: the final output differs from the first call's"); + return Ok(ExitCode::from(4)); + } + Ok(ExitCode::SUCCESS) +} + +// ------------------------------------------------------------------------------------------------ alternate: cells, environment, schedule + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] +enum Impl { + Cpp, + Rust, +} +impl Impl { + fn name(self) -> &'static str { + match self { + Impl::Cpp => "cpp", + Impl::Rust => "rust", + } + } +} + +/// One process of a round: an implementation, a tree and a replicate (`a` is the A/B process, `b` the A/A twin). +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] +struct Proc { + imp: Impl, + tree: &'static str, + rep: char, +} +impl Proc { + fn name(&self) -> String { + format!("{}-{}-{}", self.imp.name(), self.tree, self.rep) + } + 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. +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 Rust cells keep the pool from re-pinning its caller (the pin is the requested +/// one); the avx2 trees set `STRATA_FORCE_AVX2=1`, which both implementations honour. +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.sort(); + v +} + +/// A command whose environment is exactly: the parent's variables minus every STRATA_* / LELEKA_* one, plus the cell's variables. +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. +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))) +} + +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). +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 +} + +const SCHEDULE_MAGIC: &str = "# KAB1-alt schedule v1"; + +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. +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). +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()) +} + +// ------------------------------------------------------------------------------------------------ alternate: reading a process's JSON + +#[derive(Debug, Clone)] +struct RegimeStat { + copies_k: usize, + expert_bytes: usize, + llc_bytes: u64, + requested: usize, + dropped: usize, + median_ns: f64, + median_cycles: f64, + ns: Vec, + cycles: Vec, + max_drift: f64, + selfcheck: bool, +} + +#[derive(Debug, Clone)] +struct ProcOut { + proc: Proc, + regimes: BTreeMap, + ghz_start: f64, + ghz_end: f64, + /// None: unknown; Some(true): the sibling was idle (or there is none) under the 5 percent rule. + sibling_idle: Option, + final_unchanged: bool, + output_sha: Option, + tree_text: String, + cpu_model: Option, +} + +/// What a process's JSON must say about the run that produced it. +struct Expect<'a> { + manifest_sha: &'a str, + input_sha: &'a str, + case: &'a str, + pin: usize, +} + +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)?, + }) +} + +fn describe_cpp_tree(d: &Json) -> String { + let b = |k: &str| d.get(k).map_or("?".to_owned(), |v| match v { + Json::Bool(x) => x.to_string(), + Json::Num(n) => n.clone(), + _ => "?".to_owned(), + }); + let env = match d.get("strata_env") { + Some(Json::Obj(items)) if !items.is_empty() => items.iter().map(|(k, v)| format!("{k}={}", if let Json::Str(s) = v { s.as_str() } else { "?" })).collect::>().join(" "), + _ => "no STRATA_* variable set (STRATA_NO_IQ512, STRATA_NO_IQ256 and STRATA_IQ_GATHER unset)".to_owned(), + }; + format!("avx2_ok={} avx512_ok={} iq512_gather_on={} iq256_gather_setting={}; {env}", b("avx2_ok"), b("avx512_ok"), b("iq512_gather_on"), b("iq256_gather_setting")) +} + +/// Parses a process's KAB1-time JSON and checks it against the cell that was started: writer, tree, manifest and input hashes, case, +/// pin, and that the effective STRATA_* / LELEKA_* environment is exactly the cell's. +fn parse_proc_json(p: &Proc, bytes: &[u8], expect: &Expect) -> Result { + let j = parse_json(bytes)?; + let name = p.name(); + let fail = |what: String| format!("cell {name}: {what}"); + if j.str("format").map_err(fail)? != "KAB1-time" || j.uint("version").map_err(fail)? != 1 { + return Err(fail("the output is not KAB1-time version 1".to_owned())); + } + if j.str("writer").map_err(fail)? != p.imp.name() { + return Err(fail(format!("the output's writer is {:?}, expected {}", j.str("writer").unwrap_or("?"), p.imp.name()))); + } + if j.str("tree").map_err(fail)? != p.tree { + return Err(fail(format!("the process ran the {} tree, the cell asks for {}", j.str("tree").unwrap_or("?"), p.tree))); + } + if j.str("manifest_sha256").map_err(fail)? != expect.manifest_sha { + return Err(fail("manifest_sha256 differs from the run directory's".to_owned())); + } + let c = j.req("case").map_err(fail)?; + if c.str("id").map_err(fail)? != expect.case || c.str("input_sha256").map_err(fail)? != expect.input_sha { + return Err(fail("the case id or its input hash differs from the manifest's".to_owned())); + } + let pin = j.req("pin").map_err(fail)?; + if pin.uint("cpu").map_err(fail)? as usize != expect.pin { + return Err(fail(format!("pinned to CPU {}, expected {}", pin.uint("cpu").unwrap_or(u64::MAX), expect.pin))); + } + let want_env: BTreeMap = cell_env(p).into_iter().collect(); + let mut seen_env = BTreeMap::new(); + if let Json::Obj(items) = j.req("effective_env").map_err(fail)? { + for (k, v) in items { + seen_env.insert(k.clone(), match v { + Json::Str(s) => s.clone(), + Json::Num(n) => n.clone(), + _ => "?".to_owned(), + }); + } + } + if seen_env != want_env { + return Err(fail(format!("effective environment {seen_env:?} differs from the cell's {want_env:?}"))); + } + let mut regimes = BTreeMap::new(); + for r in j.array("regimes").map_err(fail)? { + let label = r.str("regime").map_err(fail)?.to_owned(); + regimes.insert(label, parse_regime(r, p.imp).map_err(fail)?); + } + for want in ["RESIDENT", "STREAMED"] { + if !regimes.contains_key(want) { + return Err(fail(format!("regime {want} is missing"))); + } + } + let clock = j.req("clock_calibration").map_err(fail)?; + let sibling_idle = match pin.req("sibling_cpu").map_err(fail)? { + Json::Null => Some(true), + _ => pin.float_or_null("sibling_busy_fraction_during_run").map_err(fail)?.map(|f| f < SIBLING_BUSY_LIMIT), + }; + let detail = j.req("tree_detail").map_err(fail)?; + let (tree_text, cpu_report) = if p.imp == Impl::Rust { + let report: Vec = detail.array("cpu_report").map_err(fail)?.iter().filter_map(|l| if let Json::Str(s) = l { Some(s.clone()) } else { None }).collect(); + let line = report.iter().find(|l| l.starts_with("cpu: process kernel family")).cloned().ok_or_else(|| fail("no process kernel family line".to_owned()))?; + (format!("leleka-serve {line}"), report) + } else { + (describe_cpp_tree(detail), Vec::new()) + }; + let cpu_model = (!cpu_report.is_empty()).then(|| cpu_model_of(&cpu_report)); + Ok(ProcOut { + proc: *p, + regimes, + ghz_start: clock.float("ghz_at_start").map_err(fail)?, + ghz_end: clock.float("ghz_at_end").map_err(fail)?, + sibling_idle, + final_unchanged: j.flag("final_output_unchanged").map_err(fail)?, + output_sha: j.get("output_sha256").and_then(|v| if let Json::Str(s) = v { Some(s.clone()) } else { None }), + tree_text, + cpu_model, + }) +} + +// ------------------------------------------------------------------------------------------------ alternate: round records + +struct Tool { + compiler: String, + version: String, + triple: String, + flags: String, +} + +struct SideStat { + median: f64, + p05: f64, + p95: f64, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Kind { + Ab, + AaCpp, + AaRust, +} +impl Kind { + fn slug(self) -> &'static str { + match self { + Kind::Ab => "ab", + Kind::AaCpp => "aa-cpp", + Kind::AaRust => "aa-rust", + } + } +} + +/// Everything a round record needs that does not change within a batch. +struct BatchCtx<'a> { + verified: &'a Verified, + case: &'a CaseEntry, + pin: usize, + machine_role: String, + os: String, + cpu_model: String, + started_utc: String, + rust_tool: Tool, + batch: u32, + /// Equality of our tree against the C++ reference per tree, from the equality phase. + equality: &'a BTreeMap<&'static str, Outcome>, +} + +fn side_stat(r: &RegimeStat, cycles: bool) -> SideStat { + let v = if cycles { &r.cycles } else { &r.ns }; + SideStat { median: if cycles { r.median_cycles } else { r.median_ns }, p05: percentile_of(v, 0.05), p95: percentile_of(v, 0.95) } +} + +fn stat_json(s: &SideStat) -> String { + format!("{{\"median\": {}, \"p05\": {}, \"p95\": {}}}", jnum(s.median, 6), jnum(s.p05, 6), jnum(s.p95, 6)) +} + +fn tool_json(t: &Tool) -> String { + format!("{{\"compiler\": {}, \"version\": {}, \"target_triple\": {}, \"flags\": {}}}", jstr(&t.compiler), jstr(&t.version), jstr(&t.triple), jstr(&t.flags)) +} + +fn equality_block(c: &CaseEntry, o: &Outcome) -> String { + let tolerance = c.tolerance.as_ref().map_or(String::new(), |t| { + format!( + ",\n \"tolerance\": {{\"value\": {:e}, \"basis\": {}, \"basis_written_utc\": {}}}", + t.value, + jstr(&format!("{} [metric: {TOLERANCE_METRIC}]", t.basis)), + jstr(&t.basis_written_utc) + ) + }); + format!( + "{{\n \"mode\": \"{}\",\n \"verdict\": \"{}\",\n \"compared_values\": {},\n \"mismatches\": {}{tolerance}\n }}", + if c.tolerance.is_some() { "tolerance" } else { "bitwise" }, + if o.equal() { "EQUAL" } else { "NOT_EQUAL" }, + o.compared, + o.mismatches + ) +} + +/// The A/A equality: the same implementation in two fresh processes. Rust: the output hashes of the two processes (and each one's +/// selfcheck); C++: each process's timed composition equals `compose_expert()` bit for bit (selfcheck), which is the same function. +fn aa_outcome(a: &ProcOut, b: &ProcOut, rows: usize) -> (Outcome, String) { + let compared = rows * H; + let selfchecks = a.regimes.values().chain(b.regimes.values()).all(|r| r.selfcheck) && a.final_unchanged && b.final_unchanged; + let same = selfchecks && (a.proc.imp == Impl::Cpp || (a.output_sha.is_some() && a.output_sha == b.output_sha)); + let note = if a.proc.imp == Impl::Cpp { "selfcheck of both processes against compose_expert()" } else { "output sha256 of both processes" }; + let outcome = Outcome { compared, mismatches: usize::from(!same), differing_bits: usize::from(!same), max_abs_error: 0.0, first_mismatch: None }; + (outcome, note.to_owned()) +} + +/// The records of one round: per tree and regime the A/B record (ours = Rust `a`, reference = C++ `a`) and the two A/A records. +fn round_records(ctx: &BatchCtx, round_no: u32, done: &[ProcOut]) -> Result, String> { + let find = |imp: Impl, tree: &str, rep: char| done.iter().find(|p| p.proc.imp == imp && p.proc.tree == tree && p.proc.rep == rep).ok_or_else(|| format!("round {round_no}: process {}-{tree}-{rep} did not run", imp.name())); + let p = &ctx.verified.provenance; + let c = ctx.case; + let cpp_tool = Tool { compiler: p.compiler_id.clone(), version: p.compiler_version.clone(), triple: p.target_triple.clone(), flags: p.reference_flags.clone() }; + let (gu, down) = (gate_up_row(c.gu).map_or("?", |x| x.4), down_row(c.down).map_or("?", |x| x.4)); + let sibling_idle = done.iter().all(|d| d.sibling_idle == Some(true)); + let (first, last) = (done.first().ok_or("empty round")?, done.last().ok_or("empty round")?); + let mut files = Vec::new(); + let trees: Vec<&'static str> = TREES.iter().copied().filter(|t| done.iter().any(|d| d.proc.tree == *t)).collect(); + for tree in trees { + let (cpp_a, cpp_b, rust_a, rust_b) = (find(Impl::Cpp, tree, 'a')?, find(Impl::Cpp, tree, 'b')?, find(Impl::Rust, tree, 'a')?, find(Impl::Rust, tree, 'b')?); + for regime in ["RESIDENT", "STREAMED"] { + for kind in [Kind::Ab, Kind::AaCpp, Kind::AaRust] { + let (ours, reference, ours_tool, ref_tool) = match kind { + Kind::Ab => (rust_a, cpp_a, &ctx.rust_tool, &cpp_tool), + Kind::AaCpp => (cpp_a, cpp_b, &cpp_tool, &cpp_tool), + Kind::AaRust => (rust_a, rust_b, &ctx.rust_tool, &ctx.rust_tool), + }; + let (o, r) = (&ours.regimes[regime], &reference.regimes[regime]); + if (o.copies_k, o.expert_bytes, o.llc_bytes) != (r.copies_k, r.expert_bytes, r.llc_bytes) { + return Err(format!("round {round_no} {tree} {regime}: the streamed set differs between {} and {} (K {} vs {}, LLC {} vs {})", ours.proc.name(), reference.proc.name(), o.copies_k, r.copies_k, o.llc_bytes, r.llc_bytes)); + } + let (equality, equality_note) = match kind { + Kind::Ab => (equality_block(c, &ctx.equality[tree]), "Rust output against the C++ reference .out file of the run directory, from the equality phase of this batch".to_owned()), + _ => { + let (outcome, note) = aa_outcome(ours, reference, c.rows); + (aa_equality_block(&outcome), format!("{note}, the same implementation in two fresh processes")) + } + }; + let kernel = format!( + "routed-expert-gate-up-down {gu}+{down} rows={} regime {regime} ROUND RECORD {} (batch {}, round {round_no}); ours-slot process {}, reference-slot process {}; tree ours: {}; tree reference: {}; equality: {equality_note}; aa_noise_floor is a PLACEHOLDER (n=1, CI 0): the A/A evaluation is S0.10b, this record carries one round's medians only", + c.rows, + match kind { + Kind::Ab => "A/B (ours = Rust, reference = C++)", + Kind::AaCpp => "A/A (C++ process a in the ours slot, C++ process b in the reference slot)", + Kind::AaRust => "A/A (Rust process a in the ours slot, Rust process b in the reference slot)", + }, + ctx.batch, + ours.proc.name(), + reference.proc.name(), + ours.tree_text, + reference.tree_text + ); + let drift = o.max_drift.max(r.max_drift); + let streamed = if regime == "STREAMED" { format!(",\n \"streamed\": {{\"copies\": {}, \"expert_bytes\": {}, \"llc_bytes\": {}}}", o.copies_k, o.expert_bytes, o.llc_bytes) } else { String::new() }; + let rowtype = |unit: &str| format!("{gu}+{down} rows={} {} [{unit}]", c.rows, regime.to_ascii_lowercase()); + let json = format!( + "{{\n \"schema_version\": \"1\",\n \"level\": \"COMPONENT_KERNEL\",\n \"record_id\": {rid},\n \"created_utc\": {created},\n \"run_started_utc\": {started},\n \"machine\": {{\"machine_role\": {role}, \"cpu_model\": {cpu}, \"gpu_name\": \"none\", \"os\": {os}}},\n \"kernel\": {kernel},\n \"toolchain\": {{\n \"ours\": {ot},\n \"reference\": {rt}\n }},\n \"case_id\": {cid},\n \"input_sha256\": {insha},\n \"kab1_manifest_sha256\": {msha},\n \"tree\": {{\"ours\": {tree_q}, \"reference\": {tree_q}}},\n \"regime\": {regime_q}{streamed},\n \"pin\": {{\"logical_cpu\": {pin}, \"sibling_idle\": {sib}}},\n \"strata_upstream_commit\": {commit},\n \"clock_calibration\": {{\"method\": {method}, \"ghz_before\": {g0}, \"ghz_after\": {g1}, \"max_drift_fraction\": {drift}, \"slices_total\": {total}, \"slices_dropped\": {dropped}}},\n \"rows\": [\n {{\"row_type\": {rt_ns}, \"unit\": \"ns\", \"rounds\": 1, \"ours\": {on}, \"reference\": {rn}}},\n {{\"row_type\": {rt_cy}, \"unit\": \"cycles\", \"rounds\": 1, \"ours\": {oc}, \"reference\": {rc}}}\n ],\n \"aa_noise_floor\": {{\"ours_vs_ours\": {{\"n\": 1, \"ci95_low\": 0, \"ci95_high\": 0}}, \"reference_vs_reference\": {{\"n\": 1, \"ci95_low\": 0, \"ci95_high\": 0}}, \"floor_fraction\": 0}},\n \"equality\": {equality}\n}}\n", + rid = jstr(&format!("kab1alt-{}-{}-b{}-r{round_no:05}-{}-{tree}-{}", ctx.verified.provenance.run_id, c.id, ctx.batch, kind.slug(), regime.to_ascii_lowercase())), + created = jstr(&now_utc()), + started = jstr(&ctx.started_utc), + role = jstr(&ctx.machine_role), + cpu = jstr(&ctx.cpu_model), + os = jstr(&ctx.os), + kernel = jstr(&kernel), + ot = tool_json(ours_tool), + rt = tool_json(ref_tool), + cid = jstr(&c.id), + insha = jstr(&c.in_sha256), + msha = jstr(&ctx.verified.manifest_sha256), + tree_q = jstr(tree), + regime_q = jstr(®ime.to_ascii_lowercase()), + pin = ctx.pin, + sib = sibling_idle, + commit = jstr(&p.engine_strata_pin), + method = jstr(&format!("{CLOCK_METHOD}; ghz_before is the first process's ghz_at_start of the round ({}), ghz_after the last process's ghz_at_end ({}); max_drift_fraction is the largest |g1 - g0| / g0 over every slice of the two processes of this record, slices_total and slices_dropped count their requested and dropped slices", first.proc.name(), last.proc.name())), + g0 = jnum(first.ghz_start, 6), + g1 = jnum(last.ghz_end, 6), + drift = jnum(drift, 6), + total = o.requested + r.requested, + dropped = o.dropped + r.dropped, + rt_ns = jstr(&rowtype("ns")), + rt_cy = jstr(&rowtype("cycles")), + on = stat_json(&side_stat(o, false)), + rn = stat_json(&side_stat(r, false)), + oc = stat_json(&side_stat(o, true)), + rc = stat_json(&side_stat(r, true)), + ); + files.push((format!("r{round_no:05}.{}.{tree}.{}.json", kind.slug(), regime.to_ascii_lowercase()), json)); + } + } + } + Ok(files) +} + +fn aa_equality_block(o: &Outcome) -> String { + format!("{{\n \"mode\": \"bitwise\",\n \"verdict\": \"{}\",\n \"compared_values\": {},\n \"mismatches\": {}\n }}", if o.equal() { "EQUAL" } else { "NOT_EQUAL" }, o.compared, o.mismatches) +} + +// ------------------------------------------------------------------------------------------------ alternate: the runner + +const ALT_FLAGS: [&str; 13] = ["run-dir", "case", "rounds", "batch", "pin", "schedule", "seed", "out", "slices", "slice-ms", "llc-bytes", "machine-role", "kab"]; + +#[derive(Debug)] +struct AltArgs { + dir: PathBuf, + case: String, + rounds: u32, + batch: u32, + pin: usize, + schedule: PathBuf, + seed: u64, + out: Option, + slices: usize, + slice_ms: Option, + llc_bytes: Option, + machine_role: Option, + kab: Option, +} + +fn parse_alt_args(args: &[String]) -> Result { + let f = Flags::parse(args, &ALT_FLAGS)?; + let rounds = f.number::("rounds")?.ok_or("--rounds is required")?; + let batch = f.number::("batch")?.ok_or("--batch is required")?; + if !(1..=10_000).contains(&rounds) || !(1..=1000).contains(&batch) { + return Err("--rounds must be 1..10000 and --batch 1..1000 (the batch number, counted from 1)".to_owned()); + } + let case = f.req("case")?.to_owned(); + if !valid_id(&case) { + return Err(format!("--case {case:?} is not a plain identifier")); + } + let slices = f.number::("slices")?.unwrap_or(20); + if !(1..=100_000).contains(&slices) { + return Err("--slices must be 1..100000".to_owned()); + } + Ok(AltArgs { + dir: PathBuf::from(f.req("run-dir")?), + case, + rounds, + batch, + pin: f.number::("pin")?.ok_or("--pin is required")?, + schedule: PathBuf::from(f.req("schedule")?), + seed: f.number::("seed")?.unwrap_or(1), + out: f.get("out").map(PathBuf::from), + slices, + slice_ms: f.number::("slice-ms")?, + llc_bytes: f.number::("llc-bytes")?, + machine_role: f.get("machine-role").map(str::to_owned), + kab: f.get("kab").map(PathBuf::from), + }) +} + +fn create_new_file(path: &Path, bytes: &[u8]) -> Result<(), String> { + let mut f = fs::OpenOptions::new().write(true).create_new(true).open(path).map_err(|e| format!("{}: {e} (nothing is overwritten)", path.display()))?; + f.write_all(bytes).map_err(|e| format!("{}: {e}", path.display())) +} + +fn file_sha(path: &Path) -> Result { + fs::read(path).map(|b| sha_hex(&b)).map_err(|e| format!("{}: {e}", path.display())) +} + +fn ours_flags() -> String { + format!("cargo profile {}; RUSTFLAGS={:?}; target-cpu default", if cfg!(debug_assertions) { "dev" } else { "release" }, std::env::var("RUSTFLAGS").unwrap_or_default()) +} + +fn cmd_alternate(args: &[String]) -> Result { + let a = parse_alt_args(args)?; + let started = now_utc(); + let verified = match verify_dir(&a.dir) { + Ok(v) => v, + Err(e) => { + println!("{e}"); + return Ok(ExitCode::from(if e.incomplete { 2 } else { 1 })); + } + }; + let case = verified.cases.iter().find(|c| c.id == a.case).ok_or_else(|| format!("case {} is not in the manifest", a.case))?.clone(); + let out = a.out.clone().unwrap_or_else(|| { + let name = a.dir.file_name().map_or_else(|| "kab1".to_owned(), |n| n.to_string_lossy().into_owned()); + a.dir.parent().unwrap_or(Path::new(".")).join(format!("{name}.alt-{}", a.case)) + }); + let abs = |p: &Path| std::path::absolute(p).unwrap_or_else(|_| p.to_path_buf()); + if abs(&out).starts_with(abs(&a.dir)) || abs(&a.dir).starts_with(abs(&out)) { + return Err("--out must not contain or lie inside the KAB1 directory".to_owned()); + } + if inside_git_checkout(&out) || inside_git_checkout(&a.schedule) { + return Err("--out and --schedule must lie outside every Git checkout (generated artifacts stay out of Git)".to_owned()); + } + let own_exe = std::env::current_exe().map_err(|e| format!("current_exe: {e}"))?; + let kab = a.kab.clone().or_else(|| std::env::var_os("KAB").map(PathBuf::from)).unwrap_or_else(|| { + PathBuf::from(std::env::var("E2E_ROOT").unwrap_or_else(|_| format!("{}/work/leleka-e2e", std::env::var("HOME").unwrap_or_default()))).join("build/kernel-ab/kab") + }); + if !kab.is_file() { + return Err(format!("the C++ driver {} does not exist (build tools/kernel-ab/cpp, or pass --kab / set KAB)", kab.display())); + } + // a host without AVX-512 has no avx512 cells (the C++ reference trees are identical by construction there) + let trees: Vec<&'static str> = TREES.iter().copied().filter(|t| *t != "avx512" || verified.provenance.avx512_ok != Some(false)).collect(); + let procs = procs_for(&trees); + + // the schedule, written BEFORE the first run and read back: the file, not the generator, drives the batch + let first_round = (a.batch - 1) * a.rounds + 1; + let planned = make_schedule(a.seed, a.batch, a.rounds, &procs); + let text = schedule_text(a.seed, a.batch, a.rounds, &a.case, a.pin, first_round, &planned); + fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?; + if let Some(parent) = a.schedule.parent().filter(|p| !p.as_os_str().is_empty()) { + fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?; + } + create_new_file(&a.schedule, text.as_bytes())?; + let schedule = parse_schedule(&fs::read_to_string(&a.schedule).map_err(|e| format!("{}: {e}", a.schedule.display()))?)?; + println!("schedule written to {} (sha256 {}) before the first run: {} rounds x {} processes", a.schedule.display(), sha_hex(text.as_bytes()), schedule.len(), procs.len()); + let (records_dir, proc_dir) = (out.join("records"), out.join("processes")); + for d in [&records_dir, &proc_dir] { + fs::create_dir_all(d).map_err(|e| format!("{}: {e}", d.display()))?; + } + let parent_env: Vec<(OsString, OsString)> = std::env::vars_os().collect(); + let sibling_at_start = sibling_idle(a.pin); + let machine_role = a.machine_role.clone().or_else(|| std::env::var("HOSTNAME").ok()).or_else(|| std::env::var("COMPUTERNAME").ok()).unwrap_or_else(|| "unknown".to_owned()); + let (rustc_version, triple) = rustc_info(); + + // equality phase: our tree against the C++ reference .out file, per tree, in fresh processes (the kernels are not touched by timing) + let eq_dir = out.join(format!("equality-b{:04}", a.batch)); + let mut equality: BTreeMap<&'static str, Outcome> = BTreeMap::new(); + for tree in &trees { + let p = Proc { imp: Impl::Rust, tree, rep: 'a' }; + let mut cmd = scrubbed_command(&own_exe, &parent_env, &cell_env(&p)); + cmd.arg("run-tree").arg(&a.dir).args(["--tree", tree, "--case", &a.case, "--out"]).arg(&eq_dir).args(["--pin", &a.pin.to_string()]); + run_cell(&mut cmd, &format!("{}/equality", p.name()))?; + let ours_name = format!("case-{}.rust-{tree}.out", a.case); + let ours = read_out(&eq_dir.join(&ours_name), &ours_name, case.rows, tree, None).map_err(|e| e.to_string())?; + let o = case.outs.iter().find(|o| o.tree == *tree).ok_or("missing reference out")?; + let reference = read_out(&a.dir.join(&o.name), &o.name, case.rows, tree, Some((&o.sha256, o.bytes))).map_err(|e| e.to_string())?; + let outcome = compare_bits(&ours, &reference, case.tolerance.as_ref()); + println!( + "EQUALITY {} [{tree}] {}{}", + a.case, + if outcome.equal() { "EQUAL" } else { "NOT_EQUAL" }, + outcome.first_mismatch.map_or(format!("; {} values", outcome.compared), |(i, x, y)| format!("; {} of {} values differ, first at {i}: ours {x:#010x} reference {y:#010x}, max abs error {:e}", outcome.mismatches, outcome.compared, outcome.max_abs_error)) + ); + equality.insert(tree, outcome); + } + + let mut cpu_model = String::new(); + let batch_json = |cpu_model: String, equality: &BTreeMap<&'static str, Outcome>| -> Result { + let eq = equality + .iter() + .map(|(t, o)| { + format!( + "{{\"tree\": {}, \"verdict\": \"{}\", \"mode\": \"{}\", \"compared_values\": {}, \"mismatches\": {}}}", + jstr(t), + if o.equal() { "EQUAL" } else { "NOT_EQUAL" }, + if case.tolerance.is_some() { "tolerance" } else { "bitwise" }, + o.compared, + o.mismatches + ) + }) + .collect::>() + .join(", "); + let cells = procs + .iter() + .map(|p| format!("{{\"process\": {}, \"impl\": {}, \"tree\": {}, \"env_set\": {}, \"env_scrubbed\": \"every STRATA_* and LELEKA_* variable of the parent\"}}", jstr(&p.name()), jstr(p.imp.name()), jstr(p.tree), json_env(&cell_env(p).into_iter().collect()))) + .collect::>() + .join(", "); + Ok(format!( + "{{\n \"format\": \"KAB1-alt\",\n \"version\": 1,\n \"batch\": {},\n \"rounds\": {},\n \"first_round\": {first_round},\n \"run_started_utc\": {},\n \"case\": {},\n \"run_dir\": {},\n \"manifest_sha256\": {},\n \"input_sha256\": {},\n \"pin\": {{\"logical_cpu\": {}, \"sibling_idle_at_start\": {sibling_at_start}}},\n \"pool\": {{\"workers\": 1}},\n \"machine\": {{\"machine_role\": {}, \"cpu_model\": {}, \"os\": {}}},\n \"seed\": {},\n \"schedule\": {{\"file\": {}, \"sha256\": {}}},\n \"kab\": {{\"path\": {}, \"sha256\": {}}},\n \"rust_example\": {{\"path\": {}, \"sha256\": {}}},\n \"slices_per_regime\": {},\n \"slice_ms\": {},\n \"equality\": [{eq}],\n \"cells\": [{cells}],\n \"no_statistics\": \"this file computes no class, no interval and no A/A verdict (S0.10b, STRA-313)\"\n}}\n", + a.batch, + a.rounds, + jstr(&started), + jstr(&a.case), + jstr(&a.dir.display().to_string()), + jstr(&verified.manifest_sha256), + jstr(&case.in_sha256), + a.pin, + jstr(&machine_role), + jstr(&cpu_model), + jstr(&host_os()), + a.seed, + jstr(&a.schedule.display().to_string()), + jstr(&sha_hex(text.as_bytes())), + jstr(&kab.display().to_string()), + jstr(&file_sha(&kab)?), + jstr(&own_exe.display().to_string()), + jstr(&file_sha(&own_exe)?), + a.slices, + a.slice_ms.map_or("null".to_owned(), |m| jnum(m, 1)) + )) + }; + + let expect = Expect { manifest_sha: &verified.manifest_sha256, input_sha: &case.in_sha256, case: &a.case, pin: a.pin }; + let mut ctx = BatchCtx { + verified: &verified, + case: &case, + pin: a.pin, + machine_role: machine_role.clone(), + os: host_os(), + cpu_model: String::new(), + started_utc: started.clone(), + rust_tool: Tool { compiler: "rustc".to_owned(), version: rustc_version, triple, flags: ours_flags() }, + batch: a.batch, + equality: &equality, + }; + let mut written = Vec::new(); + for (round_no, order) in &schedule { + let mut done: Vec = Vec::new(); + for p in order { + let name = p.name(); + let file = proc_dir.join(format!("r{round_no:05}-{name}.json")); + let mut cmd = scrubbed_command(if p.imp == Impl::Cpp { &kab } else { &own_exe }, &parent_env, &cell_env(p)); + cmd.arg("time").args(["--run-dir"]).arg(&a.dir).args(["--case", &a.case, "--slices", &a.slices.to_string(), "--pin", &a.pin.to_string(), "--out"]).arg(&file); + if let Some(ms) = a.slice_ms { + cmd.args(["--slice-ms", &ms.to_string()]); + } + if let Some(b) = a.llc_bytes { + cmd.args(["--llc-bytes", &b.to_string()]); + } + let res = run_cell(&mut cmd, &name)?; + fs::write(file.with_extension("log"), [&res.stdout[..], &res.stderr[..]].concat()).map_err(|e| format!("{}: {e}", file.display()))?; + let bytes = fs::read(&file).map_err(|e| format!("cell {name}: its output {} was not written: {e}", file.display()))?; + done.push(parse_proc_json(p, &bytes, &expect)?); + } + if cpu_model.is_empty() { + cpu_model = done.iter().find_map(|d| d.cpu_model.clone()).unwrap_or_else(|| "unknown model".to_owned()); + ctx.cpu_model = cpu_model.clone(); + create_new_file(&out.join(format!("batch-{:04}.json", a.batch)), batch_json(cpu_model.clone(), &equality)?.as_bytes())?; + } + for (name, json) in round_records(&ctx, *round_no, &done)? { + create_new_file(&records_dir.join(&name), json.as_bytes())?; + written.push(name); + } + println!("round {round_no} done: {}", order.iter().map(Proc::name).collect::>().join(" ")); + } + println!("ALTERNATE OK batch={} rounds={} records={} dir={}", a.batch, a.rounds, written.len(), records_dir.display()); + for (t, o) in &equality { + println!("EQUALITY-SUMMARY {} {t} {}", a.case, if o.equal() { "EQUAL" } else { "NOT_EQUAL" }); + } + Ok(ExitCode::SUCCESS) +} + // ------------------------------------------------------------------------------------------------ main fn usage() -> ExitCode { - eprintln!("usage: kernel_ab verify D | compare D [--out R] [--pin CPU] [--machine-role NAME] [--trees avx512,avx2] | run-tree D --tree T --out R [--pin CPU]"); + eprintln!("usage: kernel_ab verify D | compare D [--out R] [--pin CPU] [--machine-role NAME] [--trees avx512,avx2] | run-tree D --tree T --out R [--pin CPU] [--case ID]"); + eprintln!(" kernel_ab time --run-dir D --case ID --slices N --pin CPU --out F.json [--slice-ms 60] [--regime both|resident|streamed] [--llc-bytes B]"); + eprintln!(" kernel_ab alternate --run-dir D --case ID --rounds N --batch K --pin CPU --schedule FILE [--seed S] [--out R] [--slices N] [--slice-ms MS] [--llc-bytes B] [--machine-role NAME] [--kab PATH]"); ExitCode::from(64) } fn main() -> ExitCode { let args: Vec = std::env::args().skip(1).collect(); + // `time` and `alternate` take flags only (the command line of `kab time`); the older commands take the directory first + if let Some(cmd @ ("time" | "alternate")) = args.first().map(String::as_str) { + let result = if cmd == "time" { cmd_time(&args[1..]) } else { cmd_alternate(&args[1..]) }; + return result.unwrap_or_else(|e| { + eprintln!("kernel_ab {cmd}: {e}"); + ExitCode::from(1) + }); + } let (Some(cmd), Some(dir)) = (args.first(), args.get(1)) else { return usage() }; let dir = Path::new(dir); let opts = match parse_options(&args[2..]) { @@ -1162,7 +2598,7 @@ fn main() -> ExitCode { }, "compare" => cmd_compare(dir, &opts), "run-tree" => match (&opts.tree, &opts.out) { - (Some(t), Some(o)) => cmd_run_tree(dir, t, o, opts.pin), + (Some(t), Some(o)) => cmd_run_tree(dir, t, o, opts.pin, opts.case.as_deref()), _ => return usage(), }, _ => return usage(), @@ -1526,6 +2962,358 @@ mod tests { assert_eq!(rec.str("kab1_manifest_sha256").unwrap(), v.manifest_sha256); } + // ---------------------------------------------------------------------------------------------------- alternation (STRA-318) + + #[test] + fn the_schedule_is_reproducible_from_the_seed() { + let procs = procs_for(&TREES); + let a = make_schedule(7, 1, 30, &procs); + assert_eq!(a, make_schedule(7, 1, 30, &procs)); + assert_ne!(a, make_schedule(8, 1, 30, &procs), "another seed gives another schedule"); + assert_ne!(a, make_schedule(7, 2, 30, &procs), "another batch gives another schedule"); + assert_eq!(a.len(), 30); + // the text round-trips through the file format and names the seed + let text = schedule_text(7, 1, 30, "18-20-r1", 9, 1, &a); + assert!(text.contains("seed=7 batch=1 rounds=30 case=18-20-r1 pin=9")); + let back = parse_schedule(&text).unwrap(); + assert_eq!(back.iter().map(|r| r.1.clone()).collect::>(), a); + assert_eq!(back[0].0, 1); + assert_eq!(back[29].0, 30); + } + + #[test] + fn the_rotation_gives_every_process_every_position_within_a_block() { + let procs = procs_for(&TREES); + assert_eq!(procs.len(), 8); + let s = make_schedule(3, 1, 16, &procs); + for block in s.chunks(8) { + for round in block { + let mut names: Vec<_> = round.iter().map(Proc::name).collect(); + names.sort(); + assert_eq!(names.len(), 8); + names.dedup(); + assert_eq!(names.len(), 8, "every process exactly once per round"); + } + for pos in 0..8 { + let at: BTreeSet<_> = block.iter().map(|r| r[pos]).collect(); + assert_eq!(at.len(), 8, "position {pos} is taken by every process once per block of 8 rounds"); + } + } + // a host without AVX-512 has only the avx2 cells + assert_eq!(procs_for(&["avx2"]).len(), 4); + } + + #[test] + fn a_schedule_file_is_written_once_and_a_bad_one_is_refused() { + let t = TempDir::new(); + let f = t.0.join("schedule.tsv"); + create_new_file(&f, b"x").unwrap(); + assert!(create_new_file(&f, b"y").unwrap_err().contains("nothing is overwritten")); + assert_eq!(fs::read(&f).unwrap(), b"x"); + let procs = procs_for(&TREES); + let good = schedule_text(1, 1, 3, "c", 0, 1, &make_schedule(1, 1, 3, &procs)); + assert!(parse_schedule(&good).is_ok()); + assert!(parse_schedule("nope").is_err()); + assert!(parse_schedule(&good.replace("cpp-avx2-a", "cpp-avx2-z")).unwrap_err().contains("unknown process")); + assert!(parse_schedule(&good.replacen("\n2\t", "\n5\t", 1)).unwrap_err().contains("does not follow")); + // a round that names one process twice (and so lacks another) is refused + let dup = good.lines().map(|l| if l.starts_with("2\t") { l.replacen("rust-avx2-b", "rust-avx2-a", 1).replacen("rust-avx2-b", "rust-avx2-a", 1) } else { l.to_owned() }).collect::>().join("\n"); + assert!(parse_schedule(&dup).is_err()); + } + + /// The child side of the environment test: prints the managed variables it sees. Does nothing in a normal run. + #[test] + fn env_probe_child() { + if std::env::var_os("KAB_TEST_CHILD").as_deref() != Some(std::ffi::OsStr::new("probe")) { + return; + } + for (k, v) in std::env::vars() { + if is_managed_name(&k) { + println!("PROBE {k}={v}"); + } + } + } + + /// The child side of the failure test. + #[test] + fn failing_child() { + if std::env::var_os("KAB_TEST_CHILD").as_deref() == Some(std::ffi::OsStr::new("fail")) { + eprintln!("simulated kernel failure"); + std::process::exit(3); + } + } + + fn child(test: &str, mode: &str, planted: &[(&str, &str)], cell: &[(String, String)]) -> Command { + let mut parent: Vec<(OsString, OsString)> = std::env::vars_os().filter(|(k, _)| !is_managed_name(&k.to_string_lossy())).collect(); + parent.push(("KAB_TEST_CHILD".into(), mode.into())); + parent.extend(planted.iter().map(|(k, v)| ((*k).into(), (*v).into()))); + let mut c = scrubbed_command(&std::env::current_exe().unwrap(), &parent, cell); + c.args(["--exact", test, "--nocapture", "--test-threads=1"]); + c + } + + #[test] + fn environment_scrubbing_removes_a_planted_strata_variable_and_keeps_only_the_cell() { + let cell = cell_env(&Proc { imp: Impl::Rust, tree: "avx2", rep: 'a' }); + assert_eq!(cell, vec![("LELEKA_CPU_POOL_PIN_HOST".to_owned(), "off".to_owned()), ("STRATA_FORCE_AVX2".to_owned(), "1".to_owned())]); + assert!(cell_env(&Proc { imp: Impl::Cpp, tree: "avx512", rep: 'b' }).is_empty()); + let out = run_cell(&mut child("tests::env_probe_child", "probe", &[("STRATA_X", "planted"), ("LELEKA_Y", "planted"), ("strata_lower", "planted")], &cell), "rust-avx2-a").unwrap(); + let text = String::from_utf8_lossy(&out.stdout); + // libtest prints "test ... " before the child's own output on the same line + let mut probes: Vec<&str> = text.lines().flat_map(|l| l.split("PROBE ").skip(1)).collect(); + probes.sort_unstable(); + assert_eq!(probes, vec!["LELEKA_CPU_POOL_PIN_HOST=off", "STRATA_FORCE_AVX2=1"], "only the cell's variables survive:\n{text}"); + // the cpp avx512 cell sets nothing at all + let out = run_cell(&mut child("tests::env_probe_child", "probe", &[("STRATA_X", "planted")], &[]), "cpp-avx512-a").unwrap(); + assert!(!String::from_utf8_lossy(&out.stdout).contains("PROBE ")); + } + + #[test] + fn a_child_failure_is_reported_with_the_cell_named() { + let e = run_cell(&mut child("tests::failing_child", "fail", &[], &[]), "cpp-avx2-b").unwrap_err(); + assert!(e.starts_with("cell cpp-avx2-b failed (exit 3)"), "{e}"); + assert!(e.contains("simulated kernel failure"), "{e}"); + let e = run_cell(&mut Command::new("kab-does-not-exist-318"), "rust-avx512-a").unwrap_err(); + assert!(e.starts_with("cell rust-avx512-a: cannot start"), "{e}"); + } + + #[test] + fn the_time_command_line_is_the_one_of_kab_time() { + let v = |a: &[&str]| a.iter().map(|s| (*s).to_owned()).collect::>(); + let t = parse_time_args(&v(&["--run-dir", "D", "--case", "18-20-r1", "--slices", "50", "--pin", "9", "--out", "t.json"])).unwrap(); + assert_eq!((t.slices, t.pin, t.slice_ms, t.regime, t.llc_bytes), (50, 9, 60.0, RegimeSel::Both, None)); + let t = parse_time_args(&v(&["--run-dir", "D", "--case", "c", "--slices", "2", "--pin", "0", "--out", "o", "--slice-ms", "5", "--regime", "streamed", "--llc-bytes", "1000"])).unwrap(); + assert_eq!((t.slice_ms, t.regime, t.llc_bytes), (5.0, RegimeSel::Streamed, Some(1000))); + for bad in [ + v(&["--run-dir", "D", "--case", "c", "--slices", "0", "--pin", "0", "--out", "o"]), + v(&["--run-dir", "D", "--case", "c", "--slices", "1", "--out", "o"]), + v(&["--run-dir", "D", "--case", "c", "--slices", "1", "--pin", "0", "--out", "o", "--regime", "both2"]), + v(&["--run-dir", "D", "--case", "../c", "--slices", "1", "--pin", "0", "--out", "o"]), + v(&["--run-dir", "D", "--case", "c", "--slices", "1", "--pin", "0", "--out", "o", "--bogus", "1"]), + v(&["--run-dir", "D", "--run-dir", "E", "--case", "c", "--slices", "1", "--pin", "0", "--out", "o"]), + ] { + assert!(parse_time_args(&bad).is_err(), "{bad:?}"); + } + let a = parse_alt_args(&v(&["--run-dir", "D", "--case", "c", "--rounds", "30", "--batch", "1", "--pin", "9", "--schedule", "s.tsv"])).unwrap(); + assert_eq!((a.rounds, a.batch, a.seed, a.slices), (30, 1, 1, 20)); + assert!(parse_alt_args(&v(&["--run-dir", "D", "--case", "c", "--rounds", "30", "--batch", "0", "--pin", "9", "--schedule", "s"])).is_err()); + } + + #[test] + fn medians_percentiles_and_parsers_agree_with_the_reference_rules() { + assert_eq!(median_of(&[3.0, 1.0, 2.0, 10.0]), 3.0, "sorted, element size/2 as the C++ reference"); + assert_eq!(median_of(&[]), 0.0); + let v: Vec = (1..=21).map(f64::from).collect(); + assert_eq!((percentile_of(&v, 0.05), percentile_of(&v, 0.95)), (2.0, 20.0)); + assert_eq!(parse_cpu_list("2,18"), vec![2, 18]); + assert_eq!(parse_cpu_list("0-3,8"), vec![0, 1, 2, 3, 8]); + assert_eq!((parse_size("32768K"), parse_size("32M"), parse_size("512")), (32 << 20, 32 << 20, 512)); + assert_eq!(busy_fraction(Some((10, 100)), Some((30, 200))), Some(0.2)); + assert_eq!(busy_fraction(None, Some((1, 1))), None); + assert!(core_ghz() > 0.0); + } + + #[test] + fn an_output_inside_a_git_checkout_is_detected() { + let t = TempDir::new(); + let inner = t.0.join("a/b"); + fs::create_dir_all(&inner).unwrap(); + assert!(!inside_git_checkout(&inner)); + fs::create_dir_all(t.0.join(".git")).unwrap(); + assert!(inside_git_checkout(&inner)); + assert!(inside_git_checkout(&t.0.join("not/yet/created/schedule.tsv"))); + } + + fn json_regime(label: &str, k: usize, self_key: &str) -> String { + let slice = |g1: f64| format!("{{\"i\": 0, \"calls\": 10, \"wall_ns\": 100, \"ns_per_call\": 10.0, \"ghz_before\": 5.0, \"ghz_after\": {g1}, \"cycles_per_call\": 50.0}}"); + format!( + "{{\"regime\": \"{label}\", \"copies_k\": {k}, \"expert_bytes\": 1000, \"llc_bytes\": 500, \"slices_requested\": 3, \"slices_kept\": 2, \"dropped_count\": 1, \"{self_key}\": true, \"median_ns_per_call\": 10.0, \"median_cycles_per_call\": 50.0, \"slices\": [{}, {}], \"dropped\": [{}]}}", + slice(5.0), + slice(5.1), + slice(4.0) + ) + } + + /// A process JSON as the C++ writer (`imp` cpp) or this example (rust) writes it, with `env` as its effective environment. + fn proc_fixture(p: &Proc, env: &str) -> String { + let (self_key, detail) = if p.imp == Impl::Cpp { + ("selfcheck_bitwise_equal_compose_expert", "{\"tree\": \"avx512\", \"avx2_ok\": true, \"avx512_ok\": true, \"iq512_gather_on\": false, \"iq256_gather_setting\": -1, \"strata_env\": {}}".to_owned()) + } else { + ("selfcheck_bitwise_equal_first_call", format!("{{\"tree\": \"{}\", \"cpu_report\": [\"cpu: logical 16 (8 physical): Test CPU; x\", \"cpu: process kernel family AVX-512 (test)\"], \"strata_env\": {{}}}}", p.tree)) + }; + format!( + "{{\"format\": \"KAB1-time\", \"version\": 1, \"writer\": \"{}\", \"manifest_sha256\": \"m\", \"case\": {{\"id\": \"c\", \"input_sha256\": \"i\"}}, \"tree\": \"{}\", \"tree_detail\": {detail}, \"effective_env\": {env}, \"pin\": {{\"cpu\": 9, \"sibling_cpu\": 25, \"sibling_busy_fraction_during_run\": 0.01}}, \"clock_calibration\": {{\"ghz_at_start\": 5.0, \"ghz_at_end\": 5.1}}, \"final_output_unchanged\": true, \"output_sha256\": \"{}\", \"regimes\": [{}, {}]}}", + p.imp.name(), + p.tree, + "cd".repeat(32), + json_regime("RESIDENT", 1, self_key), + json_regime("STREAMED", 3, self_key) + ) + } + + #[test] + fn a_process_json_is_checked_against_the_cell_that_was_started() { + let expect = Expect { manifest_sha: "m", input_sha: "i", case: "c", pin: 9 }; + for p in [Proc { imp: Impl::Cpp, tree: "avx2", rep: 'a' }, Proc { imp: Impl::Rust, tree: "avx512", rep: 'b' }] { + let env = json_env(&cell_env(&p).into_iter().collect()); + let ok = parse_proc_json(&p, proc_fixture(&p, &env).as_bytes(), &expect).unwrap(); + assert_eq!(ok.regimes.len(), 2); + let r = &ok.regimes["STREAMED"]; + assert_eq!((r.copies_k, r.ns.len(), r.dropped, r.requested), (3, 2, 1, 3)); + assert!((r.max_drift - 0.2).abs() < 1e-9, "the dropped slice's 20 percent drift is the maximum: {}", r.max_drift); + assert_eq!(ok.sibling_idle, Some(true)); + // the environment the process saw must be exactly the cell's + let planted = json_env(&BTreeMap::from([("STRATA_X".to_owned(), "1".to_owned())])); + let e = parse_proc_json(&p, proc_fixture(&p, &planted).as_bytes(), &expect).unwrap_err(); + assert!(e.starts_with(&format!("cell {}: effective environment", p.name())), "{e}"); + // wrong pin, wrong manifest, wrong input, wrong writer: each names the cell + for (bad_expect, what) in [ + (Expect { manifest_sha: "m", input_sha: "i", case: "c", pin: 8 }, "pinned to CPU"), + (Expect { manifest_sha: "other", input_sha: "i", case: "c", pin: 9 }, "manifest_sha256"), + (Expect { manifest_sha: "m", input_sha: "x", case: "c", pin: 9 }, "input hash"), + ] { + let e = parse_proc_json(&p, proc_fixture(&p, &env).as_bytes(), &bad_expect).unwrap_err(); + assert!(e.starts_with(&format!("cell {}:", p.name())) && e.contains(what), "{e}"); + } + let other = Proc { imp: if p.imp == Impl::Cpp { Impl::Rust } else { Impl::Cpp }, ..p }; + assert!(parse_proc_json(&other, proc_fixture(&p, &env).as_bytes(), &expect).unwrap_err().contains("writer")); + } + } + + fn fake_proc(p: Proc, base: f64) -> ProcOut { + let regime = |k: usize| RegimeStat { + copies_k: k, + expert_bytes: 1_000_000, + llc_bytes: 1_000, + requested: 10, + dropped: 1, + median_ns: base, + median_cycles: base * 5.0, + ns: vec![base * 0.9, base, base * 1.1], + cycles: vec![base * 4.5, base * 5.0, base * 5.5], + max_drift: 0.01, + selfcheck: true, + }; + ProcOut { + proc: p, + regimes: BTreeMap::from([("RESIDENT".to_owned(), regime(1)), ("STREAMED".to_owned(), regime(3))]), + ghz_start: 5.0, + ghz_end: 5.1, + sibling_idle: Some(true), + final_unchanged: true, + output_sha: Some("ab".repeat(32)), + tree_text: format!("tree text of {}", p.name()), + cpu_model: Some("Test CPU".to_owned()), + } + } + + #[test] + fn round_records_have_the_schema_shape_and_keep_not_equal() { + let t = TempDir::new(); + build(&t.0, &one_case(), |_| {}); + let v = verify_dir(&t.0).unwrap(); + let outcome = |bad: usize| Outcome { compared: H, mismatches: bad, differing_bits: bad, max_abs_error: 0.0, first_mismatch: None }; + let equality = BTreeMap::from([("avx512", outcome(0)), ("avx2", outcome(1835))]); + let ctx = BatchCtx { + verified: &v, + case: &v.cases[0], + pin: 9, + machine_role: "m".into(), + os: "os".into(), + cpu_model: "cpu".into(), + started_utc: "2026-10-28T20:00:00Z".into(), + rust_tool: Tool { compiler: "rustc".into(), version: "rustc 1.99.0".into(), triple: "x86_64-unknown-linux-gnu".into(), flags: "f".into() }, + batch: 2, + equality: &equality, + }; + let mut done: Vec = procs_for(&TREES).into_iter().enumerate().map(|(i, p)| fake_proc(p, 100.0 + i as f64)).collect(); + done.reverse(); // the order of execution does not matter to the records + let files = round_records(&ctx, 31, &done).unwrap(); + assert_eq!(files.len(), 12, "2 trees x 2 regimes x (A/B + A/A cpp + A/A rust)"); + let names: BTreeSet<_> = files.iter().map(|f| f.0.as_str()).collect(); + assert_eq!(names.len(), 12); + assert!(names.contains("r00031.ab.avx2.streamed.json") && names.contains("r00031.aa-cpp.avx512.resident.json") && names.contains("r00031.aa-rust.avx2.resident.json")); + for (name, json) in &files { + let rec = parse_json(json.as_bytes()).unwrap_or_else(|e| panic!("{name}: {e}")); + for key in ["schema_version", "level", "record_id", "created_utc", "run_started_utc", "machine", "kernel", "toolchain", "case_id", "input_sha256", "kab1_manifest_sha256", "tree", "regime", "pin", "strata_upstream_commit", "clock_calibration", "rows", "aa_noise_floor", "equality"] { + assert!(rec.get(key).is_some(), "{name}: {key}"); + } + assert_eq!(rec.str("level").unwrap(), "COMPONENT_KERNEL"); + assert_eq!(rec.str("kab1_manifest_sha256").unwrap(), v.manifest_sha256); + assert_eq!(rec.str("input_sha256").unwrap(), v.cases[0].in_sha256); + let Some(Json::Arr(rows)) = rec.get("rows") else { panic!("rows") }; + let units: Vec<_> = rows.iter().map(|r| r.str("unit").unwrap().to_owned()).collect(); + assert_eq!(units, ["ns", "cycles"]); + assert_ne!(rows[0].str("row_type").unwrap(), rows[1].str("row_type").unwrap(), "no repeated row type"); + let regime = rec.str("regime").unwrap(); + assert_eq!(rec.get("streamed").is_some(), regime == "streamed", "{name}"); + assert!(rec.str("kernel").unwrap().contains("PLACEHOLDER")); + let eq = rec.req("equality").unwrap(); + let tree = rec.req("tree").unwrap().str("ours").unwrap(); + let want = if name.contains(".ab.") && tree == "avx2" { "NOT_EQUAL" } else { "EQUAL" }; + assert_eq!(eq.str("verdict").unwrap(), want, "{name}"); + if want == "NOT_EQUAL" { + assert_eq!(eq.uint("mismatches").unwrap(), 1835, "the A/B mismatch count is carried, not hidden"); + } + } + // the A/B record puts Rust in the ours slot and C++ in the reference slot; the A/A records use one implementation on both + let ab = parse_json(files.iter().find(|f| f.0 == "r00031.ab.avx512.resident.json").unwrap().1.as_bytes()).unwrap(); + assert!(ab.str("kernel").unwrap().contains("ours-slot process rust-avx512-a, reference-slot process cpp-avx512-a")); + assert_eq!(ab.req("toolchain").unwrap().req("ours").unwrap().str("compiler").unwrap(), "rustc"); + let aa = parse_json(files.iter().find(|f| f.0 == "r00031.aa-cpp.avx512.resident.json").unwrap().1.as_bytes()).unwrap(); + assert!(aa.str("kernel").unwrap().contains("ours-slot process cpp-avx512-a, reference-slot process cpp-avx512-b")); + assert_eq!(aa.req("equality").unwrap().str("mode").unwrap(), "bitwise"); + // a streamed set that differs between the two sides of a record is refused + let mut skewed = done.clone(); + skewed.iter_mut().find(|p| p.proc == Proc { imp: Impl::Cpp, tree: "avx2", rep: 'a' }).unwrap().regimes.get_mut("STREAMED").unwrap().copies_k = 4; + assert!(round_records(&ctx, 31, &skewed).unwrap_err().contains("streamed set differs")); + // a missing process is named + assert!(round_records(&ctx, 31, &done[1..]).unwrap_err().contains("did not run")); + } + + #[test] + fn the_rust_time_mode_writes_a_process_json_the_runner_accepts() { + let t = TempDir::new(); + build(&t.0, &one_case(), |_| {}); + let out = TempDir::new(); + let file = out.0.join("t.json"); + let args: Vec = ["--run-dir", t.0.to_str().unwrap(), "--case", "42-42-r1", "--slices", "40", "--pin", "0", "--out", file.to_str().unwrap(), "--slice-ms", "1", "--llc-bytes", "8000000"].iter().map(|s| (*s).to_owned()).collect(); + // exit 0, or 3 when a 1 ms slice of a ramping clock was dropped in every slice of a regime (kept slices are the loaded host's call) + let code = format!("{:?}", cmd_time(&args).unwrap()); + assert!(code == format!("{:?}", ExitCode::SUCCESS) || code == format!("{:?}", ExitCode::from(3)), "{code}"); + let text = fs::read_to_string(&file).unwrap(); + let j = parse_json(text.as_bytes()).unwrap(); + assert_eq!(j.str("writer").unwrap(), "rust"); + assert_eq!(j.str("format").unwrap(), "KAB1-time"); + assert!(j.flag("selfcheck_bitwise_equal_first_call").unwrap()); + assert_eq!(j.str("output_sha256").unwrap().len(), 64); + let tree = j.str("tree").unwrap().to_owned(); + let p = Proc { imp: Impl::Rust, tree: TREES.iter().find(|t| **t == tree).copied().unwrap(), rep: 'a' }; + if !code.contains("(0)") { + return; + } + let manifest = fs::read(t.0.join("manifest.json")).unwrap(); + let (_, _, cases, _) = read_manifest(&t.0).unwrap(); + let sha = sha_hex(&manifest); + let expect = Expect { manifest_sha: &sha, input_sha: &cases[0].in_sha256, case: "42-42-r1", pin: 0 }; + // the test process runs unscrubbed (its effective environment is empty), so the runner's environment check refuses it ... + assert!(parse_proc_json(&p, text.as_bytes(), &expect).unwrap_err().contains("effective environment")); + // ... and accepts it once the recorded environment is the cell's + let want_env = json_env(&cell_env(&p).into_iter().collect()); + let as_cell = text.replacen("\"effective_env\": {}", &format!("\"effective_env\": {want_env}"), 1); + let ok = parse_proc_json(&p, as_cell.as_bytes(), &expect).unwrap(); + for r in ["RESIDENT", "STREAMED"] { + let s = &ok.regimes[r]; + assert!(s.median_ns > 0.0 && s.median_cycles > 0.0 && !s.ns.is_empty(), "{r}"); + assert_eq!(s.requested, 40); + } + assert_eq!(ok.regimes["RESIDENT"].copies_k, 1); + assert!(ok.regimes["STREAMED"].copies_k >= 2); + assert!(ok.tree_text.starts_with("leleka-serve cpu: process kernel family")); + // a lie about the pin is refused + assert!(parse_proc_json(&p, as_cell.as_bytes(), &Expect { pin: 3, ..expect }).unwrap_err().contains("pinned to CPU")); + } + #[test] fn utc_formatting_is_exact() { assert_eq!(utc_of(0), "1970-01-01T00:00:00Z"); From 6d1adfa78c79537694f4e908a8fb085bd2ca8ab0 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 28 Oct 2026 21:25:56 +0100 Subject: [PATCH 2/2] kernel_ab alternate: calibration chain that LLVM cannot fold, Rust cells without pool spin, per-record sibling_idle and clock bounds, rustc version fallback Co-Authored-By: Claude Sonnet 5.5 --- .../native-cpu-expert/examples/kernel_ab.rs | 76 ++++++++++++------- 1 file changed, 49 insertions(+), 27 deletions(-) diff --git a/crates/native-cpu-expert/examples/kernel_ab.rs b/crates/native-cpu-expert/examples/kernel_ab.rs index 5e2689a4..fa710b78 100644 --- a/crates/native-cpu-expert/examples/kernel_ab.rs +++ b/crates/native-cpu-expert/examples/kernel_ab.rs @@ -1024,14 +1024,14 @@ fn sibling_idle(cpu: usize) -> bool { } fn rustc_info() -> (String, String) { - let rustc = std::env::var("RUSTC").unwrap_or_else(|_| "rustc".to_owned()); + // $RUSTC, then `rustc` on the PATH, then the rustup shim of the user (a non-login shell has no cargo bin directory on its PATH) + let home = std::env::var("HOME").or_else(|_| std::env::var("USERPROFILE")).unwrap_or_default(); + let shim = format!("{home}/.cargo/bin/{}", if cfg!(windows) { "rustc.exe" } else { "rustc" }); + let candidates = [std::env::var("RUSTC").unwrap_or_else(|_| "rustc".to_owned()), "rustc".to_owned(), shim]; let triple = if cfg!(windows) { "x86_64-pc-windows-msvc" } else { "x86_64-unknown-linux-gnu" }; - let version = Command::new(rustc) - .arg("--version") - .output() - .ok() - .filter(|o| o.status.success()) - .and_then(|o| String::from_utf8(o.stdout).ok()) + let version = candidates + .iter() + .find_map(|rustc| Command::new(rustc).arg("--version").output().ok().filter(|o| o.status.success()).and_then(|o| String::from_utf8(o.stdout).ok())) .map_or_else(|| "unknown (rustc not runnable at record time)".to_owned(), |s| s.trim().to_owned()); (version, triple.to_owned()) } @@ -1221,31 +1221,33 @@ const CLOCK_MOVED_FRACTION: f64 = 0.05; /// An SMT sibling busier than this fraction is not idle (the 5 percent rule of `sibling_idle`). const SIBLING_BUSY_LIMIT: f64 = 0.05; const ALIGN: usize = 4096; -/// Latency of a dependent 64-bit multiply in cycles on every core the A/B runs on (Intel Skylake to Golden Cove, AMD Zen 1 to 5). -const MUL_LATENCY_CYCLES: f64 = 3.0; -const CLOCK_METHOD: &str = "chain of dependent 64-bit multiplies (latency 3 cycles), 1000000 iterations of 4, ghz = 3 * 4e6 / (elapsed ns); before and after every slice"; +/// Cycles of one step of the calibration chain `x = (x * k) ^ (x >> 17)`: a 64-bit multiply (3 cycles on Intel Skylake to Golden Cove +/// and AMD Zen 1 to 5) then an xor (1 cycle); the shift runs beside the multiply. +const CHAIN_STEP_CYCLES: f64 = 4.0; +const CLOCK_METHOD: &str = "chain of dependent steps x = (x * k) ^ (x >> 17), 4 cycles per step (3 multiply + 1 xor), 1000000 iterations of 4 steps, ghz = 4 * 4e6 / (elapsed ns); before and after every slice"; fn mono_ns() -> u64 { static ORIGIN: OnceLock = OnceLock::new(); ORIGIN.get_or_init(Instant::now).elapsed().as_nanos() as u64 } -/// The core clock in GHz from a chain of dependent multiplies (safe code: the C++ chain of dependent adds needs inline assembly). The -/// constant is opaque to the optimiser, so the four multiplies per iteration stay four dependent instructions. +/// The core clock in GHz from a chain of dependent steps (safe code: the C++ chain of dependent adds needs inline assembly). A plain +/// chain of multiplies by an opaque constant is folded by LLVM (measured: 175 GHz), so every step also xors in a shifted copy of the +/// running value, which no reassociation can remove. fn core_ghz() -> f64 { let k = std::hint::black_box(0x9E37_79B9_7F4A_7C15u64 | 1); let mut x = std::hint::black_box(1u64); let n = 1_000_000u64; let t0 = mono_ns(); for _ in 0..n { - x = x.wrapping_mul(k); - x = x.wrapping_mul(k); - x = x.wrapping_mul(k); - x = x.wrapping_mul(k); + x = x.wrapping_mul(k) ^ (x >> 17); + x = x.wrapping_mul(k) ^ (x >> 17); + x = x.wrapping_mul(k) ^ (x >> 17); + x = x.wrapping_mul(k) ^ (x >> 17); } let dt = mono_ns().saturating_sub(t0).max(1); std::hint::black_box(x); - MUL_LATENCY_CYCLES * 4.0 * n as f64 / dt as f64 + CHAIN_STEP_CYCLES * 4.0 * n as f64 / dt as f64 } fn median_of(v: &[f64]) -> f64 { @@ -1863,8 +1865,10 @@ fn procs_for(trees: &[&'static str]) -> Vec { v } -/// The environment a cell needs and nothing else: the Rust cells keep the pool from re-pinning its caller (the pin is the requested -/// one); the avx2 trees set `STRATA_FORCE_AVX2=1`, which both implementations honour. +/// 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). fn cell_env(p: &Proc) -> Vec<(String, String)> { let mut v = Vec::new(); if p.tree == "avx2" { @@ -1872,6 +1876,7 @@ fn cell_env(p: &Proc) -> Vec<(String, String)> { } 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 @@ -2236,8 +2241,10 @@ fn round_records(ctx: &BatchCtx, round_no: u32, done: &[ProcOut]) -> Result = TREES.iter().copied().filter(|t| done.iter().any(|d| d.proc.tree == *t)).collect(); for tree in trees { @@ -2275,6 +2282,9 @@ fn round_records(ctx: &BatchCtx, round_no: u32, done: &[ProcOut]) -> Result Result ... " before the child's own output on the same line let mut probes: Vec<&str> = text.lines().flat_map(|l| l.split("PROBE ").skip(1)).collect(); probes.sort_unstable(); - assert_eq!(probes, vec!["LELEKA_CPU_POOL_PIN_HOST=off", "STRATA_FORCE_AVX2=1"], "only the cell's variables survive:\n{text}"); + assert_eq!(probes, vec!["LELEKA_CPU_POOL_PIN_HOST=off", "STRATA_FORCE_AVX2=1", "STRATA_POOL_SPIN_US=0"], "only the cell's variables survive:\n{text}"); // the cpp avx512 cell sets nothing at all let out = run_cell(&mut child("tests::env_probe_child", "probe", &[("STRATA_X", "planted")], &[]), "cpp-avx512-a").unwrap(); assert!(!String::from_utf8_lossy(&out.stdout).contains("PROBE ")); @@ -3110,7 +3123,9 @@ mod tests { assert_eq!((parse_size("32768K"), parse_size("32M"), parse_size("512")), (32 << 20, 32 << 20, 512)); assert_eq!(busy_fraction(Some((10, 100)), Some((30, 200))), Some(0.2)); assert_eq!(busy_fraction(None, Some((1, 1))), None); - assert!(core_ghz() > 0.0); + // the calibrated clock of any x86-64 core is in this range (the chain must not be folded away: 175 GHz was the folded multiply chain) + let ghz = core_ghz(); + assert!((0.3..12.0).contains(&ghz), "{ghz}"); } #[test] @@ -3228,6 +3243,7 @@ mod tests { }; let mut done: Vec = procs_for(&TREES).into_iter().enumerate().map(|(i, p)| fake_proc(p, 100.0 + i as f64)).collect(); done.reverse(); // the order of execution does not matter to the records + done.iter_mut().find(|p| p.proc == Proc { imp: Impl::Cpp, tree: "avx2", rep: 'b' }).unwrap().sibling_idle = Some(false); let files = round_records(&ctx, 31, &done).unwrap(); assert_eq!(files.len(), 12, "2 trees x 2 regimes x (A/B + A/A cpp + A/A rust)"); let names: BTreeSet<_> = files.iter().map(|f| f.0.as_str()).collect(); @@ -3263,6 +3279,12 @@ mod tests { let aa = parse_json(files.iter().find(|f| f.0 == "r00031.aa-cpp.avx512.resident.json").unwrap().1.as_bytes()).unwrap(); assert!(aa.str("kernel").unwrap().contains("ours-slot process cpp-avx512-a, reference-slot process cpp-avx512-b")); assert_eq!(aa.req("equality").unwrap().str("mode").unwrap(), "bitwise"); + // sibling_idle belongs to the two processes of a record: only the A/A cpp avx2 records see the busy sibling of cpp-avx2-b + for (name, json) in &files { + let rec = parse_json(json.as_bytes()).unwrap(); + let busy = name.contains(".aa-cpp.avx2."); + assert_eq!(matches!(rec.req("pin").unwrap().get("sibling_idle"), Some(Json::Bool(false))), busy, "{name}"); + } // a streamed set that differs between the two sides of a record is refused let mut skewed = done.clone(); skewed.iter_mut().find(|p| p.proc == Proc { imp: Impl::Cpp, tree: "avx2", rep: 'a' }).unwrap().regimes.get_mut("STREAMED").unwrap().copies_k = 4;