374 lines
17 KiB
Rust
374 lines
17 KiB
Rust
//! 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<String> {
|
|
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<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_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<ProcOut> {
|
|
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);
|
|
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<String> {
|
|
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()));
|
|
}
|