1361 lines
55 KiB
Rust
1361 lines
55 KiB
Rust
#![cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
|
// This file is its own lint gate: `cargo clippy -- -D warnings` also lints the other workspace crates, which carry warnings of their own.
|
|
#![deny(warnings, clippy::all)]
|
|
//! Rust half of the CPU kernel A/B, part 1 (STRA-289, S0.8b): the KAB1 reader, the comparison against the C++ reference outputs and
|
|
//! the COMPONENT_KERNEL record writer. The C++ driver (`tools/kernel-ab`, STRA-248) writes a run directory `D`; this example only
|
|
//! reads it. C++ and Rust meet through files: no FFI, no unsafe, public API of the crate only, no module in the production library.
|
|
//!
|
|
//! kernel_ab verify D the reader rule: manifest, every sha256 and length, header-derived sizes, finite
|
|
//! FP16 block headers and activations; any mismatch refuses the WHOLE directory
|
|
//! kernel_ab compare D [--out R] [--pin CPU] [--machine-role NAME] [--trees avx512,avx2]
|
|
//! verify D, run our trees in fresh processes (`run-tree`), compare with the C++
|
|
//! `.out` files (bitwise on the f32 bit patterns, or the tolerance the manifest case
|
|
//! declares with its basis), write `R/case-<id>.rust-<tree>.out` and one
|
|
//! COMPONENT_KERNEL record per case and tree to `R/records/`
|
|
//! 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 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
|
|
|
|
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::{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::sync::OnceLock;
|
|
use std::time::{Instant, SystemTime, UNIX_EPOCH};
|
|
|
|
thread_local! { static BUFFERS: Cell<usize> = const { Cell::new(0) }; }
|
|
|
|
fn main() -> ExitCode {
|
|
let args: Vec<String> = 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..]) {
|
|
Ok(o) => o,
|
|
Err(e) => {
|
|
eprintln!("kernel_ab: {e}");
|
|
return usage();
|
|
}
|
|
};
|
|
let result = match cmd.as_str() {
|
|
"verify" => match verify_dir(dir) {
|
|
Ok(v) => {
|
|
println!("OK {} files (manifest sha256 {})", v.file_count, v.manifest_sha256);
|
|
Ok(ExitCode::SUCCESS)
|
|
}
|
|
Err(e) => {
|
|
println!("{e}");
|
|
Ok(ExitCode::from(if e.incomplete { 2 } else { 1 }))
|
|
}
|
|
},
|
|
"compare" => cmd_compare(dir, &opts),
|
|
"run-tree" => match (&opts.tree, &opts.out) {
|
|
(Some(t), Some(o)) => cmd_run_tree(dir, t, o, opts.pin, opts.case.as_deref()),
|
|
_ => return usage(),
|
|
},
|
|
_ => return usage(),
|
|
};
|
|
result.unwrap_or_else(|e| {
|
|
eprintln!("kernel_ab: {e}");
|
|
ExitCode::from(1)
|
|
})
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------------ 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<u8> {
|
|
let mut v: Vec<u8> = (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<u8> {
|
|
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<u8> {
|
|
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<u8>)) {
|
|
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<Spec> {
|
|
vec![Spec { gu: 42, down: 42, rows: 2, tolerance: None }, Spec { gu: 18, down: 20, rows: 1, tolerance: None }]
|
|
}
|
|
|
|
fn one_case() -> Vec<Spec> {
|
|
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::<Vec<_>>());
|
|
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::<Vec<_>>(), 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::<Vec<_>>()
|
|
.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 <name> ... " 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::<Vec<_>>();
|
|
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<f64> = (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<ProcOut> =
|
|
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<String> = [
|
|
"--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 gate_up_row_fn;
|
|
#[allow(unused_imports)]
|
|
use gate_up_row_fn::civil_from_days;
|
|
#[allow(unused_imports)]
|
|
use gate_up_row_fn::down_row;
|
|
#[allow(unused_imports)]
|
|
use gate_up_row_fn::gate_up_row;
|
|
#[allow(unused_imports)]
|
|
use gate_up_row_fn::is_hex;
|
|
#[allow(unused_imports)]
|
|
use gate_up_row_fn::is_utc;
|
|
#[allow(unused_imports)]
|
|
use gate_up_row_fn::le32;
|
|
#[allow(unused_imports)]
|
|
use gate_up_row_fn::now_utc;
|
|
#[allow(unused_imports)]
|
|
use gate_up_row_fn::sha_hex;
|
|
#[allow(unused_imports)]
|
|
use gate_up_row_fn::take_buffer;
|
|
#[allow(unused_imports)]
|
|
use gate_up_row_fn::utc_of;
|
|
#[allow(unused_imports)]
|
|
use gate_up_row_fn::valid_id;
|
|
#[allow(unused_imports)]
|
|
use gate_up_row_fn::words_le;
|
|
mod impl_parser;
|
|
#[allow(unused_imports)]
|
|
use impl_parser::parse_json;
|
|
mod validate_in_header_fn;
|
|
#[allow(unused_imports)]
|
|
use validate_in_header_fn::case_files;
|
|
#[allow(unused_imports)]
|
|
use validate_in_header_fn::fp16_finite;
|
|
#[allow(unused_imports)]
|
|
use validate_in_header_fn::parse_manifest;
|
|
#[allow(unused_imports)]
|
|
use validate_in_header_fn::validate_in_header;
|
|
#[allow(unused_imports)]
|
|
use validate_in_header_fn::validate_out_header;
|
|
mod read_case_in_fn;
|
|
#[allow(unused_imports)]
|
|
use read_case_in_fn::compare_bits;
|
|
#[allow(unused_imports)]
|
|
use read_case_in_fn::jstr;
|
|
#[allow(unused_imports)]
|
|
use read_case_in_fn::read_case_in;
|
|
#[allow(unused_imports)]
|
|
use read_case_in_fn::read_manifest;
|
|
#[allow(unused_imports)]
|
|
use read_case_in_fn::read_out;
|
|
#[allow(unused_imports)]
|
|
use read_case_in_fn::record_json;
|
|
#[allow(unused_imports)]
|
|
use read_case_in_fn::verify_dir;
|
|
mod write_out_fn;
|
|
#[allow(unused_imports)]
|
|
use write_out_fn::cmd_run_tree;
|
|
#[allow(unused_imports)]
|
|
use write_out_fn::compute_case;
|
|
#[allow(unused_imports)]
|
|
use write_out_fn::cpu_model_of;
|
|
#[allow(unused_imports)]
|
|
use write_out_fn::family_of;
|
|
#[allow(unused_imports)]
|
|
use write_out_fn::host_os;
|
|
#[allow(unused_imports)]
|
|
use write_out_fn::parse_options;
|
|
#[allow(unused_imports)]
|
|
use write_out_fn::rustc_info;
|
|
#[allow(unused_imports)]
|
|
use write_out_fn::sibling_idle;
|
|
#[allow(unused_imports)]
|
|
use write_out_fn::write_out;
|
|
mod cmd_compare_fn;
|
|
#[allow(unused_imports)]
|
|
use cmd_compare_fn::cmd_compare;
|
|
#[allow(unused_imports)]
|
|
use cmd_compare_fn::core_ghz;
|
|
#[allow(unused_imports)]
|
|
use cmd_compare_fn::jnum;
|
|
#[allow(unused_imports)]
|
|
use cmd_compare_fn::median_of;
|
|
#[allow(unused_imports)]
|
|
use cmd_compare_fn::mono_ns;
|
|
#[allow(unused_imports)]
|
|
use cmd_compare_fn::parse_cpu_list;
|
|
#[allow(unused_imports)]
|
|
use cmd_compare_fn::parse_size;
|
|
#[allow(unused_imports)]
|
|
use cmd_compare_fn::percentile_of;
|
|
#[allow(unused_imports)]
|
|
use cmd_compare_fn::read_text;
|
|
mod llc_of_cpu_fn;
|
|
#[allow(unused_imports)]
|
|
use llc_of_cpu_fn::busy_fraction;
|
|
#[allow(unused_imports)]
|
|
use llc_of_cpu_fn::current_cpu;
|
|
#[allow(unused_imports)]
|
|
use llc_of_cpu_fn::is_managed_name;
|
|
#[allow(unused_imports)]
|
|
use llc_of_cpu_fn::json_env;
|
|
#[allow(unused_imports)]
|
|
use llc_of_cpu_fn::llc_of_cpu;
|
|
#[allow(unused_imports)]
|
|
use llc_of_cpu_fn::managed_env_now;
|
|
#[allow(unused_imports)]
|
|
use llc_of_cpu_fn::observed_threads;
|
|
#[allow(unused_imports)]
|
|
use llc_of_cpu_fn::parse_time_args;
|
|
#[allow(unused_imports)]
|
|
use llc_of_cpu_fn::proc_stat_cpu;
|
|
#[allow(unused_imports)]
|
|
use llc_of_cpu_fn::slice_json;
|
|
#[allow(unused_imports)]
|
|
use llc_of_cpu_fn::time_slice;
|
|
mod run_regime_fn;
|
|
#[allow(unused_imports)]
|
|
use run_regime_fn::f32_bits_sha;
|
|
#[allow(unused_imports)]
|
|
use run_regime_fn::run_regime;
|
|
mod cmd_time_fn;
|
|
#[allow(unused_imports)]
|
|
use cmd_time_fn::cmd_time;
|
|
mod impl_impl;
|
|
#[allow(unused_imports)]
|
|
use impl_impl::cell_env;
|
|
#[allow(unused_imports)]
|
|
use impl_impl::inside_git_checkout;
|
|
#[allow(unused_imports)]
|
|
use impl_impl::make_schedule;
|
|
#[allow(unused_imports)]
|
|
use impl_impl::parse_regime;
|
|
#[allow(unused_imports)]
|
|
use impl_impl::parse_schedule;
|
|
#[allow(unused_imports)]
|
|
use impl_impl::procs_for;
|
|
#[allow(unused_imports)]
|
|
use impl_impl::run_cell;
|
|
#[allow(unused_imports)]
|
|
use impl_impl::schedule_text;
|
|
#[allow(unused_imports)]
|
|
use impl_impl::scrubbed_command;
|
|
#[allow(unused_imports)]
|
|
use impl_impl::splitmix;
|
|
mod describe_cpp_tree_fn;
|
|
#[allow(unused_imports)]
|
|
use describe_cpp_tree_fn::aa_outcome;
|
|
#[allow(unused_imports)]
|
|
use describe_cpp_tree_fn::describe_cpp_tree;
|
|
#[allow(unused_imports)]
|
|
use describe_cpp_tree_fn::equality_block;
|
|
#[allow(unused_imports)]
|
|
use describe_cpp_tree_fn::parse_proc_json;
|
|
#[allow(unused_imports)]
|
|
use describe_cpp_tree_fn::side_stat;
|
|
#[allow(unused_imports)]
|
|
use describe_cpp_tree_fn::stat_json;
|
|
#[allow(unused_imports)]
|
|
use describe_cpp_tree_fn::tool_json;
|
|
mod round_records_fn;
|
|
#[allow(unused_imports)]
|
|
use round_records_fn::aa_equality_block;
|
|
#[allow(unused_imports)]
|
|
use round_records_fn::create_new_file;
|
|
#[allow(unused_imports)]
|
|
use round_records_fn::file_sha;
|
|
#[allow(unused_imports)]
|
|
use round_records_fn::ours_flags;
|
|
#[allow(unused_imports)]
|
|
use round_records_fn::parse_alt_args;
|
|
#[allow(unused_imports)]
|
|
use round_records_fn::round_records;
|
|
mod cmd_alternate_fn;
|
|
#[allow(unused_imports)]
|
|
use cmd_alternate_fn::cmd_alternate;
|
|
#[allow(unused_imports)]
|
|
use cmd_alternate_fn::usage;
|
|
|
|
mod in_magic_types;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::ALIGN;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::CHAIN_STEP_CYCLES;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::CLOCK_METHOD;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::CLOCK_MOVED_FRACTION;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::CaseEntry;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::CaseIn;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::DEFAULT_SLICE_MS;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::DOWN;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::FF;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::FileTable;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::Flags;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::GATE_UP;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::H;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::IN_HEADER;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::IN_MAGIC;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::InHeader;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::Json;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::Llc;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::MAX_CASES;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::MAX_FILE_BYTES;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::MAX_MANIFEST_BYTES;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::MAX_ROWS;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::NOT_MEASURED;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::OUT_HEADER;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::OUT_MAGIC;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::Options;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::OutRef;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::Outcome;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::Parser;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::Provenance;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::RecordInput;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::Refusal;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::RegimeSel;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::SIBLING_BUSY_LIMIT;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::TOLERANCE_METRIC;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::TREES;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::Tolerance;
|
|
#[allow(unused_imports)]
|
|
use in_magic_types::Verified;
|
|
mod time_args_types;
|
|
#[allow(unused_imports)]
|
|
use time_args_types::ALT_FLAGS;
|
|
#[allow(unused_imports)]
|
|
use time_args_types::AltArgs;
|
|
#[allow(unused_imports)]
|
|
use time_args_types::Arena;
|
|
#[allow(unused_imports)]
|
|
use time_args_types::BatchCtx;
|
|
#[allow(unused_imports)]
|
|
use time_args_types::Expect;
|
|
#[allow(unused_imports)]
|
|
use time_args_types::Impl;
|
|
#[allow(unused_imports)]
|
|
use time_args_types::Kind;
|
|
#[allow(unused_imports)]
|
|
use time_args_types::Numbered;
|
|
#[allow(unused_imports)]
|
|
use time_args_types::Proc;
|
|
#[allow(unused_imports)]
|
|
use time_args_types::ProcOut;
|
|
#[allow(unused_imports)]
|
|
use time_args_types::RegimeRun;
|
|
#[allow(unused_imports)]
|
|
use time_args_types::RegimeSpec;
|
|
#[allow(unused_imports)]
|
|
use time_args_types::RegimeStat;
|
|
#[allow(unused_imports)]
|
|
use time_args_types::SCHEDULE_MAGIC;
|
|
#[allow(unused_imports)]
|
|
use time_args_types::SideStat;
|
|
#[allow(unused_imports)]
|
|
use time_args_types::Slice;
|
|
#[allow(unused_imports)]
|
|
use time_args_types::TIME_FLAGS;
|
|
#[allow(unused_imports)]
|
|
use time_args_types::TimeArgs;
|
|
#[allow(unused_imports)]
|
|
use time_args_types::Timed;
|
|
#[allow(unused_imports)]
|
|
use time_args_types::Tool;
|