From f9bbc09ab3adb65e07479e01a963aff0b3cedc58 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 6 Nov 2026 14:29:06 +0100 Subject: [PATCH] STRA-338 size: move the kernel_ab example tests into tests/{reader,alternation,timing} --- .../examples/kernel_ab/main.rs | 965 +----------------- .../examples/kernel_ab/tests.rs | 189 ++++ .../examples/kernel_ab/tests/alternation.rs | 149 +++ .../examples/kernel_ab/tests/reader.rs | 283 +++++ .../examples/kernel_ab/tests/timing.rs | 373 +++++++ 5 files changed, 995 insertions(+), 964 deletions(-) create mode 100644 crates/native-cpu-expert/examples/kernel_ab/tests.rs create mode 100644 crates/native-cpu-expert/examples/kernel_ab/tests/alternation.rs create mode 100644 crates/native-cpu-expert/examples/kernel_ab/tests/reader.rs create mode 100644 crates/native-cpu-expert/examples/kernel_ab/tests/timing.rs diff --git a/crates/native-cpu-expert/examples/kernel_ab/main.rs b/crates/native-cpu-expert/examples/kernel_ab/main.rs index 3fafb462..0242a9e3 100644 --- a/crates/native-cpu-expert/examples/kernel_ab/main.rs +++ b/crates/native-cpu-expert/examples/kernel_ab/main.rs @@ -97,970 +97,7 @@ fn main() -> ExitCode { // ------------------------------------------------------------------------------------------------ tests #[cfg(test)] -mod tests { - use super::*; - use std::sync::atomic::{AtomicUsize, Ordering}; - - static COUNTER: AtomicUsize = AtomicUsize::new(0); - - struct TempDir(PathBuf); - impl TempDir { - fn new() -> Self { - let p = std::env::temp_dir().join(format!( - "kab1-test-{}-{}", - std::process::id(), - COUNTER.fetch_add(1, Ordering::SeqCst) - )); - fs::create_dir_all(&p).unwrap(); - Self(p) - } - } - impl Drop for TempDir { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.0); - } - } - - fn block_filled(len: usize, block: usize, seed: u8) -> Vec { - let mut v: Vec = (0..len).map(|i| (i as u8).wrapping_mul(31).wrapping_add(seed)).collect(); - for at in (0..len).step_by(block) { - v[at] = 0x00; - v[at + 1] = 0x3c; // FP16 1.0 - } - v - } - - fn in_file(gu: i32, down: i32, rows: usize) -> Vec { - let (gq, gb) = (gate_up_row(gu).unwrap().2, gate_up_row(gu).unwrap().3); - let (dq, db) = (down_row(down).unwrap().2, down_row(down).unwrap().3); - let (gsize, dsize) = (H / gq * gb * FF, FF / dq * db * H); - let mut b = Vec::new(); - for w in [ - IN_MAGIC, - 1, - gu as u32, - down as u32, - rows as u32, - H as u32, - FF as u32, - gsize as u32, - gsize as u32, - dsize as u32, - ] { - b.extend_from_slice(&w.to_le_bytes()); - } - b.resize(IN_HEADER, 0); - b.extend(block_filled(gsize, gb, 1)); - b.extend(block_filled(gsize, gb, 2)); - b.extend(block_filled(dsize, db, 3)); - for i in 0..rows * H { - b.extend_from_slice(&(((i % 97) as f32 - 48.0) / 16.0).to_bits().to_le_bytes()); - } - b - } - - fn out_file(rows: usize, tree: u32) -> Vec { - let mut b = Vec::new(); - for w in [OUT_MAGIC, 1, rows as u32, H as u32, tree] { - b.extend_from_slice(&w.to_le_bytes()); - } - for i in 0..rows * H { - b.extend_from_slice(&((i as f32) * 0.25).to_bits().to_le_bytes()); - } - b - } - - struct Spec { - gu: i32, - down: i32, - rows: usize, - tolerance: Option<&'static str>, - } - - /// Builds a synthetic KAB1 directory; `mutate` edits the `.in` bytes before the manifest records their hash. - fn build(dir: &Path, specs: &[Spec], mutate: impl Fn(&mut Vec)) { - let mut cases = Vec::new(); - let mut files = Vec::new(); - for s in specs { - let id = format!("{}-{}-r{}", s.gu, s.down, s.rows); - let mut inb = in_file(s.gu, s.down, s.rows); - mutate(&mut inb); - fs::write(dir.join(format!("case-{id}.in")), &inb).unwrap(); - let mut entry = format!( - "{{\"id\": \"{id}\", \"gu_type\": {}, \"down_type\": {}, \"rows\": {}, \"seed\": 18446744073709551615, \"equality\": \"{}\", \"tolerance\": {}, \"in\": \"case-{id}.in\", \"in_sha256\": \"{}\", \"in_bytes\": {}", - s.gu, - s.down, - s.rows, - if s.tolerance.is_some() { "tolerance" } else { "bitwise" }, - s.tolerance.unwrap_or("null"), - sha_hex(&inb), - inb.len() - ); - files.push(format!("\"case-{id}.in\": {{\"sha256\": \"{}\", \"bytes\": {}}}", sha_hex(&inb), inb.len())); - for (k, tree) in TREES.iter().enumerate() { - let ob = out_file(s.rows, k as u32); - fs::write(dir.join(format!("case-{id}.cpp-{tree}.out")), &ob).unwrap(); - entry += &format!( - ", \"out_cpp_{tree}\": \"case-{id}.cpp-{tree}.out\", \"out_cpp_{tree}_sha256\": \"{}\", \"out_cpp_{tree}_bytes\": {}", - sha_hex(&ob), - ob.len() - ); - files.push(format!( - "\"case-{id}.cpp-{tree}.out\": {{\"sha256\": \"{}\", \"bytes\": {}}}", - sha_hex(&ob), - ob.len() - )); - } - cases.push(entry + "}"); - } - let manifest = format!( - "{{\"format\": \"KAB1\", \"version\": 1, \"run_id\": \"synthetic\", \"writer\": \"cpp\", \"provenance\": {{\"engine_strata_pin\": \"41cf05a06a25dd29103b7b27a2279a3f60c21876\", \"compiler_id\": \"GNU\", \"compiler_version\": \"15.2.0\", \"target_triple\": \"x86_64-linux-gnu\", \"built_at_utc\": \"2026-10-28T19:05:05Z\", \"avx512_ok\": true, \"flags\": {{\"strata_cxx_flags\": \"-O3 -DNDEBUG\", \"ggml_cpu_arch_flags\": \"-march=native\"}}}}, \"cases\": [{}], \"files\": {{{}}}}}", - cases.join(", "), - files.join(", ") - ); - fs::write(dir.join("manifest.json"), manifest).unwrap(); - } - - fn two_cases() -> Vec { - vec![Spec { gu: 42, down: 42, rows: 2, tolerance: None }, Spec { gu: 18, down: 20, rows: 1, tolerance: None }] - } - - fn one_case() -> Vec { - vec![Spec { gu: 42, down: 42, rows: 1, tolerance: None }] - } - - fn id(file: &str) -> String { - format!("case-42-42-r1.{file}") - } - - #[test] - fn a_good_directory_verifies() { - let t = TempDir::new(); - build(&t.0, &two_cases(), |_| {}); - let v = verify_dir(&t.0).unwrap(); - assert_eq!(v.cases.len(), 2); - assert_eq!(v.file_count, 2 * 3 + 1); - assert_eq!(v.manifest_sha256.len(), 64); - assert_eq!(v.cases[0].in_sha256, sha_hex(&fs::read(t.0.join("case-42-42-r2.in")).unwrap())); - } - - #[test] - fn a_flipped_byte_refuses_the_directory_and_names_the_file() { - let t = TempDir::new(); - build(&t.0, &one_case(), |_| {}); - let p = t.0.join(id("in")); - let mut b = fs::read(&p).unwrap(); - b[IN_HEADER + 7] ^= 0x40; - fs::write(&p, b).unwrap(); - let e = verify_dir(&t.0).unwrap_err(); - assert_eq!(e.file, "case-42-42-r1.in"); - assert!(e.reason.contains("sha256"), "{e}"); - } - - #[test] - fn a_truncated_file_refuses_the_directory_and_names_the_file() { - let t = TempDir::new(); - build(&t.0, &one_case(), |_| {}); - let p = t.0.join(id("cpp-avx2.out")); - let b = fs::read(&p).unwrap(); - fs::write(&p, &b[..b.len() - 4]).unwrap(); - let e = verify_dir(&t.0).unwrap_err(); - assert_eq!(e.file, "case-42-42-r1.cpp-avx2.out"); - assert!(e.reason.contains("length"), "{e}"); - } - - #[test] - fn a_wrong_magic_is_refused() { - let t = TempDir::new(); - build(&t.0, &one_case(), |b| b[0] ^= 0xff); - let e = verify_dir(&t.0).unwrap_err(); - assert_eq!(e.file, "case-42-42-r1.in"); - assert!(e.reason.contains("magic"), "{e}"); - } - - #[test] - fn a_wrong_version_is_refused() { - let t = TempDir::new(); - build(&t.0, &one_case(), |b| b[4] = 2); - let e = verify_dir(&t.0).unwrap_err(); - assert_eq!(e.file, "case-42-42-r1.in"); - assert!(e.reason.contains("version"), "{e}"); - } - - #[test] - fn a_byte_count_that_disagrees_with_the_format_is_refused() { - let t = TempDir::new(); - build(&t.0, &one_case(), |b| { - let wrong = (le32(b, 28) + 18).to_le_bytes(); - b[28..32].copy_from_slice(&wrong); - }); - let e = verify_dir(&t.0).unwrap_err(); - assert_eq!(e.file, "case-42-42-r1.in"); - assert!(e.reason.contains("format-derived"), "{e}"); - } - - #[test] - fn a_non_finite_fp16_header_is_refused() { - let t = TempDir::new(); - // the manifest records the hash of the mutated file, so only the FP16 rule can refuse it - build(&t.0, &one_case(), |b| { - let at = IN_HEADER + 18 * 3; - b[at] = 0x00; - b[at + 1] = 0x7c; // FP16 +inf - }); - let e = verify_dir(&t.0).unwrap_err(); - assert_eq!(e.file, "case-42-42-r1.in"); - assert!(e.reason.contains("non-finite FP16"), "{e}"); - } - - #[test] - fn a_non_finite_activation_is_refused() { - let t = TempDir::new(); - build(&t.0, &one_case(), |b| { - let at = b.len() - 4; - b[at..].copy_from_slice(&f32::NAN.to_bits().to_le_bytes()); - }); - let e = verify_dir(&t.0).unwrap_err(); - assert!(e.reason.contains("non-finite activation"), "{e}"); - } - - #[test] - fn a_missing_manifest_is_incomplete_and_named() { - let t = TempDir::new(); - build(&t.0, &one_case(), |_| {}); - fs::remove_file(t.0.join("manifest.json")).unwrap(); - let e = verify_dir(&t.0).unwrap_err(); - assert_eq!(e.file, "manifest.json"); - assert!(e.incomplete); - assert!(e.to_string().contains("manifest.json")); - } - - #[test] - fn an_extra_or_missing_file_refuses_the_directory() { - let t = TempDir::new(); - build(&t.0, &one_case(), |_| {}); - fs::write(t.0.join("stray.txt"), b"x").unwrap(); - assert_eq!(verify_dir(&t.0).unwrap_err().file, "stray.txt"); - fs::remove_file(t.0.join("stray.txt")).unwrap(); - fs::remove_file(t.0.join(id("cpp-avx512.out"))).unwrap(); - assert_eq!(verify_dir(&t.0).unwrap_err().file, "case-42-42-r1.cpp-avx512.out"); - } - - #[test] - fn an_absurd_length_is_refused_without_taking_a_buffer() { - // header says gate_bytes = 4 GiB - 16; the pure header check refuses it before any buffer exists - let mut h = [0u8; IN_HEADER]; - h.copy_from_slice(&in_file(42, 42, 1)[..IN_HEADER]); - h[28..32].copy_from_slice(&(u32::MAX - 15).to_le_bytes()); - BUFFERS.with(|c| c.set(0)); - assert!(validate_in_header(&h, 1 << 20).unwrap_err().contains("format-derived")); - assert_eq!(BUFFERS.with(Cell::get), 0); - // and through the file reader: manifest and file agree on a file whose header lies about its size - let t = TempDir::new(); - build(&t.0, &one_case(), |b| b[28..32].copy_from_slice(&(u32::MAX - 15).to_le_bytes())); - BUFFERS.with(|c| c.set(0)); - let (m, _) = (fs::read(t.0.join("manifest.json")).unwrap(), 0); - let (_, cases, _) = parse_manifest(&parse_json(&m).unwrap()).unwrap(); - let e = read_case_in(&t.0, &cases[0]).err().unwrap(); - assert!(e.reason.contains("format-derived"), "{e}"); - assert_eq!(BUFFERS.with(Cell::get), 0, "a buffer was taken before the header was validated"); - // a manifest that declares an absurd length for a file is refused before a buffer too - let mut lying = cases[0].clone(); - lying.in_bytes = u64::MAX; - assert!(read_case_in(&t.0, &lying).unwrap_err().reason.contains("differs from the manifest")); - assert_eq!(BUFFERS.with(Cell::get), 0); - // the good path takes exactly one buffer per file - let g = TempDir::new(); - build(&g.0, &one_case(), |_| {}); - BUFFERS.with(|c| c.set(0)); - let (_, cases, _) = - parse_manifest(&parse_json(&fs::read(g.0.join("manifest.json")).unwrap()).unwrap()).unwrap(); - read_case_in(&g.0, &cases[0]).unwrap(); - assert_eq!(BUFFERS.with(Cell::get), 1); - } - - #[test] - fn a_tolerance_needs_basis_metric_and_a_time_before_the_reference_run() { - let ok = "{\"value\": 0.003, \"metric\": \"max_abs_error_over_max_abs_reference\", \"basis\": \"order-only difference\", \"basis_written_utc\": \"2026-10-28T10:00:00Z\"}"; - let t = TempDir::new(); - build(&t.0, &[Spec { gu: 42, down: 42, rows: 1, tolerance: Some(ok) }], |_| {}); - let v = verify_dir(&t.0).unwrap(); - assert_eq!(v.cases[0].tolerance.as_ref().unwrap().value, 0.003); - for (bad, why) in [ - (ok.replace("0.003", "0"), "positive"), - (ok.replace("max_abs_error_over_max_abs_reference", "ulp"), "metric"), - (ok.replace("order-only difference", " "), "basis"), - (ok.replace("2026-10-28T10:00:00Z", "2026-10-28T20:00:00Z"), "after the reference run"), - ] { - let leaked: &'static str = Box::leak(bad.into_boxed_str()); - let d = TempDir::new(); - build(&d.0, &[Spec { gu: 42, down: 42, rows: 1, tolerance: Some(leaked) }], |_| {}); - let e = verify_dir(&d.0).unwrap_err(); - assert_eq!(e.file, "manifest.json"); - assert!(e.reason.contains(why), "{why}: {e}"); - } - } - - #[test] - fn the_json_reader_handles_the_manifest_forms_and_refuses_the_rest() { - let j = parse_json(b"{\"a\": [1, -2.5e3, true, null, \"x\\n\\u00e9\\ud83d\\ude00\"], \"b\": {}}").unwrap(); - assert_eq!( - j.get("a"), - Some(&Json::Arr(vec![ - Json::Num("1".into()), - Json::Num("-2.5e3".into()), - Json::Bool(true), - Json::Null, - Json::Str("x\n\u{e9}\u{1f600}".into()) - ])) - ); - assert_eq!(parse_json(b"{\"s\": 18446744073709551615}").unwrap().uint("s").unwrap(), u64::MAX); - for bad in [ - "{\"a\": 1, \"a\": 2}", - "{\"a\": 1,}", - "[1 2]", - "{\"a\": \"\\ud800\"}", - "{} x", - "", - "{\"a\": 01x}", - "\"\u{1}\"", - ] { - assert!(parse_json(bad.as_bytes()).is_err(), "{bad}"); - } - assert!(parse_json("[".repeat(40).as_bytes()).is_err()); - } - - #[test] - fn bitwise_compare_sees_signed_zero_and_one_ulp_and_tolerance_is_normalised() { - let a = [1.0f32.to_bits(), 0.0f32.to_bits(), 2.0f32.to_bits()]; - assert!(compare_bits(&a, &a, None).equal()); - let neg0 = [1.0f32.to_bits(), (-0.0f32).to_bits(), 2.0f32.to_bits()]; - let o = compare_bits(&neg0, &a, None); - assert_eq!((o.mismatches, o.first_mismatch), (1, Some((1, (-0.0f32).to_bits(), 0.0f32.to_bits())))); - let ulp = [1.0f32.to_bits(), 0.0f32.to_bits(), 2.0f32.to_bits() + 1]; - assert_eq!(compare_bits(&ulp, &a, None).mismatches, 1); - let tol = Tolerance { value: 1e-6, basis: "test".into(), basis_written_utc: "2026-01-01T00:00:00Z".into() }; - assert!(compare_bits(&ulp, &a, Some(&tol)).equal()); - let far = [1.0f32.to_bits(), 0.0f32.to_bits(), 2.1f32.to_bits()]; - assert_eq!(compare_bits(&far, &a, Some(&tol)).mismatches, 1); - assert_eq!(compare_bits(&a[..2], &a, None).mismatches, 1); - } - - #[test] - fn our_trees_run_on_a_verified_synthetic_case_and_the_record_is_well_formed() { - let t = TempDir::new(); - build(&t.0, &one_case(), |_| {}); - let v = verify_dir(&t.0).unwrap(); - let case = read_case_in(&v.dir, &v.cases[0]).unwrap(); - let mut pool = DirectCpuPool::new(1).unwrap(); - let first = compute_case(&mut pool, &case).unwrap(); - let second = compute_case(&mut pool, &case).unwrap(); - assert_eq!(first.len(), H); - assert!( - first.iter().zip(&second).all(|(a, b)| a.to_bits() == b.to_bits()), - "the same case twice must be bit-identical" - ); - let path = t.0.join("ours.rust-avx2.out"); - write_out(&path, 1, "avx2", &first).unwrap(); - let back = read_out(&path, "ours.rust-avx2.out", 1, "avx2", None).unwrap(); - assert_eq!(back, first.iter().map(|v| v.to_bits()).collect::>()); - let outcome = compare_bits(&back, &back, None); - let json = record_json(&RecordInput { - record_id: "kab1-synthetic-r".into(), - created_utc: "2026-10-28T20:00:00Z".into(), - run_started_utc: "2026-10-28T19:59:00Z".into(), - machine_role: "m\"1".into(), - cpu_model: "cpu".into(), - os: "os".into(), - ours_compiler: "rustc".into(), - ours_version: "rustc 1.99.0".into(), - ours_triple: "x86_64-unknown-linux-gnu".into(), - ours_flags: "f".into(), - tree: "avx2", - verified: &v, - case: &v.cases[0], - pin_cpu: 0, - sibling_idle: true, - outcome: &outcome, - }); - let rec = parse_json(json.as_bytes()).unwrap(); - 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(), "{key}"); - } - assert_eq!(rec.req("equality").unwrap().str("verdict").unwrap(), "EQUAL"); - assert_eq!(rec.req("machine").unwrap().str("machine_role").unwrap(), "m\"1"); - 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()), - ("STRATA_POOL_SPIN_US".to_owned(), "0".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", "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 ")); - } - - #[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); - // 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] - 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 - 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(); - 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"); - // 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; - 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"); - assert_eq!(utc_of(1_782_000_000), "2026-06-21T00:00:00Z"); - assert!(is_utc(&now_utc())); - } -} +mod tests; mod gate_up_row_fn; #[allow(unused_imports)] diff --git a/crates/native-cpu-expert/examples/kernel_ab/tests.rs b/crates/native-cpu-expert/examples/kernel_ab/tests.rs new file mode 100644 index 00000000..c72a8784 --- /dev/null +++ b/crates/native-cpu-expert/examples/kernel_ab/tests.rs @@ -0,0 +1,189 @@ +//! Tests of the KAB1 reader, the comparison, the record writer, the alternation runner and the timing mode; the +//! synthetic KAB1 directories they read are built here. +use super::*; +use std::sync::atomic::{AtomicUsize, Ordering}; + +mod alternation; +mod reader; +mod timing; + +static COUNTER: AtomicUsize = AtomicUsize::new(0); + +struct TempDir(PathBuf); +impl TempDir { + fn new() -> Self { + let p = std::env::temp_dir().join(format!( + "kab1-test-{}-{}", + std::process::id(), + COUNTER.fetch_add(1, Ordering::SeqCst) + )); + fs::create_dir_all(&p).unwrap(); + Self(p) + } +} +impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +/// The keys every COMPONENT_KERNEL record carries. +const RECORD_KEYS: [&str; 19] = [ + "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", +]; +/// The provenance block of the synthetic manifest. +const PROVENANCE: &str = "{\"engine_strata_pin\": \"41cf05a06a25dd29103b7b27a2279a3f60c21876\", \ + \"compiler_id\": \"GNU\", \"compiler_version\": \"15.2.0\", \"target_triple\": \"x86_64-linux-gnu\", \ + \"built_at_utc\": \"2026-10-28T19:05:05Z\", \"avx512_ok\": true, \"flags\": {\"strata_cxx_flags\": \ + \"-O3 -DNDEBUG\", \"ggml_cpu_arch_flags\": \"-march=native\"}}"; + +fn assert_record_keys(rec: &Json, prefix: &str) { + for key in RECORD_KEYS { + assert!(rec.get(key).is_some(), "{prefix}{key}"); + } +} + +fn block_filled(len: usize, block: usize, seed: u8) -> Vec { + let mut v: Vec = (0..len).map(|i| (i as u8).wrapping_mul(31).wrapping_add(seed)).collect(); + for at in (0..len).step_by(block) { + v[at] = 0x00; + v[at + 1] = 0x3c; // FP16 1.0 + } + v +} + +fn in_file(gu: i32, down: i32, rows: usize) -> Vec { + let (gq, gb) = (gate_up_row(gu).unwrap().2, gate_up_row(gu).unwrap().3); + let (dq, db) = (down_row(down).unwrap().2, down_row(down).unwrap().3); + let (gsize, dsize) = (H / gq * gb * FF, FF / dq * db * H); + let mut b = Vec::new(); + for w in [ + IN_MAGIC, + 1, + gu as u32, + down as u32, + rows as u32, + H as u32, + FF as u32, + gsize as u32, + gsize as u32, + dsize as u32, + ] { + b.extend_from_slice(&w.to_le_bytes()); + } + b.resize(IN_HEADER, 0); + b.extend(block_filled(gsize, gb, 1)); + b.extend(block_filled(gsize, gb, 2)); + b.extend(block_filled(dsize, db, 3)); + for i in 0..rows * H { + b.extend_from_slice(&(((i % 97) as f32 - 48.0) / 16.0).to_bits().to_le_bytes()); + } + b +} + +fn out_file(rows: usize, tree: u32) -> Vec { + let mut b = Vec::new(); + for w in [OUT_MAGIC, 1, rows as u32, H as u32, tree] { + b.extend_from_slice(&w.to_le_bytes()); + } + for i in 0..rows * H { + b.extend_from_slice(&((i as f32) * 0.25).to_bits().to_le_bytes()); + } + b +} + +struct Spec { + gu: i32, + down: i32, + rows: usize, + tolerance: Option<&'static str>, +} + +/// The manifest entry of a case up to its input file (the output files follow). +fn case_entry(s: &Spec, id: &str, inb: &[u8]) -> String { + format!( + "{{\"id\": \"{id}\", \"gu_type\": {}, \"down_type\": {}, \"rows\": {}, \"seed\": 18446744073709551615, \ + \"equality\": \"{}\", \"tolerance\": {}, \"in\": \"case-{id}.in\", \"in_sha256\": \"{}\", \"in_bytes\": {}", + s.gu, + s.down, + s.rows, + if s.tolerance.is_some() { "tolerance" } else { "bitwise" }, + s.tolerance.unwrap_or("null"), + sha_hex(inb), + inb.len() + ) +} + +/// Writes the C++ output of every tree of a case and adds them to its manifest entry and to the file list. +fn write_outs(dir: &Path, id: &str, rows: usize, entry: &mut String, files: &mut Vec) { + for (k, tree) in TREES.iter().enumerate() { + let ob = out_file(rows, k as u32); + fs::write(dir.join(format!("case-{id}.cpp-{tree}.out")), &ob).unwrap(); + *entry += &format!( + ", \"out_cpp_{tree}\": \"case-{id}.cpp-{tree}.out\", \"out_cpp_{tree}_sha256\": \"{}\", \ + \"out_cpp_{tree}_bytes\": {}", + sha_hex(&ob), + ob.len() + ); + files.push(format!( + "\"case-{id}.cpp-{tree}.out\": {{\"sha256\": \"{}\", \"bytes\": {}}}", + sha_hex(&ob), + ob.len() + )); + } +} + +/// Writes a case and returns its manifest entry; `mutate` edits the `.in` bytes before the manifest records their hash. +fn write_case(dir: &Path, s: &Spec, mutate: &impl Fn(&mut Vec), files: &mut Vec) -> String { + let id = format!("{}-{}-r{}", s.gu, s.down, s.rows); + let mut inb = in_file(s.gu, s.down, s.rows); + mutate(&mut inb); + fs::write(dir.join(format!("case-{id}.in")), &inb).unwrap(); + let mut entry = case_entry(s, &id, &inb); + files.push(format!("\"case-{id}.in\": {{\"sha256\": \"{}\", \"bytes\": {}}}", sha_hex(&inb), inb.len())); + write_outs(dir, &id, s.rows, &mut entry, files); + entry + "}" +} + +/// Builds a synthetic KAB1 directory; `mutate` edits the `.in` bytes before the manifest records their hash. +fn build(dir: &Path, specs: &[Spec], mutate: impl Fn(&mut Vec)) { + let mut files = Vec::new(); + let cases: Vec = specs.iter().map(|s| write_case(dir, s, &mutate, &mut files)).collect(); + let manifest = format!( + "{{\"format\": \"KAB1\", \"version\": 1, \"run_id\": \"synthetic\", \"writer\": \"cpp\", \ + \"provenance\": {PROVENANCE}, \"cases\": [{}], \"files\": {{{}}}}}", + cases.join(", "), + files.join(", ") + ); + fs::write(dir.join("manifest.json"), manifest).unwrap(); +} + +fn two_cases() -> Vec { + vec![Spec { gu: 42, down: 42, rows: 2, tolerance: None }, Spec { gu: 18, down: 20, rows: 1, tolerance: None }] +} + +fn one_case() -> Vec { + vec![Spec { gu: 42, down: 42, rows: 1, tolerance: None }] +} + +fn id(file: &str) -> String { + format!("case-42-42-r1.{file}") +} diff --git a/crates/native-cpu-expert/examples/kernel_ab/tests/alternation.rs b/crates/native-cpu-expert/examples/kernel_ab/tests/alternation.rs new file mode 100644 index 00000000..9492953b --- /dev/null +++ b/crates/native-cpu-expert/examples/kernel_ab/tests/alternation.rs @@ -0,0 +1,149 @@ +//! The alternation runner (STRA-318): the schedule, its file, and the scrubbed environment of the cells. +use super::*; + +/// The test the environment test starts in a child process (`--exact`). +const PROBE_CHILD: &str = "tests::alternation::env_probe_child"; +/// The test the failure test starts in a child process (`--exact`). +const FAILING_CHILD: &str = "tests::alternation::failing_child"; + +#[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 +} + +/// Only the variables of the cell survive in a child that was planted with Strata and Leleka variables. +fn only_the_cell_survives(cell: &[(String, String)]) { + let planted = [("STRATA_X", "planted"), ("LELEKA_Y", "planted"), ("strata_lower", "planted")]; + let out = run_cell(&mut child(PROBE_CHILD, "probe", &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", "STRATA_POOL_SPIN_US=0"], + "only the cell's variables survive:\n{text}" + ); +} + +#[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()), + ("STRATA_POOL_SPIN_US".to_owned(), "0".to_owned()) + ] + ); + assert!(cell_env(&Proc { imp: Impl::Cpp, tree: "avx512", rep: 'b' }).is_empty()); + only_the_cell_survives(&cell); + // the cpp avx512 cell sets nothing at all + let mut cpp = child(PROBE_CHILD, "probe", &[("STRATA_X", "planted")], &[]); + let out = run_cell(&mut cpp, "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(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}"); +} diff --git a/crates/native-cpu-expert/examples/kernel_ab/tests/reader.rs b/crates/native-cpu-expert/examples/kernel_ab/tests/reader.rs new file mode 100644 index 00000000..c796b5e2 --- /dev/null +++ b/crates/native-cpu-expert/examples/kernel_ab/tests/reader.rs @@ -0,0 +1,283 @@ +//! The KAB1 reader: the rule that refuses the whole directory, the JSON reader, the comparison and our trees. +use super::*; + +#[test] +fn a_good_directory_verifies() { + let t = TempDir::new(); + build(&t.0, &two_cases(), |_| {}); + let v = verify_dir(&t.0).unwrap(); + assert_eq!(v.cases.len(), 2); + assert_eq!(v.file_count, 2 * 3 + 1); + assert_eq!(v.manifest_sha256.len(), 64); + assert_eq!(v.cases[0].in_sha256, sha_hex(&fs::read(t.0.join("case-42-42-r2.in")).unwrap())); +} + +#[test] +fn a_flipped_byte_refuses_the_directory_and_names_the_file() { + let t = TempDir::new(); + build(&t.0, &one_case(), |_| {}); + let p = t.0.join(id("in")); + let mut b = fs::read(&p).unwrap(); + b[IN_HEADER + 7] ^= 0x40; + fs::write(&p, b).unwrap(); + let e = verify_dir(&t.0).unwrap_err(); + assert_eq!(e.file, "case-42-42-r1.in"); + assert!(e.reason.contains("sha256"), "{e}"); +} + +#[test] +fn a_truncated_file_refuses_the_directory_and_names_the_file() { + let t = TempDir::new(); + build(&t.0, &one_case(), |_| {}); + let p = t.0.join(id("cpp-avx2.out")); + let b = fs::read(&p).unwrap(); + fs::write(&p, &b[..b.len() - 4]).unwrap(); + let e = verify_dir(&t.0).unwrap_err(); + assert_eq!(e.file, "case-42-42-r1.cpp-avx2.out"); + assert!(e.reason.contains("length"), "{e}"); +} + +#[test] +fn a_wrong_magic_is_refused() { + let t = TempDir::new(); + build(&t.0, &one_case(), |b| b[0] ^= 0xff); + let e = verify_dir(&t.0).unwrap_err(); + assert_eq!(e.file, "case-42-42-r1.in"); + assert!(e.reason.contains("magic"), "{e}"); +} + +#[test] +fn a_wrong_version_is_refused() { + let t = TempDir::new(); + build(&t.0, &one_case(), |b| b[4] = 2); + let e = verify_dir(&t.0).unwrap_err(); + assert_eq!(e.file, "case-42-42-r1.in"); + assert!(e.reason.contains("version"), "{e}"); +} + +#[test] +fn a_byte_count_that_disagrees_with_the_format_is_refused() { + let t = TempDir::new(); + build(&t.0, &one_case(), |b| { + let wrong = (le32(b, 28) + 18).to_le_bytes(); + b[28..32].copy_from_slice(&wrong); + }); + let e = verify_dir(&t.0).unwrap_err(); + assert_eq!(e.file, "case-42-42-r1.in"); + assert!(e.reason.contains("format-derived"), "{e}"); +} + +#[test] +fn a_non_finite_fp16_header_is_refused() { + let t = TempDir::new(); + // the manifest records the hash of the mutated file, so only the FP16 rule can refuse it + build(&t.0, &one_case(), |b| { + let at = IN_HEADER + 18 * 3; + b[at] = 0x00; + b[at + 1] = 0x7c; // FP16 +inf + }); + let e = verify_dir(&t.0).unwrap_err(); + assert_eq!(e.file, "case-42-42-r1.in"); + assert!(e.reason.contains("non-finite FP16"), "{e}"); +} + +#[test] +fn a_non_finite_activation_is_refused() { + let t = TempDir::new(); + build(&t.0, &one_case(), |b| { + let at = b.len() - 4; + b[at..].copy_from_slice(&f32::NAN.to_bits().to_le_bytes()); + }); + let e = verify_dir(&t.0).unwrap_err(); + assert!(e.reason.contains("non-finite activation"), "{e}"); +} + +#[test] +fn a_missing_manifest_is_incomplete_and_named() { + let t = TempDir::new(); + build(&t.0, &one_case(), |_| {}); + fs::remove_file(t.0.join("manifest.json")).unwrap(); + let e = verify_dir(&t.0).unwrap_err(); + assert_eq!(e.file, "manifest.json"); + assert!(e.incomplete); + assert!(e.to_string().contains("manifest.json")); +} + +#[test] +fn an_extra_or_missing_file_refuses_the_directory() { + let t = TempDir::new(); + build(&t.0, &one_case(), |_| {}); + fs::write(t.0.join("stray.txt"), b"x").unwrap(); + assert_eq!(verify_dir(&t.0).unwrap_err().file, "stray.txt"); + fs::remove_file(t.0.join("stray.txt")).unwrap(); + fs::remove_file(t.0.join(id("cpp-avx512.out"))).unwrap(); + assert_eq!(verify_dir(&t.0).unwrap_err().file, "case-42-42-r1.cpp-avx512.out"); +} + +/// A case whose input header says its gate bytes are 4 GiB - 16, in a directory of its own. +fn lying_header_directory() -> TempDir { + let t = TempDir::new(); + build(&t.0, &one_case(), |b| b[28..32].copy_from_slice(&(u32::MAX - 15).to_le_bytes())); + t +} + +/// The manifest cases of a synthetic directory. +fn manifest_cases(dir: &Path) -> Vec { + let (_, cases, _) = parse_manifest(&parse_json(&fs::read(dir.join("manifest.json")).unwrap()).unwrap()).unwrap(); + cases +} + +/// Through the file reader: manifest and file agree on a file whose header lies about its size, and a manifest that +/// declares an absurd length for a file is refused before a buffer too. +fn lying_header_through_the_reader() { + let t = lying_header_directory(); + BUFFERS.with(|c| c.set(0)); + let cases = manifest_cases(&t.0); + let e = read_case_in(&t.0, &cases[0]).err().unwrap(); + assert!(e.reason.contains("format-derived"), "{e}"); + assert_eq!(BUFFERS.with(Cell::get), 0, "a buffer was taken before the header was validated"); + let mut lying = cases[0].clone(); + lying.in_bytes = u64::MAX; + assert!(read_case_in(&t.0, &lying).unwrap_err().reason.contains("differs from the manifest")); + assert_eq!(BUFFERS.with(Cell::get), 0); +} + +#[test] +fn an_absurd_length_is_refused_without_taking_a_buffer() { + // header says gate_bytes = 4 GiB - 16; the pure header check refuses it before any buffer exists + let mut h = [0u8; IN_HEADER]; + h.copy_from_slice(&in_file(42, 42, 1)[..IN_HEADER]); + h[28..32].copy_from_slice(&(u32::MAX - 15).to_le_bytes()); + BUFFERS.with(|c| c.set(0)); + assert!(validate_in_header(&h, 1 << 20).unwrap_err().contains("format-derived")); + assert_eq!(BUFFERS.with(Cell::get), 0); + lying_header_through_the_reader(); + // the good path takes exactly one buffer per file + let g = TempDir::new(); + build(&g.0, &one_case(), |_| {}); + BUFFERS.with(|c| c.set(0)); + read_case_in(&g.0, &manifest_cases(&g.0)[0]).unwrap(); + assert_eq!(BUFFERS.with(Cell::get), 1); +} + +#[test] +fn a_tolerance_needs_basis_metric_and_a_time_before_the_reference_run() { + let ok = "{\"value\": 0.003, \"metric\": \"max_abs_error_over_max_abs_reference\", \"basis\": \"order-only \ + difference\", \"basis_written_utc\": \"2026-10-28T10:00:00Z\"}"; + let t = TempDir::new(); + build(&t.0, &[Spec { gu: 42, down: 42, rows: 1, tolerance: Some(ok) }], |_| {}); + let v = verify_dir(&t.0).unwrap(); + assert_eq!(v.cases[0].tolerance.as_ref().unwrap().value, 0.003); + for (bad, why) in [ + (ok.replace("0.003", "0"), "positive"), + (ok.replace("max_abs_error_over_max_abs_reference", "ulp"), "metric"), + (ok.replace("order-only difference", " "), "basis"), + (ok.replace("2026-10-28T10:00:00Z", "2026-10-28T20:00:00Z"), "after the reference run"), + ] { + let leaked: &'static str = Box::leak(bad.into_boxed_str()); + let d = TempDir::new(); + build(&d.0, &[Spec { gu: 42, down: 42, rows: 1, tolerance: Some(leaked) }], |_| {}); + let e = verify_dir(&d.0).unwrap_err(); + assert_eq!(e.file, "manifest.json"); + assert!(e.reason.contains(why), "{why}: {e}"); + } +} + +#[test] +fn the_json_reader_handles_the_manifest_forms_and_refuses_the_rest() { + let j = parse_json(b"{\"a\": [1, -2.5e3, true, null, \"x\\n\\u00e9\\ud83d\\ude00\"], \"b\": {}}").unwrap(); + assert_eq!( + j.get("a"), + Some(&Json::Arr(vec![ + Json::Num("1".into()), + Json::Num("-2.5e3".into()), + Json::Bool(true), + Json::Null, + Json::Str("x\n\u{e9}\u{1f600}".into()) + ])) + ); + assert_eq!(parse_json(b"{\"s\": 18446744073709551615}").unwrap().uint("s").unwrap(), u64::MAX); + for bad in [ + "{\"a\": 1, \"a\": 2}", + "{\"a\": 1,}", + "[1 2]", + "{\"a\": \"\\ud800\"}", + "{} x", + "", + "{\"a\": 01x}", + "\"\u{1}\"", + ] { + assert!(parse_json(bad.as_bytes()).is_err(), "{bad}"); + } + assert!(parse_json("[".repeat(40).as_bytes()).is_err()); +} + +#[test] +fn bitwise_compare_sees_signed_zero_and_one_ulp_and_tolerance_is_normalised() { + let a = [1.0f32.to_bits(), 0.0f32.to_bits(), 2.0f32.to_bits()]; + assert!(compare_bits(&a, &a, None).equal()); + let neg0 = [1.0f32.to_bits(), (-0.0f32).to_bits(), 2.0f32.to_bits()]; + let o = compare_bits(&neg0, &a, None); + assert_eq!((o.mismatches, o.first_mismatch), (1, Some((1, (-0.0f32).to_bits(), 0.0f32.to_bits())))); + let ulp = [1.0f32.to_bits(), 0.0f32.to_bits(), 2.0f32.to_bits() + 1]; + assert_eq!(compare_bits(&ulp, &a, None).mismatches, 1); + let tol = Tolerance { value: 1e-6, basis: "test".into(), basis_written_utc: "2026-01-01T00:00:00Z".into() }; + assert!(compare_bits(&ulp, &a, Some(&tol)).equal()); + let far = [1.0f32.to_bits(), 0.0f32.to_bits(), 2.1f32.to_bits()]; + assert_eq!(compare_bits(&far, &a, Some(&tol)).mismatches, 1); + assert_eq!(compare_bits(&a[..2], &a, None).mismatches, 1); +} + +/// Runs the first case of a verified directory twice on one pool; the output of the first call. +fn run_case_twice(v: &Verified) -> Vec { + let case = read_case_in(&v.dir, &v.cases[0]).unwrap(); + let mut pool = DirectCpuPool::new(1).unwrap(); + let first = compute_case(&mut pool, &case).unwrap(); + let second = compute_case(&mut pool, &case).unwrap(); + assert_eq!(first.len(), H); + assert!( + first.iter().zip(&second).all(|(a, b)| a.to_bits() == b.to_bits()), + "the same case twice must be bit-identical" + ); + first +} + +/// The record of the comparison of our output with itself is well formed. +fn assert_synthetic_record(v: &Verified, outcome: &Outcome) { + let json = record_json(&RecordInput { + record_id: "kab1-synthetic-r".into(), + created_utc: "2026-10-28T20:00:00Z".into(), + run_started_utc: "2026-10-28T19:59:00Z".into(), + machine_role: "m\"1".into(), + cpu_model: "cpu".into(), + os: "os".into(), + ours_compiler: "rustc".into(), + ours_version: "rustc 1.99.0".into(), + ours_triple: "x86_64-unknown-linux-gnu".into(), + ours_flags: "f".into(), + tree: "avx2", + verified: v, + case: &v.cases[0], + pin_cpu: 0, + sibling_idle: true, + outcome, + }); + let rec = parse_json(json.as_bytes()).unwrap(); + assert_record_keys(&rec, ""); + assert_eq!(rec.req("equality").unwrap().str("verdict").unwrap(), "EQUAL"); + assert_eq!(rec.req("machine").unwrap().str("machine_role").unwrap(), "m\"1"); + assert_eq!(rec.str("kab1_manifest_sha256").unwrap(), v.manifest_sha256); +} + +#[test] +fn our_trees_run_on_a_verified_synthetic_case_and_the_record_is_well_formed() { + let t = TempDir::new(); + build(&t.0, &one_case(), |_| {}); + let v = verify_dir(&t.0).unwrap(); + let first = run_case_twice(&v); + let path = t.0.join("ours.rust-avx2.out"); + write_out(&path, 1, "avx2", &first).unwrap(); + let back = read_out(&path, "ours.rust-avx2.out", 1, "avx2", None).unwrap(); + assert_eq!(back, first.iter().map(|v| v.to_bits()).collect::>()); + assert_synthetic_record(&v, &compare_bits(&back, &back, None)); +} diff --git a/crates/native-cpu-expert/examples/kernel_ab/tests/timing.rs b/crates/native-cpu-expert/examples/kernel_ab/tests/timing.rs new file mode 100644 index 00000000..9ceddb89 --- /dev/null +++ b/crates/native-cpu-expert/examples/kernel_ab/tests/timing.rs @@ -0,0 +1,373 @@ +//! The timing mode (STRA-318): the command lines, the statistics helpers, the process JSON and the round records. +use super::*; + +/// Command line words from one space-separated line. +fn words(line: &str) -> Vec { + line.split_whitespace().map(str::to_owned).collect() +} + +#[test] +fn the_time_command_line_is_the_one_of_kab_time() { + let t = parse_time_args(&words("--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 all = "--run-dir D --case c --slices 2 --pin 0 --out o --slice-ms 5 --regime streamed --llc-bytes 1000"; + let t = parse_time_args(&words(all)).unwrap(); + assert_eq!((t.slice_ms, t.regime, t.llc_bytes), (5.0, RegimeSel::Streamed, Some(1000))); + time_command_line_refusals(); + let a = parse_alt_args(&words("--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(&words("--run-dir D --case c --rounds 30 --batch 0 --pin 9 --schedule s")).is_err()); +} + +fn time_command_line_refusals() { + for bad in [ + "--run-dir D --case c --slices 0 --pin 0 --out o", + "--run-dir D --case c --slices 1 --out o", + "--run-dir D --case c --slices 1 --pin 0 --out o --regime both2", + "--run-dir D --case ../c --slices 1 --pin 0 --out o", + "--run-dir D --case c --slices 1 --pin 0 --out o --bogus 1", + "--run-dir D --run-dir E --case c --slices 1 --pin 0 --out o", + ] { + assert!(parse_time_args(&words(bad)).is_err(), "{bad:?}"); + } +} + +#[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); + // 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] +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_slice(g1: f64) -> String { + 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}}" + ) +} + +fn json_regime(label: &str, k: usize, self_key: &str) -> String { + 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\": [{}]}}", + json_slice(5.0), + json_slice(5.1), + json_slice(4.0) + ) +} + +/// The `tree_detail` and the self-check key of a process JSON as the C++ writer (`imp` cpp) or this example writes it. +fn tree_detail(p: &Proc) -> (&'static str, String) { + 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 + ), + ) + } +} + +/// 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) = tree_detail(p); + 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) + ) +} + +/// A process JSON of the cell `p` parses, and the recorded drift, sibling and environment are checked. +fn assert_fixture_accepted(p: &Proc, env: &str, expect: &Expect) { + 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)); +} + +/// Wrong pin, wrong manifest, wrong input, wrong writer: each names the cell. +fn assert_fixture_refused(p: &Proc, env: &str, expect: &Expect) { + let bad_expects = [ + (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"), + ]; + for (bad_expect, what) in bad_expects { + 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")); +} + +#[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()); + assert_fixture_accepted(&p, &env, &expect); + // 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}"); + assert_fixture_refused(&p, &env, &expect); + } +} + +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()), + } +} + +fn outcome(bad: usize) -> Outcome { + Outcome { compared: H, mismatches: bad, differing_bits: bad, max_abs_error: 0.0, first_mismatch: None } +} + +fn rust_tool() -> Tool { + Tool { + compiler: "rustc".into(), + version: "rustc 1.99.0".into(), + triple: "x86_64-unknown-linux-gnu".into(), + flags: "f".into(), + } +} + +fn batch_ctx<'a>(v: &'a Verified, equality: &'a BTreeMap<&'static str, Outcome>) -> BatchCtx<'a> { + 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: rust_tool(), + batch: 2, + equality, + } +} + +/// Every process of the schedule, in the reverse order of execution; cpp-avx2-b saw a busy sibling. +fn finished_processes() -> Vec { + 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); + done +} + +/// One round record file: the schema shape, the verdict and the carried mismatch count. +fn assert_round_file(name: &str, json: &str, v: &Verified) { + let rec = parse_json(json.as_bytes()).unwrap_or_else(|e| panic!("{name}: {e}")); + assert_record_keys(&rec, &format!("{name}: ")); + 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"); + } +} + +fn record_of(files: &[(String, String)], name: &str) -> Json { + parse_json(files.iter().find(|f| f.0 == name).unwrap().1.as_bytes()).unwrap() +} + +/// 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, and the sibling belongs to the two processes of a record. +fn assert_slots(files: &[(String, String)]) { + let ab = record_of(files, "r00031.ab.avx512.resident.json"); + 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 = record_of(files, "r00031.aa-cpp.avx512.resident.json"); + 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}"); + } +} + +#[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 equality = BTreeMap::from([("avx512", outcome(0)), ("avx2", outcome(1835))]); + let ctx = batch_ctx(&v, &equality); + let done = finished_processes(); + 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 { + assert_round_file(name, json, &v); + } + assert_slots(&files); + assert_round_refusals(&ctx, &done); +} + +/// A streamed set that differs between the two sides of a record is refused, and so is a missing process. +fn assert_round_refusals(ctx: &BatchCtx<'_>, done: &[ProcOut]) { + let mut skewed = done.to_vec(); + 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")); +} + +/// The arguments of the Rust time mode on a synthetic directory (the paths may hold spaces). +fn rust_time_args(dir: &Path, file: &Path) -> Vec { + let mut args = words("--run-dir"); + args.push(dir.to_str().unwrap().to_owned()); + args.extend(words("--case 42-42-r1 --slices 40 --pin 0 --out")); + args.push(file.to_str().unwrap().to_owned()); + args.extend(words("--slice-ms 1 --llc-bytes 8000000")); + args +} + +/// The process JSON of the Rust time mode is accepted by the runner once its environment is the cell's. +fn assert_runner_accepts(t: &TempDir, text: &str, p: &Proc) { + 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 + let lie = parse_proc_json(p, as_cell.as_bytes(), &Expect { pin: 3, ..expect }); + assert!(lie.unwrap_err().contains("pinned to CPU")); +} + +#[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"); + // 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(&rust_time_args(&t.0, &file)).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)") { + assert_runner_accepts(&t, &text, &p); + } +} + +#[test] +fn utc_formatting_is_exact() { + assert_eq!(utc_of(0), "1970-01-01T00:00:00Z"); + assert_eq!(utc_of(1_782_000_000), "2026-06-21T00:00:00Z"); + assert!(is_utc(&now_utc())); +}